# flagbearer for PHP

The PHP SDK for Flagbearer. Requires PHP 8.1 or later with the curl, json and
mbstring extensions.

## Install

```sh
composer require flagbearer/flagbearer
```

## Keys

Use a server key, which starts with `fbs_`. Server keys are secret: read them
from the environment, such as `FLAGBEARER_SERVER_KEY`, and never put them in
browser code or in the repository. Browsers use client keys, which start with
`fbc_`, through [`@flagbearer/web`](/sdks/web).

## Pick a cache

Pass a cache shared between requests with the `cache` option. It accepts any
[PSR-16](https://www.php-fig.org/psr/psr-16/) cache:

- **APCu or Redis** in production, through any PSR-16 adapter, such as
  `symfony/cache` (`Psr16Cache` around `ApcuAdapter` or `RedisAdapter`) or
  Laravel's cache store.
- **`Flagbearer\Cache\FileCache`** when neither is available.
- **`Flagbearer\Cache\MemoryCache`**, the default, only for long-running
  workers such as RoadRunner, Swoole or FrankenPHP's worker mode. Under PHP-FPM,
  always pass a shared cache.

## Check per request

Create the client once per request, or once per worker, and check flags with
the user and a default:

```php
use Flagbearer\Cache\FileCache;
use Flagbearer\Client;
use Flagbearer\Options;

$flags = Client::create(getenv('FLAGBEARER_SERVER_KEY'), new Options(
    cache: new FileCache(sys_get_temp_dir() . '/flagbearer'),
));

$user = ['key' => $currentUser->id, 'email' => $currentUser->email];
if ($flags->isEnabled('advanced-search', $user, false)) {
    // …
}
```

The default is used until the client has synced, and when the flag doesn't
exist. The user can also be a `Flagbearer\User`. The email is optional. Include it to turn flags on for testers by email.

Long-running workers that keep one client across requests should call
`$flags->flush()` after each request.

### Laravel

Register the client as a singleton in a service provider, using Laravel's cache
(Redis, Memcached or APCu are best):

```php
namespace App\Providers;

use Flagbearer\Client;
use Flagbearer\Options;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\ServiceProvider;

class FlagbearerServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(Client::class, fn () => Client::create(
            config('services.flagbearer.key'),
            new Options(cache: Cache::store()),
        ));
    }
}
```

```php
public function search(Request $request, Client $flags)
{
    $user = ['key' => (string) $request->user()->id, 'email' => $request->user()->email];
    $advanced = $flags->isEnabled('advanced-search', $user, false);
    // …
}
```

Laravel's cache store implements PSR-16, so it can be passed directly. Add
`'flagbearer' => ['key' => env('FLAGBEARER_SERVER_KEY')]` to
`config/services.php`.
