tp5.1 依赖注入的使用

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

依赖注入的概念:

总结一点就是 底层类应该依赖于上层类,避免上层类依赖于底层类。

上代码:

首先先写几个需要用到的控制器;

demo3:

<?php
namespace appindexcontroller;

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 appindexcontroller;

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 appindexcontroller;

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 appindexcontroller;

class Demo
{
   public function index()
   {
       $demo3 = new appindexcontrollerDemo3();
       $demo2 = new appindexcontrollerDemo2($demo3);
       $demo1 = new appindexcontrollerDemo1($demo2);
       dump($demo1 -> text());
       dump($demo1 -> getName());
   }
}

你看,是不是很麻烦,一个类依赖另外一个类,一个一个的实例化,麻烦的很,但是你用tp5.1里面的方法就不用理会这些了,tp框架自动帮你实例化!

tp5.1的使用方法:

<?php
namespace appindexcontroller;

class Demo
{
   public function index()
   {
       	hinkContainer::set('demo1' , 'appindexcontrollerDemo1');
       $demo1 =  	hinkContainer::get('demo1');
       dump($demo1 -> text());
       dump($demo1 -> getName());

   }
}

这里的名称和使用区分大小写,请注意!!!

原文地址:https://www.cnblogs.com/laijinquan/p/10803964.html