-
Notifications
You must be signed in to change notification settings - Fork 2.5k
fix(dev): Correct errors in DI chapter code examples #13840
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
a73bb1d
refactor(dev): Fix couple errors in DI chapter examples
joshtrichards a57318c
chore: add line highlights to more DI examples
joshtrichards 0724b74
Merge branch 'master' into jtr/dev-di-errors-and-intro
skjnldsv 2577a1b
fix(developer): improve `dependency_injection` article
skjnldsv File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,70 +1,162 @@ | ||
| ==================== | ||
| Dependency injection | ||
| ==================== | ||
|
|
||
| .. sectionauthor:: Bernhard Posselt <dev@bernhard-posselt.com> | ||
|
|
||
| The App Framework assembles the application by using a container based on the | ||
| software pattern `Dependency Injection <https://en.wikipedia.org/wiki/Dependency_injection>`_. | ||
| This makes the code easier to test and thus easier to maintain. | ||
|
|
||
| If you are unfamiliar with this pattern, watch the following video: | ||
| ================================= | ||
| Containers / Dependency Injection | ||
| ================================= | ||
|
|
||
| Introduction | ||
| ------------ | ||
|
|
||
| Modern software applications are composed of various components that need to interact | ||
| with one another. Traditionally, objects create their own dependencies internally, | ||
| which leads to tight coupling and makes code harder to test, maintain, and extend. | ||
| `Dependency injection (DI) <https://en.wikipedia.org/wiki/Dependency_injection>`_ is | ||
| a software design pattern that helps solve this problem by having dependencies provided | ||
| from the outside, rather than being constructed inside the object itself. | ||
|
|
||
| Dependency injection may sound like a big concept, but it’s really just about making | ||
| your code easier to work with and more flexible. Instead of each part of your app | ||
| creating the things it needs by itself, those “dependencies” are handed to it -- usually | ||
| by a special helper called a container. This means your classes don’t need to know how | ||
| to create their collaborators; they just need to know how to use them. | ||
|
|
||
| The App Framework in Nextcloud assembles applications using a container based on this | ||
| design pattern. This approach leads to more modular, testable, and maintainable code. | ||
|
|
||
| Using dependency injection is about more than just elegant code. When all apps follow | ||
| this pattern: | ||
|
|
||
| - It’s easier to test and upgrade both apps and the server, since dependencies can be | ||
| swapped out or mocked. | ||
| - Apps stay decoupled from internal server details, making it safer for Nextcloud to | ||
| evolve without breaking your app. | ||
| - Core features like autowiring, service discovery, and new APIs become available to all | ||
| apps without extra boilerplate. | ||
| - Memory and resource usage can be reduced. | ||
| - New services or APIs become easier to adopt as Nextcloud evolves. | ||
|
|
||
| By sharing a consistent approach to building and wiring up dependencies, everyone -- | ||
| core and app developers alike -- benefits from a more robust, secure, and future-proof | ||
| platform. | ||
|
|
||
| If you are unfamiliar with the DI design pattern, don't worry -- it's widely used in | ||
| modern frameworks, and you'll soon become comfortable with it. You can also watch the | ||
| following video introduction: | ||
|
|
||
| * `Google Clean Code Talks <https://www.youtube.com/watch?v=RlfLCWKxHJ0>`_ | ||
|
|
||
| .. _dependency-injection: | ||
|
|
||
| Dependency injection | ||
| -------------------- | ||
| Basic Pattern of Dependency Injection | ||
| ------------------------------------- | ||
|
|
||
| The essence of dependency injection is: **don't instantiate dependencies directly inside | ||
| your classes or methods, but instead pass them in as parameters**. This allows swapping | ||
| out dependencies (such as with mocks in unit tests), makes dependencies explicit, and | ||
| centralizes object creation logic. | ||
|
|
||
| Dependency Injection sounds pretty complicated but it just means: Don't put | ||
| new dependencies in your constructor or methods but pass them in. So this: | ||
| For example, consider the following pattern: | ||
|
|
||
| .. code-block:: php | ||
| :emphasize-lines: 10, 14 | ||
|
|
||
| /** | ||
| * Without dependency injection: | ||
| */ | ||
|
|
||
| use OCP\IDBConnection; | ||
|
|
||
| // without dependency injection | ||
| class AuthorMapper { | ||
|
|
||
| // Define a property to store the dependency | ||
| private IDBConnection $db; | ||
|
|
||
| public function __construct() { | ||
| // The dependency is instantiated within the class | ||
| $this->db = new Db(); | ||
| } | ||
| } | ||
|
|
||
| would turn into this by using Dependency Injection: | ||
| With dependency injection, you would instead request the dependency as part of the constructor parameters: | ||
|
|
||
| .. code-block:: php | ||
| :emphasize-lines: 10, 13, 15 | ||
|
|
||
| /** | ||
| * Using dependency injection: | ||
| */ | ||
|
|
||
| use OCP\IDBConnection; | ||
|
|
||
| // with dependency injection | ||
| class AuthorMapper { | ||
|
|
||
| // Define a property to store the dependency | ||
| private IDBConnection $db; | ||
|
|
||
| // The dependency is passed in from outside (typically by the container) | ||
| public function __construct(IDBConnection $db) { | ||
| // Assigned to the property | ||
| $this->db = $db; | ||
| } | ||
| } | ||
|
|
||
| Controller injection | ||
| Or, more succinctly, by using constructor property promotion (available in current PHP versions). | ||
| The following is exactly equivalent: | ||
|
|
||
| .. code-block:: php | ||
| :emphasize-lines: 18 | ||
|
|
||
| /** | ||
| * Using dependency injection with constructor property promotion: | ||
| */ | ||
|
|
||
| use OCP\IDBConnection; | ||
|
|
||
| class AuthorMapper { | ||
|
|
||
| /** | ||
| * Constructor property promotion with DI reduces boilerplate code by | ||
| * handling everything within the constructor parameters. The example below | ||
| * does exactly the same thing as the prior example, but in less code: | ||
| * | ||
| * - The dependency is passed in from outside (by the container) | ||
| * - The private property is established to store the dependency | ||
| * - The dependency is assigned directly to that property | ||
| */ | ||
| public function __construct(private IDBConnection $db) { | ||
| } | ||
| } | ||
|
|
||
| Advantages | ||
| ---------- | ||
|
|
||
| - **Testability:** You can inject mock objects for unit testing. | ||
| - **Maintainability:** Changing how a dependency is constructed (in the container) | ||
| updates it wherever it is injected in the application. | ||
| - **Explicitness:** Dependencies are clearly listed in constructors or method signatures, | ||
| improving readability and maintainability. | ||
|
|
||
| Controller Injection | ||
| -------------------- | ||
|
|
||
| For controllers it's possible to also have dependencies injected into methods. | ||
| For controllers, Nextcloud allows dependencies to also be injected directly into | ||
| individual methods, not just constructors. This is referred to as *method injection* and | ||
| enables you to specify dependencies only where needed, potentially reducing resource | ||
| usage for rarely required services. | ||
|
|
||
| .. code-block:: php | ||
| :caption: lib/Controller/ApiController.php | ||
| :emphasize-lines: 12-13, 16-17 | ||
| :emphasize-lines: 15-16, 19-20 | ||
|
|
||
| <?php | ||
|
|
||
| namespace OCA\MyApp\Controller; | ||
|
|
||
| use OCA\MyApp\Service\BarService; | ||
| use OCA\MyApp\Service\FooService; | ||
| use OCP\AppFramework\Controller; | ||
| use OCP\IRequest; | ||
|
|
||
| class ApiController { | ||
| public function __construct($appName, IRequest $request) { | ||
| class ApiController extends Controller { | ||
| public function __construct(string $appName, IRequest $request) { | ||
| parent::__construct($appName, $request); | ||
| } | ||
|
|
||
|
|
@@ -110,7 +202,7 @@ use the **IRegistrationContext::registerService** method: | |
| use OCP\AppFramework\Bootstrap\IBootContext; | ||
| use OCP\AppFramework\Bootstrap\IRegistrationContext; | ||
| use OCP\IDBConnection; | ||
|
|
||
| use OCP\IRequest; | ||
| use OCA\MyApp\Controller\AuthorController; | ||
| use OCA\MyApp\Service\AuthorService; | ||
| use OCA\MyApp\Db\AuthorMapper; | ||
|
|
@@ -136,7 +228,7 @@ use the **IRegistrationContext::registerService** method: | |
| $context->registerService(AuthorController::class, function(ContainerInterface $c): AuthorController { | ||
| return new AuthorController( | ||
| $c->get('appName'), | ||
| $c->get(Request::class), | ||
| $c->get(IRequest::class), | ||
| $c->get(AuthorService::class) | ||
| ); | ||
| }); | ||
|
|
@@ -171,13 +263,13 @@ The container works in the following way: | |
|
|
||
| return new AuthorController( | ||
| $c->get('appName'), | ||
| $c->get(Request::class), | ||
| $c->get(IRequest::class), | ||
| $c->get(AuthorService::class) | ||
|
Comment on lines
264
to
267
|
||
| ); | ||
|
|
||
| * The **appName** is queried and returned from the base class | ||
| * The **Request** is queried and returned from the server container | ||
| * **AuthorService** is queried:: | ||
| * **AuthorService** is queried. This triggers the registered Callable:: | ||
|
|
||
| $container->registerService(AuthorService::class, function(ContainerInterface $c): AuthorService { | ||
| return new AuthorService( | ||
|
|
@@ -188,14 +280,14 @@ The container works in the following way: | |
| * **AuthorMapper** is queried:: | ||
|
|
||
| $container->registerService(AuthorMapper::class, function(ContainerInterface $c): AuthorMapper { | ||
| return new AuthorService( | ||
| return new AuthorMapper( | ||
| $c->get(IDBConnection::class) | ||
| ); | ||
| }); | ||
|
|
||
| * The **database connection** is returned from the server container | ||
| * Now **AuthorMapper** has all of its dependencies and the object is returned | ||
| * **AuthorService** gets the **AuthorMapper** and returns the object | ||
| * Now **AuthorMapper** has all of its dependencies and can be constructed by the DI code. The object is returned. | ||
| * **AuthorService** gets the **AuthorMapper**, is constructed, and returns the object | ||
| * **AuthorController** gets the **AuthorService** and finally the controller can be instantiated and the object is returned | ||
|
|
||
| So basically the container is used as a giant factory to build all the classes that are needed for the application. Because it centralizes all the creation of objects (the **new Class()** lines), it is very easy to add new constructor parameters without breaking existing code: only the **__construct** method and the container line where the **new** is being called need to be changed. | ||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The “Without dependency injection” example instantiates
new Db()even though no such class is imported/defined in the snippet, and it’s unclear that it implementsOCP\IDBConnection. Either use a clearly placeholder concrete type (e.g.,new SomeConcreteDbConnection()), or reference a real Nextcloud DB connection class/factory so the example is internally consistent.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
\OC::$serveris deprecated @copilot.