简易 Ioc 容器
简易版控制反转Ioc
// Iocindex.php
<?php
/*
* 控制反转
*/
interface Log {
public function info();
}
class DatabaseLog implements Log {
public function info() {
echo 'database log';
}
}
class FileLog implements Log {
public function info() {
echo 'file log';
}
}
class User {
protected $log;
public function __construct(Log $log) {
$this->log = $log;
}
public function writeLog() {
$this->log->info();
}
}
class Ioc {
private $binds = [];
public function bind($contract, $concrete) {
$this->binds[$contract] = $concrete;
}
private function methodBindParams($className){
$reflect = new Reflect($className,'__construct');
return $reflect->bindParamsToMethod();
}
public function make($className){
$methodBindParams = $this->methodBindParams($className);
$reflect = new Reflect($className,'__construct');
return $reflect->make($this->binds,$methodBindParams);
}
}
class Reflect{
private $className;
private $methodName;
public function __construct($className,$methodName){
$this->className = $className;
$this->methodName = $methodName;
}
//绑定参数到方法
public function bindParamsToMethod(){
$params = [];
$method = new ReflectionMethod($this->className,$this->methodName);
foreach ($method->getParameters() as $param) {
$params[] = [$param->name,$param->getClass()->name];
}
return [$this->className=> $params];
}
public function make($bind,$methodBindParams){
$args = [];
foreach ($methodBindParams as $className => $params) {
foreach ($params as $param) {
list($paramName,$paramType) = $param;
$paramName = new $bind[$paramType]();
array_push($args, $paramName);
}
}
$reflectionClass = new ReflectionClass($this->className);
return $reflectionClass->newInstanceArgs($args);
}
}
$ioc = new Ioc();
$ioc->bind('Log', 'FileLog');
$user = $ioc->make('User');
$user->writeLog();
本作品采用《CC 协议》,转载必须注明作者和本文链接