Related recommendations:thinkphp
ThinkPHP’s## The #Containerclass provides a static method
get(), which can obtain an instance based on the class name or class alias. The created instance will be kept to avoid repeated creation. To implement this method, modify
Container.phpand add the following code.
// * ThinkPHP 5 与 6 在此处参数一致// * @param string $abstract// * @param array $vars// * @param bool $newInstance// */ public static function get(string $abstract, array $vars = [], bool $newInstance = false) { return static::getInstance()->make($abstract, $vars, $newInstance); }
getInstance()method, and add a new static attribute
$instanceto save its own instance.
protected static $instance;public static function getInstance() { // 创建自身实例 if (is_null(static::$instance)) { static::$instance = new static; } return static::$instance; }
make()method.
public function make (string $abstract, array $vars = [], bool $newInstance = false) { // 这里的 $abstract 是包含有命名空间的类名 if (isset($this->bind[$abstract])) { $abstract = $this->bind[$abstract]; } // 如果已经实例化直接返回 if (isset($this->instances[$abstract]) && !$newInstance) { return $this->instances[$abstract]; } // 如果就创建 $object = $this->invokeClass($abstract, $vars); // 保存实例 if (!$newInstance) { $this->instances[$abstract] = $object; } return $object; }
$bind
protected $bind = [ 'app' => App::class, 'config' => Config::class, 'request' => Request::class ];
invokeClass()Method
public function invokeClass (string $class, array $vars = []) { // $vars 为构造函数的参数 return new $class(); }
index.php
require __DIR__ . '/../core/base.php';use think\Request;$req = \think\Container::get('request');var_dump($req instanceof Request);
get()method functions normally.
__get()and
__set()to allow external objects to directly operate the container instance.
public function __get($abstract) { // 返回容器的类实例 return $this->make($abstract); }public function __set($abstract, $instance) { if (isset($this->bind[$abstract])) { $abstract = $this->bind[$abstract]; } // 装入容器 $this->instances[$abstract] = $instance; }
index.php
$container = \think\Container::getInstance();// 获取容器中的实例,输出对象var_dump($container->request);// 装入容器$container->contianerName = $container;var_dump($container->contianerName);
Want to learn more about programming , please pay attention to thephp trainingcolumn!
The above is the detailed content of Using the Container class to implement the ThinkPHP core framework. For more information, please follow other related articles on the PHP Chinese website!