diff --git a/en/controllers/components.rst b/en/controllers/components.rst index cd5d3b7385..44ec1be50a 100644 --- a/en/controllers/components.rst +++ b/en/controllers/components.rst @@ -147,11 +147,8 @@ in your controller, you could access it like so:: properties they share the same 'namespace'. Be sure to not give a component and a model the same name. -.. warning:: - - Component methods **don't** have access to :doc:`/development/dependency-injection` - like Controller actions have. Use a service class inside your controller actions - instead of a component if you need this functionality. +.. versionchanged:: 5.1.0 + Components are able to use :doc:`/development/dependency-injection` to receive services. .. _creating-a-component: diff --git a/en/development/dependency-injection.rst b/en/development/dependency-injection.rst index 132beeeefb..bb307fb4c9 100644 --- a/en/development/dependency-injection.rst +++ b/en/development/dependency-injection.rst @@ -14,10 +14,14 @@ CakePHP will use the :term:`DI container` in the following situations: * Constructing controllers. * Calling actions on your controllers. +* Constructing Components. * Constructing Console Commands. * Constructing Middleware by classname. -A short example would be:: +Controller Example +================== + +:: // In src/Controller/UsersController.php class UsersController extends AppController @@ -45,7 +49,10 @@ database. Because this service is injected into our controller, we can easily swap the implementation out with a mock object or a dummy sub-class when testing. -Here is an example of an injected service inside a command:: +Command Example +=============== + +:: // In src/Command/CheckUsersCommand.php class CheckUsersCommand extends Command @@ -76,6 +83,36 @@ a whole to the Container and add the ``UsersService`` as an argument. With that you can then access that service inside the constructor of the command. +Component Example +================= + +:: + + // In src/Controller/Component/SearchComponent.php + class SearchComponent extends Command + { + public function __construct( + ComponentRegistry $registry, + private UserService $users + ) { + parent::__construct($registry, []); + } + + public function something() + { + $valid = $this->users->check('all'); + } + } + + // In src/Application.php + public function services(ContainerInterface $container): void + { + $container->add(SearchComponent::class) + ->addArgument(ComponentRegistry::class) + ->addArgument(UsersService::class); + $container->add(UsersService::class); + } + Adding Services ===============