动机
我想通过di容器将service注入到command和controller中。
另外,service 使用 repository 注入。
文档中并没有提到嵌套注入这种情况。
文档
https://book.cakephp.org/4/en/development/dependency-injection.html
如何实施
服务和存储库
interface somerepository { public getall(): array; }
class somerepositoryimpl implements somerepository { public function getall(): array { print('getall()'); return []; } }
class someservice { private $somerepository; public function __construct(somerepository $somerepository) { $this->somerepository = $somerepository; } public function dosomething(): void { $this->somerepository->getall(); } }
命令
use cakecommandcommand; use cakeconsolerguments; use cakeconsoleconsoleio; use cakeconsoleconsoleoptionparser; class somecommand extends command { private someservice $service; public function __construct(someservice $service) { parent::__construct(); $this->service = $service; } public static function getdescription(): string { return 'inject service through provider'; } public function buildoptionparser(consoleoptionparser $parser): consoleoptionparser { $parser = parent::buildoptionparser($parser); return $parser; } public function execute(arguments $args, consoleio $io) { $this->service->dosomething(); } }
use cakecorecontainerinterface; use cakecoreserviceprovider; class commandserviceprovider extends serviceprovider { protected $provides = [ somecommand::class, ]; public function services(containerinterface $container): void { $container ->add(somecommand::class) ->addargument(someservice::class); } }
控制器
use cakecontrollercontroller; class somecontroller extends controller { public function index(someservice $service) { $service->dosomething(); print('index()'); } }
注册到di容器
use cakecorecontainerinterface; use cakecoreserviceprovider; class someserviceprovider extends serviceprovider { protected $provides = [ someservice::class, ]; public function services(containerinterface $container): void { $container ->add(somerepository::class, somerepositoryimpl::class); $container ->add(someservice::class) ->addargument(somerepository::class); } }
// Application.php class Application extends BaseApplication { // ... public function services(ContainerInterface $container): void { $container->addServiceProvider(new SomeServiceProvider()); $container->addServiceProvider(new ControllerServiceProvider()); } // ...
以上就是CakePHP 上层的 DI 容器的详细内容,更多请关注php中文网其它相关文章!
版权声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系 yyfuon@163.com