amansrivastava/d9-dev

#16 ­- Dependency Injection Example / Service Container

Closed this issue · 0 comments

Objective

We will be trying out an example today, in an attempt to use Dependency Injection by modifying an existing code without changing any functionality.

Exercise

  1. Download the examples module from https://www.drupal.org/project/examples. It has a bunch of modules but we will be interested in the page_example module only, during the course of this exercise.
  2. The module has a PageExampleController defined in src/Controller/PageExampleController.php. The simple() method in this controller is responsible for rendering the url “examples/page_example/simple” when the module is enabled.
  3. Let’s modify this method by adding a line such that a log entry is made whenever this url is opened. \Drupal::logger('page_example_module')->notice('Simple Page was displayed');
  4. Now, this is the code we will start with for our exercise.
  5. Modify the code to use dependency injection to give access to logger.factory service from our controller, which will be used to do the logging, instead of \Drupal::logger.
  6. The links in additional resources are a great read towards achieving this.