Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

php - Overwrite laravel 5 helper function

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).

So I'm trying to overwrite the response() helper function by creating my own helpers.php within app/Http/helpers.php.

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.

How would I be able to solve this issue? I just want to include the status code as well in the response array.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

All Laravel helper functions written with this logic

if ( ! function_exists('response'))
{
    function response($content = '', $status = 200, array $headers = array())
    {
         // function body
    }
}

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.

Unfortunately there is no way to say composer load first your autoload.files section, then laravel autoload.files. But you can do small hack ...

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';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...