Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 2 additions & 5 deletions en/controllers/components.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
41 changes: 39 additions & 2 deletions en/development/dependency-injection.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
===============

Expand Down