Extensions
An extension adds behavior to every resource of an application from one class: a tenant restriction, field rules per plan, a quota on writes, a line in the meta of each page. The class extends Lomkit\Rest\Extensions\Extension and implements one or more kinds, the interfaces of Lomkit\Rest\Extensions\Kinds, each of which extends ExtensionKind.
use Lomkit\Rest\Extensions\Contexts\RestrictionContext;
use Lomkit\Rest\Extensions\Extension;
use Lomkit\Rest\Extensions\Kinds\RestrictsQueries;
final class ArchiveExtension extends Extension implements RestrictsQueries
{
public function __construct(private readonly ArchivePolicy $policy) {}
#[\Override]
public static function name(): string
{
return 'archive';
}
#[\Override]
public function appliesTo(string $resource): bool
{
return is_subclass_of($resource, ArchivableResource::class);
}
#[\Override]
public function restrict(RestrictionContext $context): void
{
if (! $this->policy->showsArchived($context->user)) {
$context->query->where($context->query->qualifyColumn('archived'), false);
}
}
}
The methods of the resources stay the path of the application. Extensions apply after them, and their order never changes the result.
The name
name() is the one abstract method of Extension. It returns the name of the extension:
- The name is a public contract. It is the meta key (
meta.archiveof searches and/details) and the prefix of the instruction keys, response components, cache keys and SQL aliases that the extension adds. A package picks a name specific to it and keeps it for its whole major version. - A name has 1 to 32 lowercase letters or digits, starts with a letter and joins words with single underscores, such as
aclorrow_lock. Two underscores separate it from the keys it prefixes (acl__locked), soacl__xandacl_are refused. - Return a constant. A
name()that returns an invalid name, or that throws, is refused withLomkit\Rest\Exceptions\InvalidExtensionException, which names the class and the value or the error. - A subclass inherits the name. Override it only to run the subclass beside its parent.
Registering an extension
An application lists its extension classes in config/rest.php:
'extensions' => [
App\Rest\Extensions\ArchiveExtension::class,
],
A package registers its classes from the register() method of a service provider, so they are active on install:
use Lomkit\Rest\Facades\Rest;
public function register(): void
{
Rest::registerExtension(AccessControlExtension::class);
}
Rest::registerExtensions([AccessControlExtension::class, TenantExtension::class]) registers several classes.
- Extensions are registered by class name. An instance passed to
registerExtension()is a PHPTypeError. An instance, a value that is not a string, or an array that is not a list inregisterExtensions()throwsInvalidExtensionException, which shows the list form[AccessControlExtension::class]. In the config, arest.extensionsorrest.disabled_extensionsvalue that is not a list throwsLomkit\Rest\Exceptions\InvalidConfigException, and an instance or a value that is not a string in the list throwsInvalidExtensionExceptionwhen a context first reads its extensions. Both name the config key. - A registration checks the class first: it exists, extends
Extensionand is not abstract. It then reads the name. A package author sees the error on install. The classes of the config get the same checks when a context first reads its extensions. - From
register(), a registration works in any provider order. Fromboot(), it works only before every provider that declaresRest::resource()routes in its ownboot(). - Runtime registrations are fixed once the application has booted, or earlier when the package builds its first context or registers its first
Rest::resource()route. A later registration throwsInvalidExtensionException, which names the class: never register from a deferred provider or abooted()callback. - The config is read again for each context: a request, a queued action,
Rest::search(), the OpenAPI document andrest:check. A config cached without theextensionskey reads as no extension. - One class counts once, registered twice or both registered by a package and listed in the config. Its origin is
configwhenrest.extensionslists it, elseruntime.
defineEnvironment() or #[DefineEnvironment], which run before the boot, or with #[WithConfig('rest.extensions', [...])]. A registration from a test body throws.Disabling or replacing an extension
disabled_extensions lists the classes to disable, wherever they come from:
'disabled_extensions' => [
Vendor\Acl\AccessControlExtension::class,
],
- A disabled class is never built, and its name never collides with another.
- The exact class is compared: a subclass stays enabled when its parent is disabled. A leading backslash or another letter case still designates the same class.
- To replace a package extension, extend it, list the subclass in
extensionsand the package class indisabled_extensions. The subclass inherits the name, so its meta and instruction keys stay the same. - Two enabled classes with one name are refused when a context builds its extensions, with a message that names both classes:
The extensions App\Rest\Extensions\AclExtension and Vendor\Acl\AccessControlExtension share the name [acl]. Add one of them to the [rest.disabled_extensions] config, or extend one of them and override name() to give it another name.A subclass listed beside its enabled parent is refused the same way.
How extensions run
- The container builds each extension once per context, at first use, so its constructor can inject services. With no extension, nothing is built.
- Keep settings in properties. For other settings, register a subclass with its own
name(), or with the parent indisabled_extensions. - Never bind an extension as a singleton: one instance would serve every context of an Octane or queue worker. Bind it with
bind(), or not at all. - Building an extension checks its class again: a class that implements no kind, or a binding that builds another class, throws
InvalidExtensionException. appliesTo(string $resource)returnstrueby default. Each context asks it once per resource class and keeps the answer, so it may read the resource class and the config, never the user or the request.- Each kind method receives one context object of
Lomkit\Rest\Extensions\Contexts. Each kind calls its extensions in name order, so the order of the config never shows. - An exception thrown by an extension reaches the caller, except from
ObservesWrites, whose exceptions are reported, and fromChecksResources, whose exceptions are problems ofrest:check.
Errors
Every error about an extension extends Lomkit\Rest\Exceptions\ExtensionException: catch that class for all of them. Each message names the extension by its name and its class, and concerns($class) tells whether an error is about that extension class:
use Lomkit\Rest\Exceptions\ExtensionException;
use Lomkit\Rest\Facades\Rest;
try {
$page = Rest::search(TicketResource::class)->as($user)->payload($search)->page();
} catch (ExtensionException $e) {
if (! $e->concerns(AccessControlExtension::class)) {
throw $e;
}
// ...
}
| Exception | Thrown by |
|---|---|
InvalidExtensionException | registration, names and building |
InvalidQueryExtensionException | the query kinds |
InvalidEngineExtensionException | the engine kinds |
InvalidAuthorizationExtensionException | the authorization kinds |
InvalidFieldExtensionException | NarrowsFields |
InvalidRouteExtensionException | AddsRouteMiddleware |
InvalidWriteExtensionException | GuardsWrites |
InvalidMetaExtensionException | AddsSearchMeta and AddsDetailsMeta |
InvalidDocumentationExtensionException | DocumentsExtension |
The kinds
| Family | Kind | What it does |
|---|---|---|
| Queries | RestrictsQueries | Adds where clauses to the perimeter of a resource, wherever the perimeter applies |
ProvidesPerimeter | Marks a restriction that is the perimeter, for rest:check | |
AugmentsQueries | Adds columns, subqueries and eager loads to the rendered rows, for the policies | |
NarrowsLimits | Narrows the page sizes, the total cap and the include limit for the user, never upward | |
DeclaresInstructions | Adds search instructions, keyed by the extension name | |
| Search engines | RestrictsEngineQueries | Restricts each search engine query, AND-ed with the perimeter and the client filters |
DeclaresIndexAttributes | Declares server-only index attributes, lists of strings included | |
ProvidesEngineProfiles | Provides the profile of a Scout engine | |
| Authorization | PreparesRowChecks | Prepares the data that the policies read, before a batch of row checks |
VersionsRowChecks | Adds row versions to the key of a kept decision | |
ContributesCacheContext | Adds items to the cache keys of decisions and metric results, shortens or drops kept decisions | |
DeclaresGates | Adds gates to a resource | |
NarrowsFields | Hides fields, or makes them read-only, unfilterable or unsortable, for the user | |
| Routes and writes | AddsRouteMiddleware | Adds middleware to the routes of an endpoint |
GuardsWrites | Refuses a write before it runs | |
ObservesWrites | Is notified after the commit of each write | |
ObservesReads | Is notified after each HTTP search, metric and /details | |
| Responses and checks | AddsSearchMeta | Adds keys under meta.{name} of a search page |
AddsDetailsMeta | Adds keys under meta.{name} of /details | |
DocumentsExtension | Documents the extension in the OpenAPI document | |
ChecksResources | Adds checks to rest:check |
Checking extensions
php artisan rest:check lists each extension with its name, class, origin (config or runtime) and disabled state, and builds each enabled one:
extensions ... 2 extensions built, 1 disabled
Vendor\Notes\NotingExtension ... runtime, disabled
acl ... Vendor\Acl\AccessControlExtension, runtime
quota ... App\Rest\Extensions\QuotaExtension, config
- The name of a disabled class is not read.
- It fails on a
rest.extensionsorrest.disabled_extensionsvalue that is not a list, on each refused entry, on each pair of classes with one name and on each class that cannot be built, and still lists the others. - It notes, without failing, a
disabled_extensionsentry that disables nothing: a class neither registered nor configured. --jsonadds theextensionskey:registered(name,class,origin,disabled),problemsandnotes.
See Extensions in rest:check and Extension checks.