@@ -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,36 @@ 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+ private UserService $users
97+ ) {
98+ parent::__construct($registry, []);
99+ }
100+
101+ public function something()
102+ {
103+ $valid = $this->users->check('all');
104+ }
105+ }
106+
107+ // In src/Application.php
108+ public function services(ContainerInterface $container): void
109+ {
110+ $container->add(SearchComponent::class)
111+ ->addArgument(ComponentRegistry::class)
112+ ->addArgument(UsersService::class);
113+ $container->add(UsersService::class);
114+ }
115+
79116Adding Services
80117===============
81118
0 commit comments