andrewdyer / auth-gate
A framework-agnostic PHP library for defining and enforcing authorisation rules through a simple, expressive gate interface
Requires
- php: ^8.3
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.75
- phpunit/phpunit: ^10.5
README
Built on top of andrewdyer/php-package-template
Auth Gate
A framework-agnostic PHP library for defining and enforcing authorisation rules through a simple, expressive gate interface.
Introduction
This library provides a lightweight, dependency-free mechanism for registering ability callbacks and evaluating them against an authenticated actor — the user performing the action. It supports before-hooks for global overrides, multiple ability checks, and throws a typed exception when authorisation fails, making it straightforward to integrate into any PHP application regardless of framework.
Prerequisites
Installation
composer require andrewdyer/auth-gate
Getting Started
1. Implement the actor
Any class that represents an authenticated actor must implement the Authenticatable interface. This is the object that will be evaluated against your defined abilities.
use AndrewDyer\Gate\Contracts\Authenticatable; class User implements Authenticatable { public function __construct( public readonly int $id, public readonly bool $admin = false, ) {} public function isAdmin(): bool { return $this->admin; } }
2. Create a Gate instance
Instantiate the Gate with the authenticated actor. This instance will be used to define and evaluate abilities.
use AndrewDyer\Gate\Gate; $actor = new User(id: 1); $gate = new Gate($actor);
Usage
The following examples demonstrate the available gate operations using the setup above.
Defining Abilities
Abilities are registered via the define method, which accepts an ability name and a callback that returns a boolean.
$gate->define('edit-post', function ($actor, $post) { return $actor->id === $post->authorId; });
Checking Abilities
Use allows and denies to evaluate a single ability, or all and any for multiple abilities.
$gate->allows('edit-post', $post); // true or false $gate->denies('edit-post', $post); // true or false $gate->all(['edit-post', 'delete-post'], $post); // true if all pass $gate->any(['edit-post', 'view-post'], $post); // true if any pass
Authorising Actions
authorize throws an UnauthorizedException if the actor lacks any of the given abilities.
use AndrewDyer\Gate\UnauthorizedException; try { $gate->authorize(['edit-post'], $post); } catch (UnauthorizedException $e) { // Actor is not authorised }
Registering Before Callbacks
Before callbacks run prior to all ability checks. Returning true or false short-circuits the evaluation; returning null (or nothing) defers to the defined ability.
$gate->before(function ($actor, $ability) { if ($actor->isAdmin()) { return true; } });
License
Licensed under the MIT license and is free for private or commercial projects.