[英]Is it possible to override injected Request from a Laravel Package?
我正在Laravel中構建一個具有資源控制器的自定義包。 對於此示例,資源是Organization
在此Controller中,定義了基本index
, show
, store
等操作。
這是我在控制器中的store
方法:
/**
* Store a newly created Organization in storage.
*
* @param OrganizationStoreRequest $request
* @return JsonResponse
*/
public function store($request): JsonResponse
{
$newOrganization = new Organization($request->all());
if ($newOrganization->save()) {
return response()->json($newOrganization, 201);
}
return response()->json([
'message' => trans('organilations::organisation.store.error')
], 500);
}
我的OrganzationStoreRequest
現在非常基本:
class OrganizationStoreRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'name' => 'required'
];
}
}
可以在API上調用store方法在Laravel應用程序中使用該包時。 我的問題是我想讓我的包的用戶能夠用自己的請求覆蓋我的OrganizationStoreRequest
,因為他們可能必須使用不同的授權或驗證方法。
我已經嘗試構建一個中間件並將我自己的實例綁定到OrganizationStoreRequests
但是我沒有得到我想要的結果。
無論如何,包的用戶是否能夠覆蓋我的包的控制器中的OrganizationStoreRequets
?
在Larachat的開發人員的幫助下,我們得到了以下(簡單)解決方案。
在創建自己的請求時,我們可以將它的實例綁定到IoC Container。 例如,創建OrganizationOverrideRule
並擴展原始內容:
class OrganizationOverrideRules extends OrganizationStoreRequest
{
public function rules(): array
{
return [
'name' => 'required',
'website' => 'required',
'tradename' => 'required'
];
}
}
然后在AppServiceProvider
您可以像這樣綁定新實例:
App::bind(
OrganizationStoreRequest::class,
OrganizationOverrideRules::class
);
然后, OrganizationOverrideRules
將用於驗證和授權。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.