首頁 >後端開發 >php教程 >CakePHP 上層的 DI 容器

CakePHP 上層的 DI 容器

Linda Hamilton
Linda Hamilton原創
2024-12-24 06:57:23657瀏覽

DI Container on CakePHP upper

動機

我想透過 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 Cake\Command\Command;
use Cake\Console\Arguments;
use Cake\Console\ConsoleIo;
use Cake\Console\ConsoleOptionParser;

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 Cake\Core\ContainerInterface;
use Cake\Core\ServiceProvider;

class CommandServiceProvider extends ServiceProvider
{
    protected $provides = [
        SomeCommand::class,
    ];

    public function services(ContainerInterface $container): void
    {
        $container
            ->add(SomeCommand::class)
            ->addArgument(SomeService::class);
    }
}

控制器

use Cake\Controller\Controller;

class SomeController extends Controller
{
    public function index(SomeService $service)
    {
        $service->doSomething();
        print('index()');
    }
}

註冊到DI容器

use Cake\Core\ContainerInterface;
use Cake\Core\ServiceProvider;

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn