PHP实现控制反转模式(附完整源码)

时间:2025-03-29 12:29:46
<?php ​ // 定义一个接口 interface DatabaseInterface { public function query($sql); }// 实现接口 class MySQLDatabase implements DatabaseInterface { public function query($sql) { echo "执行MySQL查询:{$sql}\n"; } }// IoC容器类 class Container { private $bindings = [];public function bind($abstract, $concrete) { $this->bindings[$abstract] = $concrete; }public function resolve($abstract) { if (isset($this->bindings[$abstract])) { $concrete = $this->bindings[$abstract]; if ($concrete instanceof Closure) { return $concrete(); } return new $concrete(); } throw new Exception("无法解析抽象类: {$abstract}"); } }// 使用示例 $container = new Container();// 绑定接口和实现类 $container->bind('DatabaseInterface', 'MySQLDatabase');// 解析接口,获取实例 $database = $container->resolve('DatabaseInterface');// 使用实例 $database->query('SELECT * FROM users'); `