tp5.1 依賴注入的使用


參考:
概念:https://blog.csdn.net/qq_36172443/article/details/82667427
應用: http://www.cnblogs.com/finalanddistance/p/8960669.html

依賴注入的概念:

 

總結一點就是 底層類應該依賴於上層類,避免上層類依賴於底層類。

上代碼:

首先先寫幾個需要用到的控制器;

demo3:

<?php
namespace app\index\controller;

class Demo3
{
    private $content = '我是demo3!!!';

    public function text()
    {
        return  $this -> content;
    }

    public function setText($string)
    {
        $this -> content = $string;
    }

    public function getName()
    {
        $name = '我是demo3的名字';
        return $name;
    }
}

demo2:

<?php
namespace app\index\controller;

class Demo2
{
    private $Demo3;
    public function __construct(Demo3 $demo)
    {
       $this -> Demo3 = $demo;
    }

    public function text()
    {
        return $this -> Demo3 -> text();
    }

    public function getName()
    {
        return $this -> Demo3 -> getName();
    }
}

demo1:

<?php
namespace app\index\controller;

class Demo1
{
    private $Demo2;
    public function __construct(Demo2 $demo2)
    {
       $this -> Demo2 = $demo2;
    }

    public function text()
    {
        return $this -> Demo2 -> text();
    }

    public function getName()
    {
        return $this -> Demo2 -> getName();
    }
}

然后是我們的使用方法:

一般的使用的方法是:

<?php
namespace app\index\controller;

class Demo
{
   public function index()
   {
       $demo3 = new \app\index\controller\Demo3();
       $demo2 = new \app\index\controller\Demo2($demo3);
       $demo1 = new \app\index\controller\Demo1($demo2);
       dump($demo1 -> text());
       dump($demo1 -> getName());
   }
}

你看,是不是很麻煩,一個類依賴另外一個類,一個一個的實例化,麻煩的很,但是你用tp5.1里面的方法就不用理會這些了,tp框架自動幫你實例化!

tp5.1的使用方法:

<?php
namespace app\index\controller;

class Demo
{
   public function index()
   {
       \think\Container::set('demo1' , '\app\index\controller\Demo1');
       $demo1 =  \think\Container::get('demo1');
       dump($demo1 -> text());
       dump($demo1 -> getName());

   }
}

這里的名稱和使用區分大小寫,請注意!!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM