@@ -14,10 +14,14 @@ CakePHP will use the :term:`DI container` in the following situations:
14
14
15
15
* Constructing controllers.
16
16
* Calling actions on your controllers.
17
+ * Constructing Components.
17
18
* Constructing Console Commands.
18
19
* Constructing Middleware by classname.
19
20
20
- A short example would be::
21
+ Controller Example
22
+ ==================
23
+
24
+ ::
21
25
22
26
// In src/Controller/UsersController.php
23
27
class UsersController extends AppController
@@ -45,7 +49,10 @@ database. Because this service is injected into our controller, we can easily
45
49
swap the implementation out with a mock object or a dummy sub-class when
46
50
testing.
47
51
48
- Here is an example of an injected service inside a command::
52
+ Command Example
53
+ ===============
54
+
55
+ ::
49
56
50
57
// In src/Command/CheckUsersCommand.php
51
58
class CheckUsersCommand extends Command
@@ -76,6 +83,36 @@ a whole to the Container and add the ``UsersService`` as an argument.
76
83
With that you can then access that service inside the constructor
77
84
of the command.
78
85
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
+
79
116
Adding Services
80
117
===============
81
118
0 commit comments