久しぶりに Symfony で少し大きめのプログラムを書くことになりました。整理のためにサービスコンテナについて簡単にまとめます。
Service Container にすべて記載されていますが、自分の整理のためにまとめてみます。
Symfony の サービスコンテナ
( Service Container )は サービス(クラスのインスタンス)を管理し、依存関係を解決する仕組みです。
サービスコンテナは登録されたサービスについて適切に 依存性の注入
を管理します。
サービスコンテナ
にサービスを手動で登録( config/services.yaml に定義)することも、自動で登録(Autowiring)することもできます。
依存性の注入
( Dependency Injection, DI )とは、クラスが必要とする依存オブジェクトを、クラスの内部で直接生成するのではなく、外部から注入する設計パターンです。
サービスコンテナ
)Symfony は 依存性の注入
を サービスコンテナ
を使って実現します。
具体的には大きく以下に分けられます。
依存性の注入
依存性の注入
Symfony は 依存性の注入
をクラスの 型宣言
( type-hints ) を使用して設定なしで実現できます。
この仕組みを Autowiring
と呼びます。
parameters:
env_sample: '%env('ENV_SAMPLE')%'
services:
# default configuration for services in *this* file
_defaults:
autowire: true # Automatically injects dependencies in your services.
autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
# 著者注釈 デフォルトで Autowiring が有効(型宣言を使用して自動で依存性の注入を解決)
# makes classes in src/ available to be used as services
# this creates a service per class whose id is the fully-qualified class name
App\:
resource: '../src/'
exclude:
- '../src/DependencyInjection/'
- '../src/Entity/'
- '../src/Kernel.php'
# 著者注釈 App\ 以下のクラスはデフォルトでサービスコンテナに(サービスとして)登録
# add more service definitions when explicit configuration is needed
# please note that last definitions always *replace* previous ones
# 著者注釈 依存性の注入を定義して手動で解決
service_sample:
class: App\Service\Sample:
argument: # construct injection
$envSample: '%env_sample%'
App\Service\MyService:
arguments: # construct injection
$serviceSample: '@service_sample'
Autowiring
で使用可能なリソース一覧を表示します。
$ bin/console debug:autowiring --all
サービスコンテナ
に登録されたサービス一覧を表示します。
bin/console debug:container
No comments yet.
改行と段落タグは自動で挿入されます。
メールアドレスは表示されません。