Middleware
Actions can return a list of middleware from middleware(). The dispatcher
runs global middleware first, then the action's own middleware, then
handle().
use BradieTilley\Actions\Action;
use BradieTilley\Actions\Middleware\RunWithinTransaction;
class CreateInvoice extends Action
{
public function middleware(): array
{
return [
RunWithinTransaction::class,
];
}
public function handle(): Invoice
{
//
}
}
Custom middleware should implement BradieTilley\Actions\Contracts\ActionMiddleware:
use BradieTilley\Actions\Contracts\Actionable;
use BradieTilley\Actions\Contracts\ActionMiddleware;
use Closure;
class LogAction implements ActionMiddleware
{
public function handle(Actionable $action, Closure $next): mixed
{
logger()->info($action::class);
return $next($action);
}
}
Global middleware
use BradieTilley\Actions\Facades\Action;
Action::prependGlobalMiddleware(LogAction::class);
Action::appendGlobalMiddleware(RunWithinTransaction::class);
Action::getGlobalMiddleware();
Action::flushGlobalMiddleware();
Built-in middleware
| Class | Purpose |
|---|---|
RunWithinTransaction | Wrap the action in DB::transaction() (::attempts(n)) |
RunWithoutExceptions | Catch throwables, optionally report(), optional rescue closure |
RunWithoutOverlapping | Cache lock; returns false if the lock is not acquired |
RefreshReturnedModel | Call refresh() when handle() returns an Eloquent model |
use BradieTilley\Actions\Middleware\RunWithoutOverlapping;
use BradieTilley\Actions\Middleware\RunWithoutExceptions;
public function middleware(): array
{
return [
RunWithoutOverlapping::make('actions:create-invoice', seconds: 30),
RunWithoutExceptions::make()->report(false)->rescue(fn () => null),
];
}
Continue to Faking.