hi,你好!欢迎访问本站!登录
本站由简数采集腾讯云宝塔系统阿里云强势驱动
当前位置:首页 - PHP框架 - Laravel - 正文 请牢记本站网址www.sosophp.cn

Laravel框架下路由的运用(源码剖析)【laravel框架】

2019-11-27Laravel搜搜PHP网69°c
A+ A-
本篇文章给人人带来的内容是关于Laravel框架下路由的运用(源码剖析),有肯定的参考价值,有须要的朋侪能够参考一下,愿望对你有所协助。

媒介

我的剖析文章并不是深层次多范畴的剖析攻略。然则参考着开辟文档看此类文章会让你在一样平常开辟中更上一层楼。

空话不多说,我们最先本章的解说。

进口

Laravel启动后,会先加载效劳提供者、中间件等组件,在查找路由之前由于我们运用的是门面,所以先要查到Route的实体类。

注册

第一步固然照样经由过程效劳提供者,由于这是laravel启动的症结,在 RouteServiceProvider 内加载路由文件。

protected function mapApiRoutes()
{
    Route::prefix('api')
         ->middleware('api')
         ->namespace($this->namespace)  // 设置所处定名空间
         ->group(base_path('routes/api.php'));  //所得路由文件绝对路径
}

起首require是不可缺乏的。因路由文件中没有定名空间。 Illuminate\Routing\Router 下要领

protected function loadRoutes($routes)
{
    if ($routes instanceof Closure) {
        $routes($this);
    } else {
        $router = $this;

        require $routes;
    }
}

随后经由过程路由找到指定要领,照旧是 Illuminate\Routing\Router 内有你所运用的一切路由相干要领,比方get、post、put、patch等等,他们都挪用了一致的要领 addRoute

public function addRoute($methods, $uri, $action)
{
    return $this->routes->add($this->createRoute($methods, $uri, $action));
}

以后经由过程 Illuminate\Routing\RouteCollection addToCollections 要领增加到鸠合中

protected function addToCollections($route)
{
    $domainAndUri = $route->getDomain().$route->uri();

    foreach ($route->methods() as $method) {
        $this->routes[$method][$domainAndUri] = $route;
    }

    $this->allRoutes[$method.$domainAndUri] = $route;
}

增加后的效果如下图所示

挪用

经由过程 Illuminate\Routing\Router 要领最先运转路由实例化的逻辑

protected function runRoute(Request $request, Route $route)
{
    $request->setRouteResolver(function () use ($route) {
        
        return $route;
    });
    $this->events->dispatch(new Events\RouteMatched($route, $request));

    return $this->prepareResponse($request,
        $this->runRouteWithinStack($route, $request)
    );
}
....
protected function runRouteWithinStack(Route $route, Request $request)
{
    $shouldSkipMiddleware = $this->container->bound('middleware.disable') &&
                            $this->container->make('middleware.disable') === true;

    $middleware = $shouldSkipMiddleware ? [] : $this->gatherRouteMiddleware($route);

    return (new Pipeline($this->container))
                    ->send($request)
                    ->through($middleware)
                    ->then(function ($request) use ($route) {
                        return $this->prepareResponse(
                            $request, $route->run() // 此处挪用run要领
                        );
                    });
}

Illuminate\Routing\Route 下 run 方用于实行控制器的要领

public function run()
{
    $this->container = $this->container ?: new Container;

    try {
        if ($this->isControllerAction()) { 
            return $this->runController(); //运转一个路由并作出相应
        }
            
        return $this->runCallable();
    } catch (HttpResponseException $e) {
        return $e->getResponse();
    }
}

从上述要领内能够看出 runController 是运转路由的症结,要领内运转了一个调理顺序,将控制器 $this->getController() 和控制器要领 $this->getControllerMethod() 传入到 dispatch 调理要领内

protected function runController()
{
    
    return $this->controllerDispatcher()->dispatch(
        $this, $this->getController(), $this->getControllerMethod()
    );
}

这里注重 getController() 才是真正的将控制器实例化的要领

public function getController()
{
    
    if (! $this->controller) {
        $class = $this->parseControllerCallback()[0]; // 0=>控制器 xxController 1=>要领名 index
        $this->controller = $this->container->make(ltrim($class, '\\')); // 交给容器举行反射
    }

    return $this->controller;
}

实例化

照旧经由过程反射加载路由指定的控制器,这个时刻build的参数$concrete = App\Api\Controllers\XxxController

public function build($concrete)
{
    // 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, $this->getLastParameterOverride());
    }
    
    $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()) {
        return $this->notInstantiable($concrete);
    }
    
        
    $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.
    $instances = $this->resolveDependencies(
        $dependencies
    );

    array_pop($this->buildStack);
    
    return $reflector->newInstanceArgs($instances);
}

这时候将返回控制器的实例,下面将经由过程url接见指定要领,平常控制器都邑继续父类 Illuminate\Routing\Controller ,laravel为其设置了别号 BaseController

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));
}

Laravel经由过程controller继续的callAction去挪用子类的指定要领,也就是我们愿望挪用的自定义要领。

public function callAction($method, $parameters)
{
    return call_user_func_array([$this, $method], $parameters);
}

以上就是Laravel框架下路由的运用(源码剖析)的细致内容,更多请关注ki4网别的相干文章!

  选择打赏方式
微信赞助

打赏

QQ钱包

打赏

支付宝赞助

打赏

  选择分享方式
  移步手机端
Laravel框架下路由的运用(源码剖析)【laravel框架】

1、打开你手机的二维码扫描APP
2、扫描左则的二维码
3、点击扫描获得的网址
4、可以在手机端阅读此文章
标签: