iak / action
Simple actions for Laravel
Fund package maintenance!
Isak Berglind
Requires
- php: ^8.2
- illuminate/contracts: ^11.0||^12.0
- spatie/laravel-package-tools: ^1.16
Requires (Dev)
- larastan/larastan: ^3.0
- laravel/pint: ^1.14
- mockery/mockery: ^1.6
- nunomaduro/collision: ^8.0
- orchestra/testbench: ^10.0
- pestphp/pest: ^3.0
- pestphp/pest-plugin-arch: ^3.0
- pestphp/pest-plugin-laravel: ^3.0
- phpstan/extension-installer: ^1.4
- phpstan/phpstan-deprecation-rules: ^2.0
- phpstan/phpstan-phpunit: ^2.0
README
A simple way to organize your business logic in Laravel applications.
While you can install this, I would encourage you to simply copy the action file and take ownership of it. The logic is not complicated, and it will allow you to add/remove/update the features you like.
Installation
composer require iak/action
Basic Usage
Creating an Action
<?php namespace App\Actions; use Iak\Action\Action; class SayHelloAction extends Action { public function handle() { return "Hello"; } }
Using an Action
<?php namespace App\Http\Controllers; use App\Actions\SayHelloAction; class HomeController extends Controller { public function index(SayHelloAction $action) { $result = $action->handle(); return response()->json($result); } }
Static Methods
Actions provide helpful static methods:
// Create an instance $action = SayHelloAction::make(); // Create a fake for testing $action = SayHelloAction::fake();
Events
Actions can emit and listen to events:
<?php namespace App\Actions; use Iak\Action\Action; use Iak\Action\EmitsEvents; #[EmitsEvents(['hello_said'])] class SayHelloAction extends Action { public function handle() { $result = "Hello"; $this->event('hello_said', $result); return $result; } }
Listen to events:
$action = SayHelloAction::make() ->on('hello_said', function ($result) { // Do something when hello is said Log::info("Hello said: {$result}"); }) ->handle();
Testing
<?php use App\Actions\SayHelloAction; it('says hello', function () { $result = SayHelloAction::make()->handle(); expect($result)->toBe('Hello'); }); it('can fake an action', function () { $action = SayHelloAction::fake(); expect($action)->toBeInstanceOf(MockInterface::class); });
Requirements
- PHP 8.2+
- Laravel 11.0+ or 12.0+
License
The MIT License (MIT). Please see License File for more information.
Contributing
Please see CONTRIBUTING for details.
Credits
Support
If you discover any issues or have questions, please open an issue.