Laravel dependency injection through source code parsing, and laravel source code parsing

Source: Internet
Author: User

Laravel dependency injection through source code parsing, and laravel source code parsing

Preface

As we all know, php frameworks are countless. In recent years, a framework famous for its elegance has gradually been known and used by phper in China. However, larave has an obvious drawback, he has little content in the document.

This article will give you a detailed introduction to Laravel dependency injection and share it for your reference. I will not talk about it much below. Let's take a look at the detailed introduction.

The construction method or member method of the Controller in Laravel can use dependency injection by type constraints, such:

public function store(Request $request){ //TODO}

Here, the $ request parameter uses the type constraint. The Request is a class: \ Illuminate \ Http \ Request, indicating that the parameter must be this class or a subclass.

This article analyzes the Laravel source code to see why the Request can be directly used without passing in an instance in the method? The framework will automatically instantiate and pass parameters.

1. Route Definition

Starting from the source, the routing definition file defines such a route:

Route::resource('/role', 'Admin\RoleController');

This is a resource-based route. Laravel will automatically generate a route entry for addition, deletion, modification, and query.

The store method at the beginning of this article is a controller method. As shown in the figure, the Action defined by the route is: App \ Http \ Controllers \ Admin \ RoleController @ store

Route Method Analysis

Find the controller and method according to the route definition, and execute the specific method to implement it in the dispatch method.

(File: vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher. php)

public function dispatch(Route $route, $controller, $method){ $parameters = $this->resolveClassMethodDependencies(  $route->parametersWithoutNulls(), $controller, $method );  if (method_exists($controller, 'callAction')) {  return $controller->callAction($method, $parameters); }  return $controller->{$method}(...array_values($parameters));}

First, the resolveClassMethodDependencies method. "as the name suggests" is to obtain the dependent object based on the method parameters of the class, then call the class method and inject the object parameters.

If multiple dependent objects exist, the foreach will be parsed in sequence and injected as parameters.

Code for obtaining the dependent object example:

protected function resolveClassMethodDependencies(array $parameters, $instance, $method){ if (! method_exists($instance, $method)) {  return $parameters; }  return $this->resolveMethodDependencies(  $parameters, new ReflectionMethod($instance, $method) );}

The focus here is to use PHP reflection. Pay attention to the RelectionMethod method. It obtains the method parameter list of the class and can know the type constraints and parameter names of the parameters.

The $ instance parameter here is the RoleController class, and the $ method parameter is the method name strore.

2. Example of obtaining dependent objects

Obtain the constraint type of the dependent object from the method parameters, and then the dependent object can be instantiated.

protected function transformDependency(ReflectionParameter $parameter, $parameters){ $class = $parameter->getClass();  // If the parameter has a type-hinted class, we will check to see if it is already in // the list of parameters. If it is we will just skip it as it is probably a model // binding and we do not want to mess with those; otherwise, we resolve it here. if ($class && ! $this->alreadyInParameters($class->name, $parameters)) {  return $parameter->isDefaultValueAvailable()   ? $parameter->getDefaultValue()   : $this->container->make($class->name); }}

Get the object from the container according to the class name. The process of binding the object instance is defined and defined first by the service provider.

Then, pass the instantiated object to the store method to use the dependent object.

3. PHP reflection

For example, use ReflectionMethod.

class Demo{ private $request; public function store(Request $request) { }}

Print the content of new ReflectionMethod (Demo: class, 'store ').

The parameter list of this method can be obtained. The constraint types of the parameters, such as typeHint, Illuminate \ Http \ Request.

You can obtain instances bound by the service provider from the container based on the class name.

Summary

The above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.

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.