eryw / pastry-bag
为 CakePHP 3 提供构造函数依赖注入和控制方法注入的插件
v1.0.1
2016-09-25 16:29 UTC
Requires
- aura/di: ^3.0
- cakephp/cakephp: >=3.2.0 <4.0
- cakephp/plugin-installer: *
Requires (Dev)
- phpunit/phpunit: 5.5.*
This package is not auto-updated.
Last update: 2024-09-26 03:24:39 UTC
README
CakePHP 3 的依赖注入插件。此插件提供了构造函数注入和控制方法注入。
安装
Composer
composer require eryw/pastry-bag=@stable
配置
将以下行添加到您的 config/bootstrap.php
Plugin::load('PastryBag', ['bootstrap' => true]);
对于带有调度过滤器的 CakePHP 3.2
替换 config/bootstrap.php
中的控制器工厂过滤器
DispatcherFactory::add('ControllerFactory');
为以下内容
DispatcherFactory::add('PastryBag\Routing\Filter\ControllerFactoryFilter');
对于带有中间件的 CakePHP 3.3
请在您的 Application
类中覆盖方法 getDispatcher()
class Application extends BaseApplication { // ... // protected function getDispatcher() { return new ActionDispatcher(new ControllerFactory(), null, DispatcherFactory::filters()); } }
为了使依赖注入生效,所有控制器都必须继承 PastryBag\Controller\Controller
。
因此,将您的 AppController
父类从 Cake\Controller\Controller
更改为 PastryBag\Controller\Controller
class AppController extends \PastryBag\Controller\Controller { // ... // }
使用方法
构造函数注入
class UsersController extends AppController { protected $payment; public function __construct(PaymentService $payment) { parent::__construct(); $this->payment = $payment; } public function payBill() { // `$this->payment` will auto injected with instance of PaymentService $this->payment->anyMethodOfPaymentService(); } }
控制方法注入
class RemoteGaleryController extends AppController { public function index($id, MyHttpClient $client) { // `$client` will auto injected with instance of MyHttpClient $client->request('GET', 'http://remotesite.com'); } }
注意
只有类型提示的参数会自动注入。
配置
此插件使用 Aura.Di 作为容器。配置应放在实现 Aura\Di\ContainerConfigInterface
的类中,配置列表(类名或实例)必须放在 config/container_configs.php
中
config/container_configs.php
的示例内容
use Aura\Di\Container; use Aura\Di\ContainerConfig; use Cake\ORM\TableRegistry; // OPTIONAL. You can move this class to other file if you want class DiConfig extends ContainerConfig { public function define(Container $di) { $di->set(\App\Model\Table\UsersTable::class, $di->lazy(function () { return TableRegistry::get('Users'); })); $di->types[\App\Model\Table\UsersTable::class] = $di->lazyGet(\App\Model\Table\UsersTable::class); } } // REQUIRED. This file must return list of configs as array return [ 'My\Awesome\App\ClassImplementsAuraDiContainerConfigInterface', new DiConfig, ];
有关高级容器配置和使用方法,请参阅 Aura.Di 的官方文档
如果您想直接访问容器实例,可以使用静态方法 PastryBag::getContainer()
// `$di` is instance of Aura\Di\Container $di = PastryBag::getContainer();
此插件受 PipingBag 插件的启发,但不需要注解。