Overwrite laravel 5 helper function(覆盖 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 辅助函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:覆盖 Laravel 5 辅助函数
基础教程推荐
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- PHP 守护进程/worker 环境 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01