問題描述
如果我想為一些 oauth 的東西制作一個 currentUser()
函數,我正在做的地方我可以在視圖或控制器中使用它(想想 rails,你在哪里做 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 = AppPackage::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的注冊函數中添加如下代碼
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
'AppProvidersHelperServiceProvider',
這篇關于如何在 Laravel 5 中創建全局輔助函數?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!