@@ -14,10 +14,14 @@ CakePHP will use the :term:`DI container` in the following situations:
1414
1515* Constructing controllers.
1616* Calling actions on your controllers.
17+ * Constructing Components.
1718* Constructing Console Commands.
1819* Constructing Middleware by classname.
1920
20- A short example would be::
21+ Controller Example
22+ ==================
23+
24+ ::
2125
2226 // In src/Controller/UsersController.php
2327 class UsersController extends AppController
@@ -45,7 +49,10 @@ database. Because this service is injected into our controller, we can easily
4549swap the implementation out with a mock object or a dummy sub-class when
4650testing.
4751
48- Here is an example of an injected service inside a command::
52+ Command Example
53+ ===============
54+
55+ ::
4956
5057 // In src/Command/CheckUsersCommand.php
5158 class CheckUsersCommand extends Command
@@ -76,6 +83,43 @@ a whole to the Container and add the ``UsersService`` as an argument.
7683With that you can then access that service inside the constructor
7784of the command.
7885
86+ Component Example
87+ =================
88+
89+ ::
90+
91+ // In src/Controller/Component/SearchComponent.php
92+ class SearchComponent extends Command
93+ {
94+ public function __construct(
95+ ComponentRegistry $registry,
96+ array $config = [],
97+ private UserService $users
98+ ) {
99+ parent::__construct($registry, $config);
100+ }
101+
102+ public function something()
103+ {
104+ $valid = $this->users->check('all');
105+ }
106+ }
107+
108+ // In src/Application.php
109+ public function services(ContainerInterface $container): void
110+ {
111+ $container->add(SearchComponent::class)
112+ ->addArgument(ComponentRegistry::class)
113+ ->addArgument([])
114+ ->addArgument(AlfredFTP::class);
115+ $container->add(UsersService::class);
116+ }
117+
118+ This means if you have components which need config you not only need to add
119+ the component config in your ``AppController `` via
120+ ``$this->loadComponent('Search', ['key' => 'value']) `` but also need to add
121+ the component to the DI container manually.
122+
79123Adding Services
80124===============
81125
0 commit comments