michael-rubel / laravel-auto-binder
此软件包通过扫描指定的项目文件夹,增加了将接口绑定到实现类在服务容器中的功能。这有助于在项目需要将大量接口绑定到其实例时避免手动注册容器绑定。
Requires
- php: ^8.0
- illuminate/contracts: ^10.0|^11.0
- spatie/laravel-package-tools: ^1.9
Requires (Dev)
- brianium/paratest: ^6.3|^7.4
- infection/infection: ^0.27.10
- laravel/pint: ^1.1
- mockery/mockery: ^1.4.4
- nunomaduro/collision: ^7.0|^8.0
- nunomaduro/larastan: ^2.0
- orchestra/testbench: ^8.0|^9.0
- phpunit/phpunit: ^9.5.4|^10.5
README
Laravel Auto-Binder
此软件包通过扫描指定的项目文件夹,增加了将接口绑定到服务容器中具体类的功能。这有助于在项目需要将大量接口绑定到其实例时避免手动注册容器绑定。
该软件包需要 PHP 8
或更高版本以及 Laravel 9
或更高版本。
#StandWithUkraine
安装
使用 composer 安装该软件包
composer require michael-rubel/laravel-auto-binder
使用方法
在您的 ServiceProvider 中定义
AutoBinder::from(folder: 'Services') ->as('singleton') ->bind();
假设您的服务位于 App\Services
,其接口位于 App\Services\Interfaces
,则该软件包将注册每个类和接口对的绑定
$this->app->singleton(AuthServiceInterface::class, AuthService::class); $this->app->singleton(UserServiceInterface::class, UserService::class); $this->app->singleton(CompanyServiceInterface::class, CompanyService::class); ...
自定义
如果您需要自定义基本路径或命名空间,可以使用以下方法
AutoBinder::from(folder: 'Services') ->basePath('app/Domain') ->classNamespace('App\\Domain') ->interfaceNamespace('App\\Domain\\Interfaces') ->bind();
此配置将在 app/Domain/Services
文件夹中查找类,使用 App\\Domain
命名空间,并使用 ClassNameInterface
命名约定从 App\\Domain\\Interfaces
命名空间应用接口。
如果您需要更改接口的命名约定,可以指定您喜欢的命名空间和名称
AutoBinder::from(folder: 'Services') ->interfaceNaming('Contract') ->bind();
此配置将使用 App\\Services
命名空间扫描 app/Services
文件夹,使用 App\\Services\\Contracts
接口命名空间,以及 ClassNameContract
接口命名约定。
排除扫描的子文件夹
您也可以从根目录的扫描中排除子目录
AutoBinder::from(folder: 'Services') ->exclude('Traits', 'Components') ->bind();
依赖注入
如果您在扫描服务时想注入依赖项,可以使用 when
方法
AutoBinder::from(folder: 'Services') ->when(ExampleServiceInterface::class, function ($app, $service) { return new ExampleService($app); }) ->bind();
传递具体类和接口都是可能的,但请注意接口在应用依赖项时具有更高的优先级。
同时扫描多个文件夹
如果您传递多个文件夹,则 from
方法将返回一个 Illuminate/Support/Collection
实例。假设您这样做,您可以使用访问内部属性的 AutoBinder
类实例遍历。
例如
AutoBinder::from('Services', 'Models')->each( fn ($binder) => $binder->basePath('app') ->classNamespace('App\\Domain') ->interfaceNamespace("App\\Domain\\$binder->classFolder\\Interfaces") ->as('singleton') ->bind() );
缓存
该软件包将在应用程序引导过程中避免冗余文件夹扫描,将您的绑定缓存起来。
如果您想禁用缓存,可以在 AutoBinder 实例上使用 withoutCaching
方法,例如
AutoBinder::from(folder: 'Services') ->withoutCaching() ->as('singleton') ->bind();
您还可以使用 Artisan 命令清除特定文件夹的缓存
php artisan binder:clear Services,Models
请注意,对于该命令要生效,您应该使用在 from
方法中传递给 AutoBinder 实例的文件夹名称。此外,缓存将在 local
环境中忽略。
测试
composer test
许可证
MIT 许可证 (MIT)。有关更多信息,请参阅许可证文件。