Laravel源碼解析之反射的使用

clipboard.png

前言

PHP的反射類與實例化對象做用相反,實例化是調用封裝類中的方法、成員,而反射類則是拆封類中的全部方法、成員變量,幷包括私有方法等。就如「解刨」同樣,咱們能夠調用任何關鍵字修飾的方法、成員。固然在正常業務中是建議不使用,比較反射類已經摒棄了封裝的概念。php

本章講解反射類的使用及Laravel對反射的使用。laravel

反射

反射類是PHP內部類,無需加載便可使用,你能夠經過實例化 ReflectionClass 類去使用它。bootstrap

方法

這裏列舉下PHP反射類經常使用的方法設計模式

方法名 註釋
ReflectionClass::getConstant 獲取定義過的一個常量
ReflectionClass::getConstants 獲取一組常量
ReflectionClass::getConstructor 獲取類的構造函數
ReflectionClass::getDefaultProperties 獲取默認屬性
ReflectionClass::getDocComment 獲取文檔註釋
ReflectionClass::getEndLine 獲取最後一行的行數
ReflectionClass::getFileName 獲取定義類的文件名
ReflectionClass::getInterfaceNames 獲取接口(interface)名稱
ReflectionClass::getMethods 獲取方法的數組
ReflectionClass::getModifiers 獲取類的修飾符
ReflectionClass::getName 獲取類名
ReflectionClass::getNamespaceName 獲取命名空間的名稱
ReflectionClass::getParentClass 獲取父類

等等等等.... 全部關於類的方法、屬性及其繼承的父類、實現的接口均可以查詢到。
詳細文檔請參考官網: http://php.net/manual/zh/clas...api

栗子

<?php
    namespace A\B;
    
    class Foo { }
    
    $function = new \ReflectionClass('stdClass');
    
    var_dump($function->inNamespace());
    var_dump($function->getName());
    var_dump($function->getNamespaceName());
    var_dump($function->getShortName());
    
    $function = new \ReflectionClass('A\\B\\Foo');
    
    var_dump($function->inNamespace());
    var_dump($function->getName());
    var_dump($function->getNamespaceName());
    var_dump($function->getShortName());
?>

輸出結果數組

bool(false)
string(8) "stdClass"
string(0) ""
string(8) "stdClass"

bool(true)
string(7) "A\B\Foo"
string(3) "A\B"
string(3) "Foo"

Laravel

Laravel在實現服務容器加載時使用了反射類。如今咱們開啓「解刨」模式app

入口文件

index.php

$app = require_once __DIR__.'/../bootstrap/app.php';

/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can handle the incoming request
| through the kernel, and send the associated response back to
| the client's browser allowing them to enjoy the creative
| and wonderful application we have prepared for them.
|
*/

$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

$response->send();

$kernel->terminate($request, $response);

是引用語句發生的下一行調用了make方法。各位很清楚,make方法用於解析類,全部make方法的實現必定是在引用的文件內。ide

bootstrap\app.php

$app = new Illuminate\Foundation\Application(
    realpath(__DIR__.'/../')
);

laravel開始加載它的核心類,全部的實現從 Illuminate\Foundation\Application 開始。函數

Illuminate\Foundation\Application

public function make($abstract, array $parameters = [])
{
        $abstract = $this->getAlias($abstract);

        if (isset($this->deferredServices[$abstract]) && ! isset($this->instances[$abstract])) {
            $this->loadDeferredProvider($abstract);
        }

        return parent::make($abstract, $parameters);
}

在覈心類中你可能準確的查找到make方法的存在,它加載了服務提供者隨後調用了父類的方法make,要知道做爲獨立的模塊 「服務容器」是絕對不能寫在覈心類的。懂點設計模式的都很清楚。ui

Illuminate\Container\Container

$api = $this->app->make('HelpSpot\API',['id'=>1]); 爲例來說解

// 真正的make方法,它直接調用了resolve繼續去實現make的功能
// $abstract = 'HelpSpot\API'
public function make($abstract, array $parameters = [])
{
    // $abstract = 'HelpSpot\API'
    return $this->resolve($abstract, $parameters);
}

...

protected function resolve($abstract, $parameters = [])
{
    ...
    // 判斷是否能夠合理反射
    // $abstract = 'HelpSpot\API'
    if ($this->isBuildable($concrete, $abstract)) {
        // 實例化具體實例 (實際並非實例化,而是經過反射「解刨」了)
        $object = $this->build($concrete);
    } else {
        $object = $this->make($concrete);
    }
    ...
}

public function build($concrete)
{
        // $concrete = 'HelpSpot\API'
        if ($concrete instanceof Closure) {
            return $concrete($this, $this->getLastParameterOverride());
        }
        // 實例化反射類
        $reflector = new ReflectionClass($concrete);

        // 檢查類是否可實例化
        if (! $reflector->isInstantiable()) {
            return $this->notInstantiable($concrete);
        }

        $this->buildStack[] = $concrete;

        // 獲取類的構造函數
        $constructor = $reflector->getConstructor();
        
        if (is_null($constructor)) {
            array_pop($this->buildStack);

            return new $concrete;
        }

        $dependencies = $constructor->getParameters();

        $instances = $this->resolveDependencies(
            $dependencies
        );

        array_pop($this->buildStack);
           
        //  從給出的參數建立一個新的類實例。
        return $reflector->newInstanceArgs($instances);
}

可見一個服務容器就加載成功了。

致謝

感謝你看到這裏,本篇文章源碼解析靠我的理解。若有出入請拍磚。

但願本篇文章能夠幫到你。謝謝

相關文章
相關標籤/搜索