In this tutorial, we'll learn about dependency injection using a basic example.
<?php
namespace App\Services;
class Logger
{
public function log($message)
{
echo $message;
}
}
<?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!');
}
}
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.