aidynmakhataev / laravel-attributes
使用 PHP 属性自动注册 Laravel 事件监听器、命令处理器和路由
1.0.1
2021-09-03 05:29 UTC
Requires
- php: ^8.0
- illuminate/bus: ^8.0
- illuminate/events: ^8.0
- illuminate/routing: ^8.0
Requires (Dev)
- orchestra/testbench: ^6.0
- phpunit/phpunit: ^9.5
- psalm/plugin-laravel: ^1.4.2
- vimeo/psalm: ^4.6.0
README
本软件包提供自动注册 Laravel 路由、事件监听器和命令总线处理器的 PHP 属性。
要求
- PHP ^8.0
- Laravel ^8.0
安装
您可以通过 composer 安装此软件包
composer require aidynmakhataev/laravel-attributes
您可以使用以下命令发布配置文件
php artisan vendor:publish --provider="AidynMakhataev\LaravelAttributes\LaravelAttributesServiceProvider" --tag="config"
这是发布配置文件的内容
return [ 'events' => [ /* * Automatic registration of listeners will only happen if this setting is `true` */ 'enabled' => true, /* * Listeners in these directories that have attributes will automatically be registered. */ 'directories' => [ base_path('app/Listeners') ] ], 'command_bus' => [ /* * Automatic registration of command handlers will only happen if this setting is `true` */ 'enabled' => true, /* * Handlers in these directories that have attributes will automatically be registered. */ 'directories' => [ base_path('app/CommandHandlers') ], ], 'routing' => [ /* * Automatic registration of routes will only happen if this setting is `true` */ 'enabled' => true, /* * Controllers in these directories that have attributes will automatically be registered. */ 'directories' => [ base_path('app/Http/Controllers') ], ], ];
用法
软件包提供了一些注解,应该放在您的函数上。
事件监听器
namespace App\Listeners; use AidynMakhataev\LaravelAttributes\Attributes\EventListener; use App\Events\OrderShipped; class SendShipmentNotification { #[EventListener] public function handle(OrderShipped $event) { // } }
此属性将自动通过执行以下命令注册此监听器
Event::listen(OrderShipped::class, 'SendShipmentNotification@handle');
命令处理器
namespace App\CommandHandlers; use AidynMakhataev\LaravelAttributes\Attributes\CommandHandler; use App\Events\OrderShipped; class CreateOrderCommandHandler { #[CommandHandler] public function handle(CreateOrderCommand $command) { // } }
此属性将自动通过执行以下命令注册此处理器
Bus::map([ CreateOrderCommand::class => CreateOrderCommandHandler::class, ]);
路由
namespace App\Http\Controllers; use AidynMakhataev\LaravelAttributes\Attributes\Route; use App\Events\OrderShipped; use Illuminate\Http\Request; class OrderController { #[Route(path: '/orders', methods: ['POST'], name: 'orders.store', middlewares: ['auth'])] public function store(Request $request) { // } }
此属性将自动通过执行以下命令注册此路由
Route::post('/orders', [OrderController::class, 'store'])->name('orders.store')->middlewares(['auth']);
测试
composer test
许可协议
MIT 许可协议 (MIT)。请参阅 许可文件 获取更多信息。