如何在laravel 5中创建全局助手功能? [英] How do I make global helper functions in laravel 5?

查看:103
本文介绍了如何在laravel 5中创建全局助手功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想为某些oauth东西创建一个currentUser()函数,我正在做的事情是我可以在视图或控制器中使用它(想想如何在应用程序控制器中执行helper_method: current_user的地方).

If I wanted to make a currentUser() function for some oauth stuff I am doing where I can use it in a view or in a controller (think rails, where you do helper_method: current_user in the application controller).

我阅读的所有内容都创建了一个helpers文件夹,并在其中添加了功能,然后您便可以执行此操作.Helpers::functionName这是执行此操作的正确方法吗?

Everything I read states to create a helpers folder and add the function there and then that way you can do Helpers::functionName Is this the right way to do this?

创建可在刀片模板和控制器中使用的辅助功能的"laravel方法"是什么?

Whats the "laravel way" of creating helper functions that can be used in blade templates and controllers?

推荐答案

在您的app/Helpers目录中创建一个新文件,将其命名为AnythingHelper.php 我的助手的一个示例是:

Create a new file in your app/Helpers directory name it AnythingHelper.php An example of my helper is :

<?php
function getDomesticCities()
{
$result = \App\Package::where('type', '=', 'domestic')
    ->groupBy('from_city')
    ->get(['from_city']);

return $result;
}

通过执行以下命令为您的助手生成服务提供商

generate a service provider for your helper by following command

php artisan make:provider HelperServiceProvider

在新生成的HelperServiceProvider.php的register函数中,添加以下代码

in the register function of your newly generated HelperServiceProvider.php add following code

require_once app_path('Helpers/AnythingHelper.php');

现在在您的config/app.php中加载该服务提供商,您就可以完成

now in your config/app.php load this service provider and you are done

'App\Providers\HelperServiceProvider',

这篇关于如何在laravel 5中创建全局助手功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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