aidan-casey / laravel-route-binding
为非控制器对象添加Laravel路由绑定。
v0.1.2
2022-05-25 20:57 UTC
Requires
- php: ^8.1
- illuminate/collections: ^9.0
- illuminate/routing: ^9.0
- illuminate/support: ^9.0
Requires (Dev)
- orchestra/testbench: ^7.5
- phpunit/phpunit: ^9.5
This package is not auto-updated.
Last update: 2024-09-13 00:02:02 UTC
README
此包受到Laravel中默认的路由绑定的很大影响。主要区别在于,此包将此类功能提取到可以在整个应用程序中使用的工具类。
此包还抵制使用Laravel容器来实例化对象(尽管使用Laravel容器解析依赖),这样此实用程序可以在Laravel服务提供者中使用而不会导致递归依赖查找。
安装
要安装,请运行
composer install aidan-casey/laravel-route-binding
用法
要构建一个带有路由参数的类并返回其实例,请使用静态make
方法。此方法接受一个额外的参数数组,如果您想覆盖任何值。
use AidanCasey\Laravel\RouteBinding\Binder; // Binds route parameters to the construct of the referenced class. $viewModel = Binder::make(IndexViewModel::class); // Overrides the "user" parameter. $viewModel = Binder::make(IndexViewModel::class, [ 'user' => 2, ]);
要将路由参数绑定到类的特定方法,请使用静态call
方法。您可以传递现有类实例或类字符串给此方法。
use AidanCasey\Laravel\RouteBinding\Binder; // Calls the "execute" method on "MyTestClass." Binder::call(MyTestClass::class, 'execute'); // Overrides the "user" parameter. Binder::call(MyTestClass::class, 'execute', [ 'user' => 2, ]); // Calls the "execute" method on the existing instance. $instance = new MyTestClass; Binder::call($instance, 'execute');
性能
此包广泛使用了反射类。建议您将结果绑定到容器,这样只会发生一次。这可以通过在Laravel服务提供者中使用beforeResolving
方法来完成。例如
use AidanCasey\Laravel\RouteBinding\Binder; use Illuminate\Support\ServiceProvider; class SomeServiceProvider extends ServiceProvider { public function register(){ $this->app->beforeResolving(MyClass::class, function ($class, $parameters, $app) { if ($app->has($class)) { return; } $app->bind($class, fn ($container) => Binder::make($class, $parameters)); }); } }