控制反轉 將物件建立與依賴管理權從程式碼移至外部容器,降低耦合度。本文用 PHP 動態特性實作簡易 IoC 容器,透過 JSON 設定檔動態建立物件並注入屬性。
<?php
interface Fruit {
public function showColor();
}
class Apple implements Fruit {
private $color;
public function getColor() { return $this->color; }
public function setColor($v) { $this->color = $v; }
public function showColor() { echo "Apple Color: " . $this->color; }
}
class Banana implements Fruit {
private $color;
public function getColor() { return $this->color; }
public function setColor($v) { $this->color = $v; }
public function showColor() { echo "Banana Color: " . $this->color; }
}
?>
<?php
class ClassFactory {
private $config;
public function __construct($configFile) {
$content = file_get_contents($configFile);
// 移除註解 (簡易處理)
$content = preg_replace('/\/\/.*?\n/', '', $content);
$this->config = json_decode($content, true);
}
public function getBean($id) {
foreach ($this->config as $conf) {
if ($conf['id'] === $id) {
require_once $conf['class_file'];
$obj = new $conf['class_name']();
// 注入屬性:對應 setXxx() 方法
foreach ($conf['properties'] as $prop) {
$method = 'set' . ucfirst($prop['name']);
if (method_exists($obj, $method)) {
$obj->$method($prop['value']);
}
}
return $obj;
}
}
return null;
}
}
?>
[
{
"id": "Apple",
"class_name": "Apple",
"class_file": "Fruit.php",
"properties": [ { "name": "color", "value": "Red" } ]
},
{
"id": "Banana",
"class_name": "Banana",
"class_file": "Fruit.php",
"properties": [ { "name": "color", "value": "Yellow" } ]
}
]
<?php
require_once "ClassFactory.php";
$factory = new ClassFactory("config.json");
$fruit = $factory->getBean("Apple");
$fruit->showColor(); // Apple Color:Red
echo "<br/>";
$fruit = $factory->getBean("Banana");
$fruit->showColor(); // Banana Color:Yellow
?>
Apple Color:Red Banana Color:Yellow
PHP 動態語言特性讓 IoC 實作極簡潔,無需複雜反射即可完成核心功能。