LaraflareDocsFrameworkPackagesReleases13.x

Docs / Packages / Pennant

Pennant

Introduction

Pennant (@laraflare/pennant) is a simple and light-weight feature flag package - without the cruft. Feature flags enable you to incrementally roll out new application features with confidence, A/B test new interface designs, complement a trunk-based development strategy, and much more.

Note

Pennant's storage is asynchronous, so every method that reads or writes a feature's value (active, value, activate, and so on) returns a promise. The examples below await them.

Installation

First, install Pennant into your project using npm:

npm install @laraflare/pennant

Next, you should publish the Pennant configuration and migration files using the vendor:publish Artisan command:

npx artisan vendor:publish --provider="PennantServiceProvider"

Finally, you should run your application's database migrations. This will create a features table that Pennant uses to power its database driver:

npx artisan migrate

Configuration

After publishing Pennant's assets, its configuration file will be located at config/pennant.ts. This configuration file allows you to specify the default storage mechanism that will be used by Pennant to store resolved feature flag values.

Pennant includes support for storing resolved feature flag values in an in-memory array via the array driver. Or, Pennant can store resolved feature flag values persistently in a relational database via the database driver, which is the default storage mechanism used by Pennant. The default store is read from the PENNANT_STORE environment variable.

Defining Features

To define a feature, you may use the define method offered by the Feature facade. You will need to provide a name for the feature, as well as a closure that will be invoked to resolve the feature's initial value.

Typically, features are defined in a service provider using the Feature facade. The closure will receive the "scope" for the feature check. Most commonly, the scope is the currently authenticated user. In this example, we will define a feature for incrementally rolling out a new API to our application's users:

import { Lottery, ServiceProvider } from '@laraflare/framework';
import { Feature } from '@laraflare/pennant';
import type { User } from '../Models/User';

export class AppServiceProvider extends ServiceProvider {
  /**
   * Bootstrap any application services.
   */
  override boot(): void {
    Feature.define('new-api', (user: User) => {
      if (user.isInternalTeamMember()) return true;
      if (user.isHighTrafficCustomer()) return false;

      return Lottery.odds(1, 100);
    });
  }
}

As you can see, we have the following rules for our feature:

The first time the new-api feature is checked for a given user, the result of the closure will be stored by the storage driver. The next time the feature is checked against the same user, the value will be retrieved from storage and the closure will not be invoked.

For convenience, if a feature definition only returns a lottery, you may omit the closure completely:

Feature.define('site-redesign', Lottery.odds(1, 1000));

Class Based Features

Pennant also allows you to define class-based features. Unlike closure-based feature definitions, there is no need to register a class-based feature in a service provider. To create a class-based feature, you may invoke the pennant:feature Artisan command. By default, the feature class will be placed in your application's app/Features directory:

npx artisan pennant:feature NewApi

When writing a feature class, you only need to define a resolve method, which will be invoked to resolve the feature's initial value for a given scope. Again, the scope will typically be the currently authenticated user:

import { Lottery } from '@laraflare/framework';
import type { User } from '../Models/User';

export class NewApi {
  /**
   * Resolve the feature's initial value.
   */
  resolve(user: User): unknown {
    if (user.isInternalTeamMember()) return true;
    if (user.isHighTrafficCustomer()) return false;

    return Lottery.odds(1, 100);
  }
}

If you would like to manually resolve an instance of a class-based feature, you may invoke the instance method on the Feature facade:

import { Feature } from '@laraflare/pennant';
import { NewApi } from '../Features/NewApi';

const instance = Feature.instance(NewApi);

Note

Feature classes are resolved via the container, so you may inject dependencies into the feature class's constructor when needed.

Customizing the Stored Feature Name

By default, Pennant will store the feature class's name. If you would like to decouple the stored feature name from the application's internal structure, you may add a static featureName property to the feature class. The value of this property will be stored in place of the class name:

export class NewApi {
  static featureName = 'new-api';

  // ...
}

Checking Features

To determine if a feature is active, you may use the active method on the Feature facade. By default, features are checked against the currently authenticated user:

import type { Request } from '@laraflare/framework';
import { Feature } from '@laraflare/pennant';

export class PodcastController {
  /**
   * Display a listing of the resource.
   */
  async index(request: Request) {
    return (await Feature.active('new-api'))
      ? this.resolveNewApiResponse(request)
      : this.resolveLegacyApiResponse(request);
  }

  // ...
}

Although features are checked against the currently authenticated user by default, you may easily check the feature against another user or scope. To accomplish this, use the for method offered by the Feature facade:

return (await Feature.for(user).active('new-api'))
  ? this.resolveNewApiResponse(request)
  : this.resolveLegacyApiResponse(request);

Pennant also offers some additional convenience methods that may prove useful when determining if a feature is active or not:

// Determine if all of the given features are active...
await Feature.allAreActive(['new-api', 'site-redesign']);

// Determine if any of the given features are active...
await Feature.someAreActive(['new-api', 'site-redesign']);

// Determine if a feature is inactive...
await Feature.inactive('new-api');

// Determine if all of the given features are inactive...
await Feature.allAreInactive(['new-api', 'site-redesign']);

// Determine if any of the given features are inactive...
await Feature.someAreInactive(['new-api', 'site-redesign']);

Note

When using Pennant outside of an HTTP context, such as in an Artisan command or a queued job, you should typically explicitly specify the feature's scope. Alternatively, you may define a default scope that accounts for both authenticated HTTP contexts and unauthenticated contexts.

Checking Class Based Features

For class-based features, you should provide the class when checking the feature:

import type { Request } from '@laraflare/framework';
import { Feature } from '@laraflare/pennant';
import { NewApi } from '../../Features/NewApi';

export class PodcastController {
  /**
   * Display a listing of the resource.
   */
  async index(request: Request) {
    return (await Feature.active(NewApi))
      ? this.resolveNewApiResponse(request)
      : this.resolveLegacyApiResponse(request);
  }

  // ...
}

Conditional Execution

The when method may be used to fluently execute a given closure if a feature is active. Additionally, a second closure may be provided and will be executed if the feature is inactive:

import type { Request } from '@laraflare/framework';
import { Feature } from '@laraflare/pennant';
import { NewApi } from '../../Features/NewApi';

export class PodcastController {
  /**
   * Display a listing of the resource.
   */
  async index(request: Request) {
    return Feature.when(NewApi,
      () => this.resolveNewApiResponse(request),
      () => this.resolveLegacyApiResponse(request),
    );
  }

  // ...
}

The unless method serves as the inverse of the when method, executing the first closure if the feature is inactive:

return Feature.unless(NewApi,
  () => this.resolveLegacyApiResponse(request),
  () => this.resolveNewApiResponse(request),
);

The HasFeatures Mixin

Pennant's HasFeatures mixin may be added to your application's User model (or any other model that has features) to provide a fluent, convenient way to check features directly from the model:

import { Authenticatable } from '@laraflare/framework';
import { HasFeatures } from '@laraflare/pennant';

export class User extends HasFeatures(Authenticatable) {
  // ...
}

Once the mixin has been added to your model, you may easily check features by invoking the features method:

if (await user.features().active('new-api')) {
  // ...
}

Of course, the features method provides access to many other convenient methods for interacting with features:

// Values...
const value = await user.features().value('purchase-button');
const values = await user.features().values(['new-api', 'purchase-button']);

// State...
await user.features().active('new-api');
await user.features().allAreActive(['new-api', 'server-api']);
await user.features().someAreActive(['new-api', 'server-api']);

await user.features().inactive('new-api');
await user.features().allAreInactive(['new-api', 'server-api']);
await user.features().someAreInactive(['new-api', 'server-api']);

// Conditional execution...
await user.features().when('new-api',
  () => { /* ... */ },
  () => { /* ... */ },
);

await user.features().unless('new-api',
  () => { /* ... */ },
  () => { /* ... */ },
);

Note

laraflare's screens are Vue, so Pennant has no template directives for them. Check a feature in a controller or route and pass the result to the screen as a prop.

Middleware

Pennant also includes a middleware that may be used to verify the currently authenticated user has access to a feature before a route is even invoked. You may assign the middleware to a route and specify the features that are required to access the route. If any of the specified features are inactive for the currently authenticated user, a 400 Bad Request HTTP response will be returned by the route. Multiple features may be passed to the static using method.

import { Route } from '@laraflare/framework';
import { EnsureFeaturesAreActive } from '@laraflare/pennant';

Route.get('/api/servers', () => {
  // ...
}).middleware(EnsureFeaturesAreActive.using('new-api', 'servers-api'));

Customizing the Response

If you would like to customize the response that is returned by the middleware when one of the listed features is inactive, you may use the whenInactive method provided by the EnsureFeaturesAreActive middleware. Typically, this method should be invoked within the boot method of one of your application's service providers:

import { Response, type Request } from '@laraflare/framework';
import { EnsureFeaturesAreActive } from '@laraflare/pennant';

/**
 * Bootstrap any application services.
 */
override boot(): void {
  EnsureFeaturesAreActive.whenInactive(
    (request: Request, features: string[]) => new Response('', 403),
  );

  // ...
}

Intercepting Feature Checks

Sometimes it can be useful to perform some in-memory checks before retrieving the stored value of a given feature. Imagine you are developing a new API behind a feature flag and want the ability to disable the new API without losing any of the resolved feature values in storage. If you notice a bug in the new API, you could easily disable it for everyone except internal team members, fix the bug, and then re-enable the new API for the users that previously had access to the feature.

You can achieve this with a class-based feature's before method. When present, the before method is always run in-memory before retrieving the value from storage. If a non-null value is returned from the method, it will be used in place of the feature's stored value for the duration of the request:

import { Config, Lottery } from '@laraflare/framework';
import type { User } from '../Models/User';

export class NewApi {
  /**
   * Run an always-in-memory check before the stored value is retrieved.
   */
  before(user: User): unknown {
    if (Config.get('features.new-api.disabled')) {
      return user.isInternalTeamMember();
    }

    return null;
  }

  /**
   * Resolve the feature's initial value.
   */
  resolve(user: User): unknown {
    if (user.isInternalTeamMember()) return true;
    if (user.isHighTrafficCustomer()) return false;

    return Lottery.odds(1, 100);
  }
}

You could also use this feature to schedule the global rollout of a feature that was previously behind a feature flag:

import { Carbon, Config } from '@laraflare/framework';
import type { User } from '../Models/User';

export class NewApi {
  /**
   * Run an always-in-memory check before the stored value is retrieved.
   */
  before(user: User): unknown {
    if (Config.get('features.new-api.disabled')) {
      return user.isInternalTeamMember();
    }

    if (Carbon.parse(Config.get('features.new-api.rollout-date')).isPast()) {
      return true;
    }

    return null;
  }

  // ...
}

In-Memory Cache

When checking a feature, Pennant will create an in-memory cache of the result. If you are using the database driver, this means that re-checking the same feature flag within a single request will not trigger additional database queries. This also ensures that the feature has a consistent result for the duration of the request.

If you need to manually flush the in-memory cache, you may use the flushCache method offered by the Feature facade:

Feature.flushCache();

Scope

Specifying the Scope

As discussed, features are typically checked against the currently authenticated user. However, this may not always suit your needs. Therefore, it is possible to specify the scope you would like to check a given feature against via the Feature facade's for method:

return (await Feature.for(user).active('new-api'))
  ? this.resolveNewApiResponse(request)
  : this.resolveLegacyApiResponse(request);

Of course, feature scopes are not limited to "users". Imagine you have built a new billing experience that you are rolling out to entire teams rather than individual users. Perhaps you would like the oldest teams to have a slower rollout than the newer teams. Your feature resolution closure might look something like the following:

import { Carbon, Lottery } from '@laraflare/framework';
import { Feature } from '@laraflare/pennant';
import type { Team } from '../Models/Team';

Feature.define('billing-v2', (team: Team) => {
  if (team.createdAt.isAfter(new Carbon('2023-01-01'))) {
    return true;
  }

  if (team.createdAt.isAfter(new Carbon('2019-01-01'))) {
    return Lottery.odds(1, 100);
  }

  return Lottery.odds(1, 1000);
});

You will notice that the closure we have defined is not expecting a User, but is instead expecting a Team model. To determine if this feature is active for a user's team, you should pass the team to the for method offered by the Feature facade:

if (await Feature.for(user.team).active('billing-v2')) {
  return redirect('/billing/v2');
}

// ...

Global Scope

To check or interact with a feature using a global scope, regardless of the configured default scope resolver, use the globally method. This is useful for application-wide feature flags, such as temporarily enabling maintenance behavior or rolling out a feature to every user:

await Feature.globally().active('new-api');

await Feature.globally().activate('new-api');

Default Scope

It is also possible to customize the default scope Pennant uses to check features. For example, maybe all of your features are checked against the currently authenticated user's team instead of the user. Instead of having to call Feature.for(user.team) every time you check a feature, you may instead specify the team as the default scope. Typically, this should be done in one of your application's service providers:

import { Auth, ServiceProvider } from '@laraflare/framework';
import { Feature } from '@laraflare/pennant';

export class AppServiceProvider extends ServiceProvider {
  /**
   * Bootstrap any application services.
   */
  override boot(): void {
    Feature.resolveScopeUsing(async (driver: string) => (await Auth.user())?.team);

    // ...
  }
}

If no scope is explicitly provided via the for method, the feature check will now use the currently authenticated user's team as the default scope:

await Feature.active('billing-v2');

// Is now equivalent to...

await Feature.for(user.team).active('billing-v2');

Nullable Scope

TypeScript's types are gone when the code runs, so Pennant cannot read a closure's parameter type to learn whether it accepts null. A feature closure is therefore always called, with null as the scope when there is none.

So, if the scope you are passing to a feature is potentially null, you should account for that in your feature's definition. A null scope may occur if you check a feature within an Artisan command, queued job, or unauthenticated route. Since there is usually not an authenticated user in these contexts, the default scope will be null.

If you do not always explicitly specify your feature scope then you should ensure the scope's type is "nullable" and handle the null scope value within your feature definition logic:

import { Lottery } from '@laraflare/framework';
import { Feature } from '@laraflare/pennant';
import type { User } from '../Models/User';

Feature.define('new-api', (user: User | null) => {
  if (user === null) return true;
  if (user.isInternalTeamMember()) return true;
  if (user.isHighTrafficCustomer()) return false;

  return Lottery.odds(1, 100);
});

If you would rather have Pennant skip a feature that cannot handle a null scope, and return false for it, set handlesNullScope = false on the closure or, for a class-based feature, as a static property on the class. When a null scope is skipped this way, the UnexpectedNullScopeEncountered event is dispatched.

Identifying Scope

Pennant's built-in array and database storage drivers know how to properly store scope identifiers for strings, numbers and models. However, if your application utilizes a third-party Pennant driver, that driver may not know how to properly store an identifier for a model or other custom types in your application.

In light of this, Pennant allows you to format scope values for storage by implementing the FeatureScopeable contract on the objects in your application that are used as Pennant scopes.

For example, imagine you are using two different feature drivers in a single application: the built-in database driver and a third-party "Flag Rocket" driver. The "Flag Rocket" driver does not know how to properly store a model. Instead, it requires a FlagRocketUser instance. By implementing the toFeatureIdentifier method defined by the FeatureScopeable contract, we can customize the storable scope value provided to each driver used by our application:

import { Model } from '@laraflare/framework';
import { FlagRocketUser } from 'flag-rocket';
import type { FeatureScopeable } from '@laraflare/pennant';

export class User extends Model implements FeatureScopeable {
  /**
   * Cast the object to a feature scope identifier for the given driver.
   */
  toFeatureIdentifier(driver: string): unknown {
    switch (driver) {
      case 'database':
        return this;
      case 'flag-rocket':
        return FlagRocketUser.fromId(this.flag_rocket_id);
    }
  }
}

Serializing Scope

By default, Pennant will use the class name when storing a feature associated with a model. If you are already using an Eloquent morph map, you may choose to have Pennant also use the morph map to decouple the stored feature from your application structure.

To achieve this, after defining your Eloquent morph map in a service provider, you may invoke the Feature facade's useMorphMap method:

import { Relation } from '@laraflare/framework';
import { Feature } from '@laraflare/pennant';
import { Post } from '../Models/Post';
import { Video } from '../Models/Video';

Relation.enforceMorphMap({
  post: Post,
  video: Video,
});

Feature.useMorphMap();

Rich Feature Values

Until now, we have primarily shown features as being in a binary state, meaning they are either "active" or "inactive", but Pennant also allows you to store rich values as well.

For example, imagine you are testing three new colors for the "Buy now" button of your application. Instead of returning true or false from the feature definition, you may instead return a string:

import { Arr } from '@laraflare/framework';
import { Feature } from '@laraflare/pennant';

Feature.define('purchase-button', (user: User) => Arr.random([
  'blue-sapphire',
  'seafoam-green',
  'tart-orange',
]));

You may retrieve the value of the purchase-button feature using the value method:

const color = await Feature.value('purchase-button');

Since the screens are Vue, pass the value to the screen as a prop and choose what to render there.

Note

When using rich values, it is important to know that a feature is considered "active" when it has any value other than false.

When calling the conditional when method, the feature's rich value will be provided to the first closure:

await Feature.when('purchase-button',
  (color) => { /* ... */ },
  () => { /* ... */ },
);

Likewise, when calling the conditional unless method, the feature's rich value will be provided to the optional second closure:

await Feature.unless('purchase-button',
  () => { /* ... */ },
  (color) => { /* ... */ },
);

Retrieving Multiple Features

The values method allows the retrieval of multiple features for a given scope:

await Feature.values(['billing-v2', 'purchase-button']);

// {
//     'billing-v2': false,
//     'purchase-button': 'blue-sapphire',
// }

Or, you may use the all method to retrieve the values of all defined features for a given scope:

await Feature.all();

// {
//     'billing-v2': false,
//     'purchase-button': 'blue-sapphire',
//     'site-redesign': true,
// }

However, class-based features are dynamically registered and are not known by Pennant until they are explicitly checked. This means your application's class-based features may not appear in the results returned by the all method if they have not already been checked during the current request.

If you would like to ensure that feature classes are always included when using the all method, you may use Pennant's feature discovery capabilities. Workers have no directory to scan, so you pass the feature classes to the discover method yourself, in one of your application's service providers:

import { ServiceProvider } from '@laraflare/framework';
import { Feature } from '@laraflare/pennant';
import { NewApi } from '../Features/NewApi';

export class AppServiceProvider extends ServiceProvider {
  /**
   * Bootstrap any application services.
   */
  override boot(): void {
    Feature.discover('App\\Features', [NewApi]);

    // ...
  }
}

The discover method will register the feature classes you give it. The all method will now include these classes in its results, regardless of whether they have been checked during the current request:

await Feature.all();

// {
//     'NewApi': true,
//     'billing-v2': false,
//     'purchase-button': 'blue-sapphire',
//     'site-redesign': true,
// }

Eager Loading

Although Pennant keeps an in-memory cache of all resolved features for a single request, it is still possible to encounter performance issues. To alleviate this, Pennant offers the ability to eager load feature values.

To illustrate this, imagine that we are checking if a feature is active within a loop:

import { Feature } from '@laraflare/pennant';

for (const user of users) {
  if (await Feature.for(user).active('notifications-beta')) {
    await user.notify(new RegistrationSuccess());
  }
}

Assuming we are using the database driver, this code will execute a database query for every user in the loop - executing potentially hundreds of queries. However, using Pennant's load method, we can remove this potential performance bottleneck by eager loading the feature values for a collection of users or scopes:

await Feature.for(users).load(['notifications-beta']);

for (const user of users) {
  if (await Feature.for(user).active('notifications-beta')) {
    await user.notify(new RegistrationSuccess());
  }
}

To load feature values only when they have not already been loaded, you may use the loadMissing method:

await Feature.for(users).loadMissing([
  'new-api',
  'purchase-button',
  'notifications-beta',
]);

You may load all defined features using the loadAll method:

await Feature.for(users).loadAll();

Updating Values

When a feature's value is resolved for the first time, the underlying driver will store the result in storage. This is often necessary to ensure a consistent experience for your users across requests. However, at times, you may want to manually update the feature's stored value.

To accomplish this, you may use the activate and deactivate methods to toggle a feature "on" or "off":

import { Feature } from '@laraflare/pennant';

// Activate the feature for the default scope...
await Feature.activate('new-api');

// Deactivate the feature for the given scope...
await Feature.for(user.team).deactivate('billing-v2');

It is also possible to manually set a rich value for a feature by providing a second argument to the activate method:

await Feature.activate('purchase-button', 'seafoam-green');

To instruct Pennant to forget the stored value for a feature, you may use the forget method. When the feature is checked again, Pennant will resolve the feature's value from its feature definition:

await Feature.forget('purchase-button');

Bulk Updates

To update stored feature values in bulk, you may use the activateForEveryone and deactivateForEveryone methods.

For example, imagine you are now confident in the new-api feature's stability and have landed on the best 'purchase-button' color for your checkout flow - you can update the stored value for all users accordingly:

import { Feature } from '@laraflare/pennant';

await Feature.activateForEveryone('new-api');

await Feature.activateForEveryone('purchase-button', 'seafoam-green');

Alternatively, you may deactivate the feature for all users:

await Feature.deactivateForEveryone('new-api');

Note

This will only update the resolved feature values that have been stored by Pennant's storage driver. You will also need to update the feature definition in your application.

Purging Features

Sometimes, it can be useful to purge an entire feature from storage. This is typically necessary if you have removed the feature from your application or you have made adjustments to the feature's definition that you would like to rollout to all users.

You may remove all stored values for a feature using the purge method:

// Purging a single feature...
await Feature.purge('new-api');

// Purging multiple features...
await Feature.purge(['new-api', 'purchase-button']);

If you would like to purge all features from storage, you may invoke the purge method without any arguments:

await Feature.purge();

As it can be useful to purge features as part of your application's deployment pipeline, Pennant includes a pennant:purge Artisan command which will purge the provided features from storage:

npx artisan pennant:purge new-api

npx artisan pennant:purge new-api purchase-button

It is also possible to purge all features except those in a given feature list. For example, imagine you wanted to purge all features but keep the values for the "new-api" and "purchase-button" features in storage. To accomplish this, you can pass those feature names to the --except option:

npx artisan pennant:purge --except=new-api --except=purchase-button

For convenience, the pennant:purge command also supports an --except-registered flag. This flag indicates that all features except those explicitly registered in a service provider should be purged:

npx artisan pennant:purge --except-registered

Testing

When testing code that interacts with feature flags, the easiest way to control the feature flag's returned value in your tests is to simply re-define the feature. For example, imagine you have the following feature defined in one of your application's service provider:

import { Arr } from '@laraflare/framework';
import { Feature } from '@laraflare/pennant';

Feature.define('purchase-button', () => Arr.random([
  'blue-sapphire',
  'seafoam-green',
  'tart-orange',
]));

To modify the feature's returned value in your tests, you may re-define the feature at the beginning of the test. The following test will always pass, even though the Arr.random() implementation is still present in the service provider:

import assert from 'node:assert/strict';
import { test } from 'node:test';
import { Feature } from '@laraflare/pennant';

test('it can control feature values', async () => {
  Feature.define('purchase-button', 'seafoam-green');

  assert.equal(await Feature.value('purchase-button'), 'seafoam-green');
});

The same approach may be used for class-based features:

import assert from 'node:assert/strict';
import { test } from 'node:test';
import { Feature } from '@laraflare/pennant';
import { NewApi } from '../app/Features/NewApi';

test('it can control feature values', async () => {
  Feature.define(NewApi, true);

  assert.equal(await Feature.value(NewApi), true);
});

If your feature is returning a Lottery instance, there are a handful of useful testing helpers available.

Store Configuration

You may configure the store that Pennant will use during testing by defining the PENNANT_STORE environment variable in the environment your tests run with, such as your application's .env file:

PENNANT_STORE=array

Adding Custom Pennant Drivers

Implementing the Driver

If none of Pennant's existing storage drivers fit your application's needs, you may write your own storage driver. Your custom driver should implement the Driver interface:

import type { Driver, Resolver } from '@laraflare/pennant';

export class RedisFeatureDriver implements Driver {
  define(feature: string, resolver: Resolver): void {}
  defined(): string[] { return []; }
  async getAll(features: Record<string, unknown[]>): Promise<Record<string, unknown[]>> { return {}; }
  async get(feature: string, scope: unknown): Promise<unknown> { return null; }
  async set(feature: string, scope: unknown, value: unknown): Promise<void> {}
  async setForAllScopes(feature: string, value: unknown): Promise<void> {}
  async delete(feature: string, scope: unknown): Promise<void> {}
  async purge(features: string[] | null): Promise<void> {}
}

Now, we just need to implement each of these methods using a Redis connection. For an example of how to implement each of these methods, take a look at the DatabaseDriver in @laraflare/pennant (packages/pennant/src/Drivers/DatabaseDriver.ts).

Note

laraflare does not ship with a directory to contain your extensions. You are free to place them anywhere you like. In this example, we have created an Extensions directory to house the RedisFeatureDriver.

Registering the Driver

Once your driver has been implemented, you are ready to register it with laraflare. To add additional drivers to Pennant, you may use the extend method provided by the Feature facade. You should call the extend method from the boot method of one of your application's service provider:

import { ServiceProvider } from '@laraflare/framework';
import { Feature } from '@laraflare/pennant';
import { RedisFeatureDriver } from '../Extensions/RedisFeatureDriver';

export class AppServiceProvider extends ServiceProvider {
  /**
   * Register any application services.
   */
  override register(): void {
    // ...
  }

  /**
   * Bootstrap any application services.
   */
  override boot(): void {
    Feature.extend('redis', (config: Record<string, unknown>, name: string) => {
      return new RedisFeatureDriver();
    });
  }
}

Once the driver has been registered, you may use the redis driver in your application's config/pennant.ts configuration file:

stores: {

  redis: {
    driver: 'redis',
    connection: null,
  },

  // ...

},

Defining Features Externally

If your driver is a wrapper around a third-party feature flag platform, you will likely define features on the platform rather than using Pennant's Feature.define method. If that is the case, your custom driver should also implement the DefinesFeaturesExternally interface:

import type { DefinesFeaturesExternally, Driver } from '@laraflare/pennant';

export class FeatureFlagServiceDriver implements Driver, DefinesFeaturesExternally {
  /**
   * Get the features defined for the given scope.
   */
  definedFeaturesForScope(scope: unknown): string[] { return []; }

  /* ... */
}

The definedFeaturesForScope method should return a list of feature names defined for the provided scope.

Events

Pennant dispatches a variety of events that can be useful when tracking feature flags throughout your application. Each is exported from @laraflare/pennant.

FeatureRetrieved

This event is dispatched whenever a feature is checked. This event may be useful for creating and tracking metrics against a feature flag's usage throughout your application.

FeatureResolved

This event is dispatched the first time a feature's value is resolved for a specific scope.

UnknownFeatureResolved

This event is dispatched the first time an unknown feature is resolved for a specific scope. Listening to this event may be useful if you have intended to remove a feature flag but have accidentally left stray references to it throughout your application:

import { Event, Log, ServiceProvider } from '@laraflare/framework';
import { UnknownFeatureResolved } from '@laraflare/pennant';

export class AppServiceProvider extends ServiceProvider {
  /**
   * Bootstrap any application services.
   */
  override boot(): void {
    Event.listen(UnknownFeatureResolved, (event: UnknownFeatureResolved) => {
      Log.error(`Resolving unknown feature [${event.feature}].`);
    });
  }
}

DynamicallyRegisteringFeatureClass

This event is dispatched when a class-based feature is dynamically checked for the first time during a request.

UnexpectedNullScopeEncountered

This event is dispatched when a null scope is passed to a feature definition that doesn't support null.

This situation is handled gracefully and the feature will return false. However, if you would like to opt out of this feature's default graceful behavior, you may register a listener for this event in the boot method of your application's AppServiceProvider:

import { abort, Event } from '@laraflare/framework';
import { UnexpectedNullScopeEncountered } from '@laraflare/pennant';

/**
 * Bootstrap any application services.
 */
override boot(): void {
  Event.listen(UnexpectedNullScopeEncountered, () => abort(500));
}

FeatureUpdated

This event is dispatched when updating a feature for a scope, usually by calling activate or deactivate.

FeatureUpdatedForAllScopes

This event is dispatched when updating a feature for all scopes, usually by calling activateForEveryone or deactivateForEveryone.

FeatureDeleted

This event is dispatched when deleting a feature for a scope, usually by calling forget.

FeaturesPurged

This event is dispatched when purging specific features.

AllFeaturesPurged

This event is dispatched when purging all features.

Adapted from Laravel's documentation, Copyright (c) Taylor Otwell, used under the MIT License.