Case Analysis of thinkphp 5.1 Framework Container and Dependency Injection

  • 2021-12-13 16:29:42
  • OfStack

This article illustrates the thinkphp 5.1 framework container and dependency injection. Share it for your reference, as follows:

Container-/thinkphp/library/think/Container. php

Dependency injection: Pass the data of an object type to a method as a parameter (solve the problem of passing an object to a method in a class)

Bind 1 class to container:


public function bindClass()
{
  // Put 1 Classes are put into the container: equivalent to registering in the container 
  \think\Container::set('tmp (Alias) ','\app\common\Temp( Instances )');
  // Helper function bind();
  bind('tmp (Alias) ','\app\common\Temp( Instances )');
  // Instantiate and take out the class in the container and initialize it by calling the constructor at the same time of instantiation 
  $tmp = \think\Container::get('tmp',['name' => 'you']);
  $tmp = app('tmp',['name' => 'you']);// Helper function 
  return $tmp->getName();
}

Bind 1 closure to container:


public function bindClosure()
{
  // Put 1 Closures are put into the container 
  \think\Container::set('demo',function($domain) {
    return ' Domain name: ' . $domain;
  });
  // Take out the closure in the container and use it 
  return \think\Container::get('demo',['domain' => 'www.php.cn']);
}

Readers who are interested in thinkPHP can check the topics of this site: "ThinkPHP Introduction Tutorial", "thinkPHP Template Operation Skills Summary", "ThinkPHP Common Methods Summary", "codeigniter Introduction Tutorial", "CI (CodeIgniter) Framework Advanced Tutorial", "Zend FrameWork Framework Introduction Tutorial" and "PHP Template Technology Summary".

I hope this article is helpful to the PHP programming based on ThinkPHP framework.


Related articles: