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:
<?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; } }
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);
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); }
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; } }
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:
<?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 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.