From 236828b9327ab4743c31edc62fd901c0fd743ddd Mon Sep 17 00:00:00 2001 From: Christoph Wurst Date: Fri, 3 Nov 2023 12:34:36 +0100 Subject: [PATCH] feat(devmanual): Optional dependency injection services Signed-off-by: Christoph Wurst --- .../basics/dependency_injection.rst | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/developer_manual/basics/dependency_injection.rst b/developer_manual/basics/dependency_injection.rst index 245fa340f..b1e8da1d9 100644 --- a/developer_manual/basics/dependency_injection.rst +++ b/developer_manual/basics/dependency_injection.rst @@ -443,6 +443,26 @@ What not to inject: .. _`reflection`: https://www.php.net/manual/en/book.reflection.php +Optional services +----------------- + +.. versionadded:: 28 + +If an injected dependency can't be found or build, an exception is thrown. This can be avoided by using the a nullable type notation for a dependency: + +.. code-block:: php + :emphasize-lines: 6 + + namespace OCA\MyApp\MyService; + + use Some\Service; + + class MyService { + public function __construct(private ?Service $service) { + } + } + +If ``\Some\Service`` exists and can be built, it will be injected. Else ``MyService`` will receive ``null``. Accessing the container from anywhere -------------------------------------