Laravel method for realizing automatic dependency injection of constructors _php example

Source: Internet
Author: User
Tags closure reflection reflector smarty template

This article illustrates the method of Laravel to realize the automatic dependency injection of constructors. Share to everyone for your reference, specific as follows:

Automatic dependency injection can be implemented in Laravel constructors without requiring the instantiation of the required class before instantiating, as shown in the code:

 <?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, Threadcreat
  or $threadCreator) {$this->threads = $threads;
  $this->tags = $tags;
  $this->threadcreator = $threadCreator;
 $this->replies = $replies; }
}

Note that there are several types of constraints in the constructor, in fact, there is no place to instantiate the controller and pass the parameters of these types, Laravel automatically detects the type constraint parameters in the class's constructor and automatically recognizes whether it is initialized and passed in.

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

$constructor = $reflector->getconstructor ();
Dump ($constructor);

This resolves the constructor of the class, which is printed here:

It finds the parameters of the constructor, and then looks at the operation of the complete build method:

Public function builds ($concrete, array $parameters = []) {//If the concrete type is actually a Closure, we'll just E Xecute it and//hand back the results of the functions, which allows, functions to is//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 isn't instantiable, the developer is attempting to resolve//an abstract type such as a Interface of Ab
 Stract 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 the OB JectsRight away, without//resolving any of the 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 the//dependency instances and then use the Refle
 Ction 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);

 }

How to get an instance from a container specifically:

protected function Resolveclass (Reflectionparameter $parameter)
{
 try {return
  $this->make ($ Parameter->getclass ()->name);
 If we can not resolve the class instance, we'll check to the if the value
 /are optional, and if it is we re Turn the optional parameter value
 AS//the value of the dependency, similarly to "how we Do" with scalars.
 catch (Bindingresolutioncontractexception $e) {
  if ($parameter->isoptional ()) {return
   $parameter-> Getdefaultvalue ();
  }
  throw $e;
 }
}

The bottom layer of the framework saves a lot of detail through reflection reflection and realizes automatic dependency injection. There's no further research here.

Wrote a class test that simulates the process:

<?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;

The principle is to resolve the constructor of the class by Reflectionclass class, and take out the parameters of the constructor, thus judging the dependencies, taking them from the container and automatically injecting them.

Turn from: Small Talk blog http://www.tantengvip.com/2016/01/laravel-construct-ioc/

More interested in laravel related content readers can view the site topics: "Laravel Framework Introduction and Advanced Course", "PHP Excellent Development Framework Summary", "Smarty Template Primer Tutorial", "PHP date and Time usage summary", "PHP object-oriented Program Design Introductory Course ", PHP string (String) Usage summary," PHP+MYSQL Database operation Introduction Tutorial "and" PHP common database Operation Skills Summary "

I hope this article will help you with the PHP program design based on Laravel framework.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.