php反射学习之依赖注入示例

yipeiwu_com5年前PHP代码库

本文实例讲述了php反射学习之依赖注入。分享给大家供大家参考,具体如下:

先看代码:

<?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';
}

(以上代码非原创)将以上代码保存为 run.php

运行方式,在终端下执行php run.php Hello World

可以看到,我们要执行 HelloController 下的 WorldAction,
HelloController 的构造函数需要一个 TestModel类型的对象,

通过php 反射,我们实现了, TestModel 对象的自动注入,

上面的例子类似于一个请求分发的过程,是路由请求的分发的一部分,假如我们要接收一个请求 地址例如: /Hello/World

意思是要执行 HelloController 下的 WorldAction 方法。

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《PHP运算与运算符用法总结》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家PHP程序设计有所帮助。

相关文章

php+AJAX传送中文会导致乱码的问题的解决方法

//如果传送参数是直接赋予的,就会产生乱码! 复制代码 代码如下:http_request.open("POST",url,true); http_request.setRequestH...

PHP CLI模式下的多进程应用分析

PHP在很多时候不适合做常驻的SHELL进程, 他没有专门的gc例程, 也没有有效的内存管理途径. 所以如果用PHP做常驻SHELL, 你会经常被内存耗尽导致abort而unhappy....

PHP syntax error, unexpected $end 错误的一种原因及解决

Parse error: syntax error, unexpected $end in script.php on line xx 调试了一会后发现产生错误的行是文件中间某行 //$...

PHP Session_Regenerate_ID函数双释放内存破坏漏洞

SEBUG-ID:1491 SEBUG-Appdir:PHP发布时间:2007-03-17 影响版本: PHP PHP 5.2.1 PHP PHP 5.1.6 PHP PHP 5.1.5...

PHP实现动态压缩js与css文件的方法

本文实例讲述了PHP实现动态压缩js与css文件的方法。分享给大家供大家参考,具体如下: 正式发布产品时,我们希望将项目里的js,css合并压缩,以减少http请求、防止轻易查看源代码。...