2
0

More than 3 years have passed since last update.

EC-CUBE4 DI を利用する

Last updated at Posted at 2021-01-28

はじめに

EC-CUBE4 は Symfony3系 で作られているので、DIの仕組みとして Service Container が使えます。

カスタマイズ領域は、ネームスペースが Customize\Entity Customize\Resource Customize\Tests 以外が、依存解決時の対象となるようです。

app/config/eccube/services.yaml
services:
    # 省略
    Customize\:
        resource: '../../../app/Customize/*'
        exclude: '../../../app/Customize/{Entity,Resource,Tests}'
    # 省略

インターフェースと実装を結びつける

app/config/eccube/packages/my_service_name.yml
services:
    Customize\Service\MyServiceInterface: '@Customize\Service\MyService'

サービスクラスのコンストラクタに必要な情報を設定する

サービスクラスのコンストラクタが、他の依存で解決できる場合、この設定は不要です。

例えば、サービスクラスのコンストラクタで、リソースディレクトリ内の特定のディレクトリパスを渡したい場合に、以下のように設定します。

app/config/eccube/packages/my_service_name.yml
services:
    Customize\Service\MyServiceInterface: '@Customize\Service\MyService'
+   Customize\Service\MyService:
+       arguments:
+           $myPath: '%kernel.project_dir%/app/Customize/Resource/config/my_service.json'

依存が注入される度に、新しいインスタンスを生成したい場合は shared: true を設定します。

app/config/eccube/packages/my_service_name.yml
services:
    Customize\Service\MyServiceInterface: '@Customize\Service\MyService'
    Customize\Service\MyService:
        arguments:
            $myPath: '%kernel.project_dir%/app/Customize/Resource/config/my_service.json'
+       shared: true

独自のサービスクラスを作成する

app/Customize/Service/MyServiceInterface.php
interface MyServiceInterface
{
}
app/Customize/Service/MyService.php
<?php

declare(strict_types=1);

namespace Customize\Service;

class MyService implements MyServiceInterface
{
    private $myPath;

    public function __construct(string $myPath)
    {
        $this->myPath = $myPath;
    }
}

適当なクラスで利用する

$myPath つまり /app/Customize/Resource/config/my_service.json で初期化された状態の MyService クラスのインスタンスが注入されます。

<?php

declare(strict_types=1);

namespace Customize\Controller;

use Customize\Service\MyServiceInterface;
use Eccube\Controller\AbstractController;

class SomeController extends AbstractController
{
    /** @var MyServiceInterface */
    private $myService;

    public function __construct(MyServiceInterface $myService)
    {
        $this->myService = $myService;
    }
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0