zoukankan      html  css  js  c++  java
  • 关于PHP中依赖注入的详细介绍

    依赖注入原理:

    依赖注入是一种允许我们从硬编码的依赖中解耦出来,从而在运行时或者编译时能够修改的软件设计模式。简而言之就是可以让我们在类的方法中更加方便的调用与之关联的类。

    实例讲解:

    假设有一个这样的类:

    1

    2

    3

    4

    5

    6

    7

    class Test

    {

     public function index(Demo $demo,Apple $apple){

      $demo->show();

      $apple->fun();

     }

    }

    如果想使用index方法我们需要这样做:

    1

    2

    3

    4

    $demo = new Demo();

    $apple = new Apple();

    $obj = new Test();

    $obj->index($demo,$apple);

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

    1

    2

    $obj = new dependencyInjection();

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

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

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

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

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    <?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。如果我们使用了依赖注入和类的自动加载之后,我们就可以像下面这样使用。

    1

    2

    3

    4

    public function index(UserModel $userModel,MessageModel $messageModel){

     $userList = $userModel->getAllUser();

     $messageList = $messageModel->getAllMessage();

    }

  • 相关阅读:
    Linux YUM (Yellowdog Updater, Modified) Commands for Package Management
    awk命令例子详解
    sed命令例子详解
    浅谈XX系统跨平台迁移(测试环境)
    Postgres常用命令之增、删、改、查
    Postgres主备切换
    Postgres配置主从流复制
    Crontab定时任务
    GIL全局锁测试
    python try exception finally记录
  • 原文地址:https://www.cnblogs.com/heyue0117/p/11827789.html
Copyright © 2011-2022 走看看