覆盖 Laravel 5 辅助函数 [英] Overwrite laravel 5 helper function

查看:23
本文介绍了覆盖 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.

当我将它添加到我的 Composer 文件时,它会首先从框架自动加载当前的 helpers.php,当我在 autload 包含在 bootstrap/global.php 之前添加它时,我将无法使用 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.

不幸的是,没有办法说 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';

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

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