Skip to Content

Using feature flags in CodeIgniter 4 (supashiphq/php-sdk)

Register Supaship\SupaClient in app/Config/Services.php as a shared service, keep a single fallback map for all flag names, and optionally run a filter before controllers to updateContext with the signed-in user (for targeting and rollouts).

Prerequisites: PHP SDK overviewcomposer require supashiphq/php-sdk, Server SDK key.

1. Environment variables

In .env:

supaship.sdkKey = "your-sdk-key" supaship.environment = "production"

2. Centralized flag fallbacks

Create app/Config/SupashipFeatures.php (or inline the array inside Services):

<?php namespace Config; class SupashipFeatures { /** @return array<string, mixed> */ public static function fallbacks(): array { return [ 'new-ui' => false, 'theme-config' => [ 'primaryColor' => '#007bff', 'darkMode' => false, ], ]; } }

3. Services registration (shared SupaClient)

In app/Config/Services.php:

<?php namespace Config; use CodeIgniter\Config\BaseService; use Supaship\SupaClient; class Services extends BaseService { public static function supaship(bool $getShared = true): SupaClient { if ($getShared) { return static::getSharedInstance('supaship'); } return new SupaClient([ 'sdkKey' => getenv('supaship.sdkKey') ?: '', 'environment' => getenv('supaship.environment') ?: 'production', 'features' => SupashipFeatures::fallbacks(), 'context' => [ 'ciEnv' => ENVIRONMENT, ], ]); } }

4. Filter for per-request context

Example app/Filters/SupashipContext.php:

<?php namespace App\Filters; use CodeIgniter\Filters\FilterInterface; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; use Config\Services; class SupashipContext implements FilterInterface { public function before(RequestInterface $request, $arguments = null) { $client = Services::supaship(); $session = session(); if ($session->get('userId')) { $client->updateContext([ 'userId' => (string) $session->get('userId'), ]); } } public function after( RequestInterface $request, ResponseInterface $response, $arguments = null, ) { } }

Register the filter in app/Config/Filters.php for routes or route groups that need user-aware flag evaluation.

5. Controller usage

<?php namespace App\Controllers; use CodeIgniter\Controller; use Config\Services; class Home extends Controller { public function index() { $features = Services::supaship(); $data = [ 'new_ui' => $features->getFeature('new-ui'), 'theme' => $features->getFeature('theme-config'), ]; return view('home', $data); } }
Last updated on