Understanding Inversion of Control (IoC) with PHP Code Examples
This article explains the Inversion of Control (IoC) principle, contrasts a tightly coupled logging implementation with a dependency‑injected version in PHP, and demonstrates how passing a logger via the constructor decouples classes and follows the open‑closed principle.
Control Inversion (IoC) : Inversion of Control (IoC) is a design pattern that moves the responsibility of managing dependencies from inside a class to an external entity.
Concept Overview : IoC and Dependency Injection express the same idea – a class should not create its own dependencies. For example, a user‑login feature needs a logger, which could be a file logger or a database logger.
Code Demonstration – Tight Coupling :
// 定义写日志的接口规范
interface Log {
public function write();
}
// 文件记录日志
class FileLog implements Log {
public function write() {
echo 'file log write...';
}
}
// 数据库记录日志
class DatabaseLog implements Log {
public function write() {
echo 'database log write...';
}
}
// 程序操作类
class User {
protected $fileLog;
public function __construct() {
$this->fileLog = new FileLog();
}
public function login() {
// 登录成功,记录登录日志
echo 'login success...';
$this->fileLog->write();
}
}
$user = new User();
$user->login();The above code works, but the User class is tightly coupled to FileLog . If we want to switch to DatabaseLog , we must modify User , violating the Open‑Closed Principle.
Code Demonstration – Using IoC (Dependency Injection) :
class User {
protected $log;
public function __construct(Log $log) {
$this->log = $log;
}
public function login() {
// 登录成功,记录登录日志
echo 'login success...';
$this->log->write();
}
}
$user = new User(new DatabaseLog());
$user->login();Now the logging mechanism is supplied from outside via the constructor, so User no longer needs to know which logger is used. This is the essence of Inversion of Control: external code provides the dependencies, achieving decoupling and adhering to the open‑closed principle.
In summary, by applying IoC you can change logging strategies (or any other dependency) without altering the core business class, making the system more flexible and maintainable.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.