Blogger Information
Blog 56
fans 3
comment 1
visits 50681
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
容器注入和Facade——2018年5月29日
沈斌的博客
Original
677 people have browsed it

注入让类之间解耦,解耦后通过参数传入类的实例,而不是在某个类内部实例化其他类。代码修改更加方便。

容器注入是在注入的前提下,通过容器管理各个依赖类,保存在关联数组中。类和相应的实例化方法绑定bind,

实例化参数传入容器完成实例化,make.

Facade 方便了调用,都采用静态调用。Facade中调用Container中的make 方法,完成各个类的实例化。


container.php

实例

<?php

class Db {
    public function connect()
    {
        return 'connect db success<br>';
    }
}

class Validate
{
    public function check()
    {
        return 'validate success<br>';
    }
}

class View
{
    public function login()
    {
        return 'login success <br>';
    }
}

// 创建容器类
class Container
{
    public $instance=[];

    // 类名与实例化方法绑定
    public function bind($abstract,Closure $process)
    {
        $this->instance[$abstract]=$process;
    }

    public function make($abstrct,$params=[])
    {
        return call_user_func_array($this->instance[$abstrct],$params);
    }
}

$container=new Container();
$container->bind('db',function(){
    return new DB();
});

$container->bind('validate',function(){
    return new Validate();
});

$container->bind('view',function(){
    return new View();
});

运行实例 »

点击 "运行实例" 按钮查看在线实例

demo.php

实例

<?php
require 'container.php';

class Facade
{
    protected static $container=null;

    public static function initialize(Container $container)
    {
        static::$container=$container;
    }

    public static function connect()
    {
        return static::$container->make('db')->connect();
    }

    public static function check()
    {
        return static::$container->make('validate')->check();
    }

    public static function display()
    {
        return static::$container->make('view')->login();
    }
}

Facade::initialize($container);

echo Facade::connect();
echo Facade::check();
echo Facade::display();

运行实例 »

点击 "运行实例" 按钮查看在线实例

Facade.png

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post