Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...