欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Laravel框架下路由的使用(源码解析)

程序员文章站 2023-01-25 13:49:13
本篇文章给大家带来的内容是关于Laravel框架下路由的使用(源码解析),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。 前言 我的解析文章并非深层次多领域的解析攻略。但是参考着开发文档看此类文章会让你在日常开发中更上一层楼。 废话不多说,我们开始本章的讲解。 入口 Laravel启 ......

本篇文章给大家带来的内容是关于laravel框架下路由的使用(源码解析),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

前言

我的解析文章并非深层次多领域的解析攻略。但是参考着开发文档看此类文章会让你在日常开发中更上一层楼。

废话不多说,我们开始本章的讲解。

入口

laravel启动后,会先加载服务提供者、中间件等组件,在查找路由之前因为我们使用的是门面,所以先要查到route的实体类。

注册

第一步当然还是通过服务提供者,因为这是laravel启动的关键,在 routeserviceprovider 内加载路由文件。

1

2

3

4

5

6

7

protected function mapapiroutes()

{

    route::prefix('api')

         ->middleware('api')

         ->namespace($this->namespace// 设置所处命名空间

         ->group(base_path('routes/api.php'));  //所得路由文件绝对路径

}

首先require是不可缺少的。因路由文件中没有命名空间。 illuminate\routing\router 下方法

1

2

3

4

5

6

7

8

9

10

protected function loadroutes($routes)

{

    if ($routes instanceof closure) {

        $routes($this);

    } else {

        $router = $this;

 

        require $routes;

    }

}

随后通过路由找到指定方法,依旧是 illuminate\routing\router 内有你所使用的所有路由相关方法,例如get、post、put、patch等等,他们都调用了统一的方法 addroute

1

2

3

4

public function addroute($methods, $uri, $action)

{

    return $this->routes->add($this->createroute($methods, $uri, $action));

}

之后通过 illuminate\routing\routecollection addtocollections 方法添加到集合中

1

2

3

4

5

6

7

8

9

10

protected function addtocollections($route)

{

    $domainanduri = $route->getdomain().$route->uri();

 

    foreach ($route->methods() as $method) {

        $this->routes[$method][$domainanduri] = $route;

    }

 

    $this->allroutes[$method.$domainanduri] = $route;

}

添加后的结果如下图所示

Laravel框架下路由的使用(源码解析)

调用

通过 illuminate\routing\router 方法开始运行路由实例化的逻辑

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

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 方用于执行控制器的方法

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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 调度方法内

1

2

3

4

5

6

7

protected function runcontroller()

{

     

    return $this->controllerdispatcher()->dispatch(

        $this, $this->getcontroller(), $this->getcontrollermethod()

    );

}

这里注意 getcontroller() 才是真正的将控制器实例化的方法

1

2

3

4

5

6

7

8

9

10

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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去调用子类的指定方法,也就是我们希望调用的自定义方法。

1

2

3

4

public function callaction($method, $parameters)

{

    return call_user_func_array([$this, $method], $parameters);

}