LoginSignup
2
2

More than 3 years have passed since last update.

Lravel Routeを追ってみた。

Last updated at Posted at 2019-06-27
\routes\web.php
Route::get($uri, $action);

これを追ってみます。

Aliases

まずエイリアスを見てみます。

config\app.php
'aliases' => [
'Route' => Illuminate\Support\Facades\Route::class,
],

となっていますね。
見てみましょう。

Illuminate\Support\Facades\Route.php
<?php

namespace Illuminate\Support\Facades;

/**
 * @see \Illuminate\Routing\Router
 */
class Route extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return 'router';
    }
}

この記述があるだけで、get()はありません。
ですが、この'router';が大事なんですね。

継承元のFacadeを見てみます。

Illuminate\Support\Facades.php
namespace Illuminate\Support\Facades;

use Closure;
use Mockery;
use RuntimeException;
use Mockery\MockInterface;

abstract class Facade
{

public static function getFacadeRoot()
    {
        return static::resolveFacadeInstance(static::getFacadeAccessor());
    }

protected static function resolveFacadeInstance($name)
    {
        if (is_object($name)) {
            return $name;
        }

        if (isset(static::$resolvedInstance[$name])) {
            return static::$resolvedInstance[$name];
        }

        return static::$resolvedInstance[$name] = static::$app[$name];
    }

public static function __callStatic($method, $args)
    {
        $instance = static::getFacadeRoot();

        if (! $instance) {
            throw new RuntimeException('A facade root has not been set.');
        }

        return $instance->$method(...$args);
    }
}

まず__callStaticがあります。
実装されていない静的メンバが実行された際に走る処理です。
get()と言うメソッドはここにもないので__callStaticの処理が走ります。

getFacadeRoot();では見ての通りです。
オーバーライドされたgetFacadeAccessor();にはrouterがreturneされていました。
よってreturn static::resolveFacadeInstance('router');となりメソッドが実行されます。

resolveFacadeInstance('router')では、オブジェクトかの判断やnullではないかの処理が設定されています。

そして、最後のstatic::$app[$name];この部分。
$appにはIlluminate\Foundation\Application.phpが格納されています。
つまりサービスコンテナでrouterで登録されているインスタンスを取得しreturnしています。
サービスコンテナ一覧

もう一度__callStaticに戻ります。
ちなみに__callStaticは第一引数の$methodに呼び出そうとしたメソッドが格納されます。

Illuminate\Support\Facades.php
public static function __callStatic($method, $args)
    {
        $instance = static::getFacadeRoot();

        if (! $instance) {
            throw new RuntimeException('A facade root has not been set.');
        }

        return $instance->$method(...$args);
    }

$instanceにはrouterで登録されているインスタンスが格納されました。
つまりこのインスタンスですねIlluminate\Routing\Router::Class

そして、最後のreturnで$methodを実行。
つまりこう言うことでしょう。

Illuminate\Routing\Router->get();

なので、Route::get()が成り立つのですね。
と言うことはaliasesはサービスコンテナからインスタンスを生成するためだけに設定されているものなのでしょうか。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2