php中的依赖注入实例详解

本文实例讲述了php中的依赖注入。分享给大家供大家参考,具体如下:

依赖注入是一种允许我们从硬编码的依赖中解耦出来,从而在运行时或者编译时能够修改的软件设计模式。

我到现在依然不大明白上面“依赖注入”的定义是什么……

有兴趣可以参考下《PHP之道》上面对“依赖注入”的 解释。
http://laravel-china.github.io/php-the-right-way/#dependency_injection

简而言之就是可以让我们在类的方法中更加方便的调用与之关联的类。

假设我们有一个这样的类

class Test
{
 public function index(Demo $demo,Apple $apple){
  $demo->show();
  $apple->fun();
 }
}

如果想使用index方法我们一般需要这样做。

$demo = new Demo();
$apple = new Apple();
$obj = new Test();
$obj->index($demo,$apple);

index方法调用起来是不是很麻烦?上面的方法还只是有两个参数,如果有更多的参数,我们就要实例化更多的对象作为参数。如果我们引入的“依赖注入”,调用方式将会是像下面这个样子。

$obj = new dependencyInjection();
$obj->fun("Test","index");

我们上面的例子中,Test类的index方法依赖于Demo和Apple类。

“依赖注入”就是识别出所有方法“依赖”的类,然后作为参数值“注入”到该方法中。

dependencyInjection类就是完成这个依赖注入任务的。

<?php
/**
 * Created by PhpStorm.
 * User: zhezhao
 * Date: 2016/8/10
 * Time: 19:18
 */
class dependencyInjection
{
 function fun($className,$action){
  $reflectionMethod = new ReflectionMethod($className,$action);
  $parammeters = $reflectionMethod->getParameters();
  $params = array();
  foreach ($parammeters as $item) {
   preg_match('/> ([^ ]*)/',$item,$arr);
   $class = trim($arr[1]);
   $params[] = new $class();
  }
  $instance = new $className();
  $res = call_user_func_array([$instance,$action],$params);
  return $res;
 }
}

在mvc框架中,control有时会用到多个model。如果我们使用了依赖注入类的自动加载之后,我们就可以像下面这样使用。

public function index(UserModel $userModel,MessageModel $messageModel){
 $userList = $userModel->getAllUser();
 $messageList = $messageModel->getAllMessage();
}

灰常方便~

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

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