Home > Backend Development > PHP Tutorial > Laravel implements constructor automatic dependency injection method, laravel constructor_PHP tutorial

Laravel implements constructor automatic dependency injection method, laravel constructor_PHP tutorial

WBOY
Release: 2016-07-12 08:56:45
Original
792 people have browsed it

Laravel's method of implementing automatic dependency injection of constructors, laravel constructor

The example in this article describes how Laravel implements automatic dependency injection of constructors. Share it with everyone for your reference, the details are as follows:

Automatic dependency injection can be implemented in Laravel's constructor without the need to instantiate the required class before instantiation, as shown in the code:

<&#63;php
namespace Lio\Http\Controllers\Forum;
use Lio\Forum\Replies\ReplyRepository;
use Lio\Forum\Threads\ThreadCreator;
use Lio\Forum\Threads\ThreadCreatorListener;
use Lio\Forum\Threads\ThreadDeleterListener;
use Lio\Forum\Threads\ThreadForm;
use Lio\Forum\Threads\ThreadRepository;
use Lio\Forum\Threads\ThreadUpdaterListener;
use Lio\Http\Controllers\Controller;
use Lio\Tags\TagRepository;
class ForumThreadsController extends Controller implements ThreadCreatorListener, ThreadUpdaterListener, ThreadDeleterListener
{
 protected $threads;
 protected $tags;
 protected $currentSection;
 protected $threadCreator;
 public function __construct(
  ThreadRepository $threads,
  ReplyRepository $replies,
  TagRepository $tags,
  ThreadCreator $threadCreator
 ) {
  $this->threads = $threads;
  $this->tags = $tags;
  $this->threadCreator = $threadCreator;
  $this->replies = $replies;
 }
}

Copy after login

Pay attention to several type constraints in the constructor. In fact, there is no place to instantiate this Controller and pass these types of parameters in. Laravel will automatically detect the type constraint parameters in the constructor of the class and automatically identify whether Initialized and passed in.

The build method in the source code vendor/illuminate/container/Container.php:

$constructor = $reflector->getConstructor();
dump($constructor);

Copy after login

The constructor of the class will be parsed here, print it here:

It will find out the parameters of the constructor, and then look at the complete operation of the build method:

public function build($concrete, array $parameters = [])
{
 // If the concrete type is actually a Closure, we will just execute it and
 // hand back the results of the functions, which allows functions to be
 // used as resolvers for more fine-tuned resolution of these objects.
 if ($concrete instanceof Closure) {
  return $concrete($this, $parameters);
 }
 $reflector = new ReflectionClass($concrete);
 // If the type is not instantiable, the developer is attempting to resolve
 // an abstract type such as an Interface of Abstract Class and there is
 // no binding registered for the abstractions so we need to bail out.
 if (! $reflector->isInstantiable()) {
  $message = "Target [$concrete] is not instantiable.";
  throw new BindingResolutionContractException($message);
 }
 $this->buildStack[] = $concrete;
 $constructor = $reflector->getConstructor();
 // If there are no constructors, that means there are no dependencies then
 // we can just resolve the instances of the objects right away, without
 // resolving any other types or dependencies out of these containers.
 if (is_null($constructor)) {
  array_pop($this->buildStack);
  return new $concrete;
 }
 $dependencies = $constructor->getParameters();
 // Once we have all the constructor's parameters we can create each of the
 // dependency instances and then use the reflection instances to make a
 // new instance of this class, injecting the created dependencies in.
 $parameters = $this->keyParametersByArgument(
  $dependencies, $parameters
 );
 $instances = $this->getDependencies(
  $dependencies, $parameters
 );
 array_pop($this->buildStack);
 return $reflector->newInstanceArgs($instances);
}

Copy after login

Specific method of obtaining instances from containers:

protected function resolveClass(ReflectionParameter $parameter)
{
 try {
  return $this->make($parameter->getClass()->name);
 }
 // If we can not resolve the class instance, we will check to see if the value
 // is optional, and if it is we will return the optional parameter value as
 // the value of the dependency, similarly to how we do this with scalars.
 catch (BindingResolutionContractException $e) {
  if ($parameter->isOptional()) {
   return $parameter->getDefaultValue();
  }
  throw $e;
 }
}

Copy after login

The bottom layer of the framework saves a lot of details for development through Reflection and realizes automatic dependency injection. No further in-depth research will be conducted here.

Written a class test that simulates this process:

<&#63;php
class kulou
{
 //
}
class junjun
{
 //
}
class tanteng
{
 private $kulou;
 private $junjun;
 public function __construct(kulou $kulou,junjun $junjun)
 {
  $this->kulou = $kulou;
  $this->junjun = $junjun;
 }
}
//$tanteng = new tanteng(new kulou(),new junjun());
$reflector = new ReflectionClass('tanteng');
$constructor = $reflector->getConstructor();
$dependencies = $constructor->getParameters();
print_r($dependencies);exit;

Copy after login

The principle is to parse the constructor of the class through the ReflectionClass class, and take out the parameters of the constructor to determine the dependency relationship, retrieve it from the container, and automatically inject it.

Reprinted from: Xiaotan Blog http://www.tantengvip.com/2016/01/laravel-construct-ioc/

Readers who are interested in more information about Laravel can check out the special topics on this site: "Introduction and Advanced Tutorial on Laravel Framework", "Summary of PHP Excellent Development Framework", "Basic Tutorial on Getting Started with Smarty Templates", "php Date and Time" Usage Summary", "php object-oriented programming introductory tutorial", "php string (string) usage summary", "php mysql database operation introductory tutorial" and "php common database operation skills summary"

I hope this article will be helpful to everyone’s PHP program design based on the Laravel framework.

Articles you may be interested in:

  • PHP's Laravel framework combined with MySQL and Redis database deployment
  • Using message queue queue and asynchronous queue in PHP's Laravel framework Method
  • Laravel executes the migrate command prompt: No such file or directory solution
  • Detailed explanation of usage examples of Trait in Laravel
  • Detailed explanation of the steps to register Facades in Laravel
  • How Laravel uses Caching to cache data to reduce database query pressure
  • Making an APP interface (API) based on laravel
  • Detailed explanation of the use of Eloquent object-relational mapping in PHP's Laravel framework
  • Summary of CURD operations and coherent operations in Laravel framework database
  • In-depth analysis of event operations in PHP's Laravel framework

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1111349.htmlTechArticleLaravel's method to implement automatic dependency injection of constructors, laravel constructor This article describes the example of Laravel's implementation of automatic dependency injection of constructors method. Sharing it with everyone for your reference,...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template