溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Laravel中怎么實現(xiàn)依賴注入

發(fā)布時間:2021-07-19 14:39:58 來源:億速云 閱讀:154 作者:Leah 欄目:開發(fā)技術

這期內容當中小編將會給大家?guī)碛嘘PLaravel中怎么實現(xiàn)依賴注入,文章內容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

1.路由定義

從源頭開始看起,在路由定義文件中定義了這么一個路由:

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

這是一個資源型的路由,Laravel 會自動生成增刪改查的路由入口。

Laravel中怎么實現(xiàn)依賴注入

本文開頭的 store 方法就是一個控制器的方法,圖中可見路由定義的 Action 也是:App\Http\Controllers\Admin\RoleController@store

路由方法解析

根據(jù)路由定義找到控制器和方法,執(zhí)行具體的方法在 dispatch 方法中實現(xiàn)。

(文件: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));
}

首先 resolveClassMethodDependencies 方法,“顧名思義”是根據(jù)類的方法參數(shù)獲取依賴對象,然后再調用類的方法并把對象參數(shù)注入。

如果有多個依賴對象,也會 foreach 依次解析出來作為參數(shù)注入。

獲取依賴對象示例的代碼:

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

這里重點就是用到了 PHP 的反射,注意 RelectionMethod 方法,它獲取到類的方法參數(shù)列表,可以知道參數(shù)的類型約束,參數(shù)名稱等等。

這里的 $instance 參數(shù)就是 RoleController 控制器類,$method 參數(shù)就是方法名稱 strore.

2.獲取依賴對象的示例

從方法的參數(shù)中獲取了依賴對象的約束類型,就可以實例化這個依賴的對象。

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

根據(jù)類名從容器中獲取對象,這個綁定對象實例的過程在服務提供者中先定義和了。

然后把實例化的對象傳入到 store 方法中,就可以使用依賴的對象了。

3.關于 PHP 反射

舉個使用 ReflectionMethod 的例子。

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

打印出 new ReflectionMethod(Demo::class, ‘store') 的內容如圖:

Laravel中怎么實現(xiàn)依賴注入

可以得出這個方法的參數(shù)列表,參數(shù)的約束類型,如 typeHint,Illuminate\Http\Request.

根據(jù)類名可以從容器中獲取一開始通過服務提供者綁定的實例。

上述就是小編為大家分享的Laravel中怎么實現(xiàn)依賴注入了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI