2024-12-16

CakePHP 上层的 DI 容器

cakephp 上层的 di 容器

动机

我想通过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中文网其它相关文章!

https://www.php.cn/faq/1142590.html

发表回复

Your email address will not be published. Required fields are marked *