PHP实现一个自动依赖解析原型[代码]

依赖解析器


require 'lib.php';

class App
{
     
	// 创建自动解析函数
	function build($class){
     
		$reflect = new ReflectionClass($class);

		if(!$reflect->isInstantiable()){
     
			throw new Exception('cannot be instantiated');
		}

		$constructor = $reflect->getConstructor();

		if(is_null($constructor)){
     
			return new $class;
		}
		// 获取实例化时候的各个参数
		$parameters = $constructor->getParameters();
		$dependencies = $this->getDependencies($parameters);
		
		return $reflect->newInstanceArgs($dependencies);
	}
	// 
	public function getDependencies($params){
     
		$dependencies = [];
		foreach($params as $param){
     
			$dependency = $param->getClass();
			if(is_null($dependency)){
     
				// 处理非class类型的函数
				$dependencies[] = $this->resolveNonClass($param);
			}else{
     
				// 处理class类型的函数
				$dependencies[] = $this->build($dependency->name);
			}
		}
		return $dependencies;
	}
	// 解析没有参数的
	public function resolveNonClass($param){
     
		if($param->isDefaultValueAvailable()){
     
			return $param->getDefaultValue();
		}
		throw new Exception('no default value, no idea what to do');
	}

}

$class = 'lib\A';

$object = (new App)->build($class);
print_r($object);

用于测试依赖解析的类,文件名./lib.php


namespace lib;

class A{
     
	protected $b; 
	protected $c; 
	public function __construct(B $b, C $c){
     
		$this->b = $b;
		$this->c = $c;
	}
}

class B{
     
	protected $c;
	public function __construct(C $c){
     
		$this->c = $c;
	}
}

class C{
     

}

执行依赖解析器后的输出结果是:


lib\A Object
(
    [b:protected] => lib\B Object
        (
            [c:protected] => lib\C Object
                (
                )

        )

    [c:protected] => lib\C Object
        (
        )

)

你可能感兴趣的:(PHP语言)