問題描述
我經(jīng)常使用 response()
助手,我只是將數(shù)據(jù)和一條消息返回給用戶.現(xiàn)在我還必須包含 http 狀態(tài)代碼,但我不想更改每個響應(yīng)(無論如何這可能很糟糕).
I'm using the response()
helper very often and I just return the data with a message to the user. Now I have to include the http status code as well, but I don't want to change every response (which is likely bad anyway).
所以我試圖通過在 app/Http/helpers.php
中創(chuàng)建我自己的 helpers.php
來覆蓋 response()
輔助函數(shù)代碼>.
So I'm trying to overwrite the response()
helper function by creating my own helpers.php
within app/Http/helpers.php
.
當(dāng)我將它添加到我的 Composer 文件時,它會首先從框架自動加載當(dāng)前的 helpers.php,當(dāng)我在 autload 包含在 bootstrap/global.php
之前添加它時,我將無法使用 app()
和其他 Laravel 函數(shù).
When I add it to my composer files, it does autoload the current helpers.php from the framework first and when I add it before the autload include in bootstrap/global.php
I wont be able to use the app()
and other Laravel functions.
我該如何解決這個問題?我只想在響應(yīng)數(shù)組中包含狀態(tài)代碼.
How would I be able to solve this issue? I just want to include the status code as well in the response array.
推薦答案
所有 Laravel 輔助函數(shù)都用這個邏輯編寫
All Laravel helper functions written with this logic
if ( ! function_exists('response'))
{
function response($content = '', $status = 200, array $headers = array())
{
// function body
}
}
首先 Laravel 檢查這個函數(shù)是否存在,如果存在,Laravel 不會再次定義這個函數(shù)(否則會拋出致命錯誤).因此,如果您將在自動加載器包含 vendor/laravel/framework/src/Illuminate/Foundation/helpers.php
文件之前定義您的函數(shù),您可以定義自定義響應(yīng)函數(shù).
for first Laravel check is this function exists, if it exists, Laravel will not define this function again(otherwise it will throw fatal error).
So if you will define your function before autoloader include vendor/laravel/framework/src/Illuminate/Foundation/helpers.php
file,
you can define your custom response function.
不幸的是,沒有辦法說 composer 首先加載你的 autoload.files
部分,然后是 laravel autoload.files
.但是你可以做一些小黑客......
Unfortunately there is no way to say composer load first your autoload.files
section, then laravel autoload.files
. But you can do small hack ...
打開 bootstrap/autoload.php
文件并在自動加載器之前包含您的文件
open bootstrap/autoload.php
file and include your file before autoloader
// file with your custom helper functions
require __DIR__.'/../app/app/Http/helpers.php';
require __DIR__.'/../vendor/autoload.php';
這篇關(guān)于覆蓋 Laravel 5 輔助函數(shù)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!