php 反射 依赖注入
2017-05-04 15:29
381 查看
<?php | |
if (PHP_SAPI != 'cli') { | |
exit('Please run it in terminal!'); | |
} | |
if ($argc < 3) { | |
exit('At least 2 arguments needed!'); | |
} | |
$controller = ucfirst($argv[1]) . 'Controller'; | |
$action = 'action' . ucfirst($argv[2]); | |
// 检查类是否存在 | |
if (!class_exists($controller)) { | |
exit("Class $controller does not existed!"); | |
} | |
// 获取类的反射 | |
$reflector = new ReflectionClass($controller); | |
// 检查方法是否存在 | |
if (!$reflector->hasMethod($action)) { | |
exit("Method $action does not existed!"); | |
} | |
// 取类的构造函数 | |
$constructor = $reflector->getConstructor(); | |
// 取构造函数的参数 | |
$parameters = $constructor->getParameters(); | |
// 遍历参数 | |
foreach ($parameters as $key => $parameter) { | |
// 获取参数声明的类 | |
$injector = new ReflectionClass($parameter->getClass()->name); | |
// 实例化参数声明类并填入参数列表 | |
$parameters[$key] = $injector->newInstance(); | |
} | |
// 使用参数列表实例 controller 类 | |
$instance = $reflector->newInstanceArgs($parameters); | |
// 执行 | |
$instance->$action(); | |
class HelloController | |
{ | |
private $model; | |
public function __construct(TestModel $model) | |
{ | |
$this->model = $model; | |
} | |
public function actionWorld() | |
{ | |
echo $this->model->property, PHP_EOL; | |
} | |
} | |
class TestModel | |
{ | |
public $property = 'property'; | |
} |
相关文章推荐
- PHP反射机制实现自动依赖注入
- 学习php反射(3)——一个依赖注入的例子
- PHP实现依赖注入-使用反射机制和动态代理技术 - 简单思想(咋个办呢 zgbn)
- PHP基于反射机制实现自动依赖注入的方法详解
- 使用反射及依赖注入实现灵活的插件模式
- [ javascript ] 反射与依赖注入!
- awesome PHP之依赖注入容器pimple
- 理解PHP 依赖注入|Laravel IoC容器
- Java反射及依赖注入简单模拟
- 【转】理解 PHP 依赖注入 | Laravel IoC容器
- java反射模拟spring依赖注入
- Spring的反射机制和依赖注入
- PHP 依赖注入,从此不再考虑加载顺序
- php依赖注入
- 利用反射简单模拟Spring的控制反转(Ioc)和依赖注入(DI)
- php 依赖注入容器(dependency injection container)
- PHP依赖注入简单理解
- .NET 反射和依赖注入
- PHP 依赖注入 (设计模式)
- 反射与注入依赖问题