Dependency Injection Tutorial

In this tutorial, we'll learn about dependency injection using a basic example.

Step 1: Create a Logger Class

<?php
namespace App\Services;

class Logger
{
    public function log($message)
    {
        echo $message;
    }
}

Step 2: Create a Controller

<?php
namespace App\Controllers;

use App\Services\Logger;

class MyController extends BaseController
{
    protected $logger;

    public function __construct(Logger $logger)
    {
        $this->logger = $logger;
    }

    public function index()
    {
        $this->logger->log('Hello, Dependency Injection!');
    }
}

Step 3: Instantiate Controller and Logger

Now, let's instantiate the Logger and MyController, and call the index method.

<?php
// Instantiate the Logger
$logger = new \App\Services\Logger();

// Instantiate MyController and pass the Logger instance
$myController = new \App\Controllers\MyController($logger);

// Call the index method
$myController->index();

Congratulations! You've successfully learned about dependency injection using a basic example.