PHP's own framework 2.0 sets constants and binds containers (Refactoring Part 3)

Table of contents

1. Set constants and bind containers

2. The container adds the ability to set the instance of the current container and bind a class instance as the container

3. Bind constants to the container

4. Operation effect


1. Set constants and bind containers

2. The container adds the ability to set the instance of the current container and bind a class instance as the container
 //设置当前容器的实例

    public static function setInstance($instance)
    {
        static::$instance = $instance;
    }


    //绑定一个类实例当容器

    public function bandInstance($abstract, $instance)
    {
        if ($instance instanceof \Closure) {
            $this->bind[$abstract] = $instance;
        } else {
            if (isset($this->bind[$abstract])) {
                $abstract = $this->bind[$abstract];
            }

            $this->instances[$abstract] = $instance;
        }

        return $this;
    }
3. Bind constants to the container
<?php
namespace fm;
class core extends Di{
    protected $corePath;//核心目录路径
    protected $rootPath;//项目根目录
    public function __construct($appPath = '')
    {

    }
    public  function run(){
        $this->_int();//初始化常量
        echo '框架运行中';
    }
     public function _int(){

         //获取框架核心路径 都替换/以便兼容linux
         $path=str_replace("\\","/",__FILE__);
         //定义常量
         $this->corePath=dirname(dirname($path));
         $this->rootPath=dirname($this->corePath);
         static::setInstance($this);
         $this->bandInstance('core', $this);
         var_dump( $this->getInstance());
         exit;
     }

}
4. Operation effect

Guess you like

Origin blog.csdn.net/weixin_39934453/article/details/132858653