Laravel implement the method of automatic dependency injection of constructors, Laravel constructor _php tutorial

Source: Internet
Author: User
Tags reflector

Laravel implements the method of automatic dependency injection of constructors, Laravel constructor


This paper describes the method of laravel implementation of automatic dependency injection of constructors. Share to everyone for your reference, as follows:

Automatic dependency injection can be implemented in the constructor of Laravel without the need to instantiate the class before instantiating it, as shown in the code:

<?phpnamespace 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 $threadC  Reator) {$this->threads = $threads;  $this->tags = $tags;  $this->threadcreator = $threadCreator; $this->replies = $replies; }}

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

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

$constructor = $reflector->getconstructor ();d UMP ($constructor);

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

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

Public function build ($concrete, array $parameters = []) {//If the concrete type is actually a Closure, we'll just exec Ute it and//hand back the results of the functions, which allows functions to being//used as resolvers for more fine-tune D resolution of these objects. if ($concrete instanceof Closure) {return $concrete ($this, $parameters);} $reflector = new Reflectionclass ($concrete); If the type is not instantiable, the developer are attempting to resolve//a abstract type such as an Interface of Abs Tract Class and there are//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 is no constructors, that means there is no dependencies then//We can just resolve the instances of the obj ECTs right away, withoutResolving any and 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 Reflec tion instances to make a//new instance of this class, injecting the created dependencies in. $parameters = $this->key Parametersbyargument ($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 see If the value//are optional, and if it is we'll retu RN 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; }}

The bottom layer of the frame is developed by reflection reflection to save a lot of detail and realize automatic dependency injection. There's no further research here.

Write a class test that simulates the process:

<?phpclass 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 ();p rint_r ($dependencies); exit;

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, fetch from the container, and inject it automatically.

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

More interested in laravel related content readers can view this site topic: "Laravel Framework Introductory and Advanced tutorial", "PHP Excellent Development Framework Summary", "Smarty Template Primer Basic Tutorial", "PHP date and Time usage summary", "PHP object-oriented Programming introduction tutorial "," PHP String Usage Summary "," Introduction to Php+mysql Database Operations "and" PHP common database Operation Skills Summary "

It is hoped that this article is helpful to the PHP program design based on Laravel framework.

Articles you may be interested in:

    • PHP's Laravel framework combined with MySQL and Redis database deployment
    • Methods for using Message Queuing queue and asynchronous queues in PHP's Laravel framework
    • Laravel Execute migrate command prompt: No such solution for file or directory
    • A detailed example of trait usage in Laravel
    • Steps to register facades in Laravel
    • Laravel ways to reduce database query pressure using caching cache data
    • Create an App interface (API) based on Laravel
    • Eloquent Object relational mapping in PHP's Laravel framework using
    • Laravel Framework Database curd operation and coherent operation summary
    • In-depth parsing of event events operations in PHP's Laravel framework

http://www.bkjia.com/PHPjc/1111349.html www.bkjia.com true http://www.bkjia.com/PHPjc/1111349.html techarticle Laravel Implement the method of automatic dependency injection of constructors, Laravel constructor function This paper describes the method of laravel implementation of automatic dependency injection of constructors. Share to everyone for your reference, ...

  • 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.