覆盖Laravel 5助手功能 [英] Overwrite laravel 5 helper function

查看:60
本文介绍了覆盖Laravel 5助手功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常使用response()助手,我只是将数据和一条消息返回给用户.现在,我还必须包括http状态代码,但是我不想更改每个响应(无论如何可能都是不好的).

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中创建自己的helpers.php来覆盖response()辅助函数.

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

当我将其添加到我的作曲家文件中时,它会首先自动从框架中自动加载当前的helpers.php,并且在bootstrap/global.php中的autload包含之前添加它时,我将无法使用app()和其他Laravel功能.

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.

推荐答案

使用此逻辑编写的所有Laravel帮助器功能

All Laravel helper functions written with this logic

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

首先检查Laravel是否存在此函数,如果存在,Laravel将不再定义此函数(否则将引发致命错误). 因此,如果您要在自动加载器包含vendor/laravel/framework/src/Illuminate/Foundation/helpers.php文件之前定义函数, 您可以定义您的自定义响应函数.

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.

不幸的是,没有办法说作曲家首先加载您的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';

这篇关于覆盖Laravel 5助手功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆