php 我在哪里放置可以显示 Flash 消息的 Laravel 4 辅助函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/14902589/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Where do I put Laravel 4 helper functions that can display flash messages?
提问by Chris G.
I've written a simple display_messages()function that will search Session::get('errors')for flash data and echo it to the screen.
我已经编写了一个简单的display_messages()函数来搜索Session::get('errors')闪存数据并将其回显到屏幕上。
Where do I put this function? In Codeigniter, you had a helpers folder where you could stick all your little global helper methods.
我把这个功能放在哪里?在 Codeigniter 中,您有一个 helpers 文件夹,您可以在其中保存所有小的全局辅助方法。
采纳答案by ptim
As Usman suggested,
正如乌斯曼所建议的那样,
- create a file /application/libraries/demo.php
- define a class Demo() {inside it
- call the function like so: {{ Demo::display() }}
- 创建一个文件/application/libraries/demo.php
- 在class Demo() {里面定义一个
- 像这样调用函数: {{ Demo::display() }}
Works because libraries and models are autoloaded in start.php line 76. I believe that filenames must match Classnames (note capital).
之所以有效,是因为库和模型在 start.php 第 76 行中自动加载。我相信文件名必须匹配类名(注意大写)。
<?php
class Demo {
    public static function display() {
        if( !$message = Session::get('errors'))
            $message = 'No Errors';
        echo "<pre>print_r($message)</pre>";
    }
}
Can't quite figure out why I had a problem using the classname Common, there may be a conflict (you could define a namespace if this were important)...
无法弄清楚为什么我在使用类名 Common 时遇到问题,可能存在冲突(如果这很重要,您可以定义一个命名空间)...
回答by Muhammad Usman
Create a folder helperswithin your app folder and create a file application_helper.php. With such code:
创建一个文件夹helpers您的应用程序文件夹中,创建一个文件application_helper.php。使用这样的代码:
// app/helpers/application_helper.php
function display_messages()
{
  exit('Yes');
}
Then open your composer.json file in root. autoload app/helpers/application_helper.phpwith composer files.
然后在 root 中打开您的 composer.json 文件。app/helpers/application_helper.php使用 composer自动加载files。
"autoload": {
....
    "files": [
        "app/helpers/application_helper.php"
    ]
Done, you can now call display_messages().
完成,您现在可以调用display_messages().
Some autoloaders may require you to run composer dumpcommand for the first time.
某些自动加载器可能会要求您composer dump第一次运行命令。
回答by riotCode
Thank you memeLab provided a very useful answer which helped me a lot. I just wanted to expand on his answer as the "libraries" folder was not an auto load directory, at least not in the release/current version of L4 I am using. Also the start.php seems to have been expanded to be  the startfolder with global.php, local.php, and artisan.php. 
谢谢 memeLab 提供了一个非常有用的答案,对我帮助很大。我只是想扩展他的回答,因为“ libraries”文件夹不是自动加载目录,至少在我使用的 L4 的发行版/当前版本中不是。此外,start.php 似乎已扩展为start包含global.php、local.php 和 artisan.php的文件夹。
So to use your own classes for separate libraries or helpers with the L4 lazy auto loader you just have to include whichever folder you want to store these in to the global.php. For example I added a librariesfolder to the directory list.
因此,要将您自己的类用于单独的库或具有 L4 延迟自动加载器的帮助程序,您只需将您想要将它们存储到global.php. 例如,我libraries在目录列表中添加了一个文件夹。
ClassLoader::addDirectories(array(
    app_path().'/commands',
    app_path().'/controllers',
    app_path().'/models',
    app_path().'/database/seeds',
    // this a custom path
    app_path().'/libraries',
));
Then whatever class you define in that folder as classname.phpcan be called via CLASSNAME::methodName($someVar);in your controllers.
然后您在该文件夹中定义的任何类classname.php都可以CLASSNAME::methodName($someVar);在您的控制器中调用。
class CLASSNAME {
    public static function methodName($someVar=NULL) {
        // whatever you want to do...
        return $message;
    }
}
So in this fashion you can create a helper class and define different methods to use throughout your controllers. Also be careful defining regular functions outside of your Class in this manner will cause you grief because they will not work (because the class is not always loaded). (for example someFunctionName($someVar);instead of CLASSNAME::methodName($someVar);) If you want to create functions in this manner you would need to make sure the is loaded, however I will not elaborate on this because it is better practice to use the lazy loader classes for such things so you only load the classes you really need. 
因此,通过这种方式,您可以创建一个辅助类并定义在整个控制器中使用的不同方法。还要小心以这种方式在类之外定义常规函数会导致您悲伤,因为它们将不起作用(因为类并不总是加载)。(例如,someFunctionName($someVar);而不是CLASSNAME::methodName($someVar);)如果你想以这种方式创建函数,你需要确保加载,但是我不会详细说明这一点,因为更好的做法是使用惰性加载器类来做这样的事情,所以你只加载你真正需要的课程。
Thanks again to memeLab and Usman, I would not have gotten as far without their answers. :)
再次感谢 memeLab 和 Usman,如果没有他们的答案,我就不会走得这么远。:)
回答by Chen-Tsu Lin
For loading Classes:
对于加载类:
Create app/libraries/class/Message.php, and add class in file
创建app/libraries/class/Message.php,并在文件中添加类
class Message {
    public static function display() {
    }
}
Add "app/libraries/class"to composer.json
添加"app/libraries/class"到composer.json
"autoload": {
    "classmap": [
        "app/commands",
        "app/controllers",
        "app/models",
        "app/database/migrations",
        "app/database/seeds",
        "app/tests/TestCase.php",
        "app/libraries/class"
    ]
},
Finally run composer dump-autoloadin command line.
最后composer dump-autoload在命令行中运行。
You can access that by Message::display()
你可以通过 Message::display()
For loading plain non-object php Functions:
加载普通的非对象 php函数:
Create app/libraries/function/display_messages.php, and add function in file
创建app/libraries/function/display_messages.php,并在文件中添加函数
function display_messages() {
}
add one line in start/global.php
在 start/global.php 中添加一行
require app_path().'/libraries/function/display_messages.php';
You can access that just by display_messages()
你可以通过 display_messages()
回答by AldoZumaran
Add this in app/start/global.php
在 app/start/global.php 中添加这个
require app_path().'/config/autoload.php';
require app_path().'/start/loader.php';
App::instance('loader',new loader($autoload));
create a new file loader.php in app/start and add:
在 app/start 中创建一个新文件 loader.php 并添加:
class loader{
private $helpers = array();
public $autoload = array(
    'helpers' => array()
);
function __construct($autoload  = array()) {
    if (!empty($autoload))
        $this->autoload = $autoload;
    foreach ($this->autoload as $key => $value)
    {
        $function = strtolower($key);
        $this->$function($value);
    }
}
function helpers($helpers=array())
{
    if (!is_array($helpers))
        $helpers = explode(",",$helpers);
    foreach ($helpers as $key => $value) {
        $this->helper($value);
    }
}
function helper($helper = '',$path = '/')
{
    $folder = app_path().'/helpers'.$path;
    if (file_exists($folder.$helper.'.php') && !in_array($helper, $this->helpers)){
        $this->helpers[] = $helper;
        require $folder.$helper.'.php';
    }
    else{
        $segments = explode('/',$helper);
        if (is_dir($folder.$segments[0])){
            array_shift($segments); 
            $this->helper($segments,$path.$segments[0].'/');
        }
    }
}
}
}
create a new file autoload.php in app/config and add:
在 app/config 中创建一个新文件 autoload.php 并添加:
$autoload['helpers'] = array('functions'); // my autoload helpers!
create a new folder helpers in app/ , add your helper files. ( es. myhelper.php )
在 app/ 中创建一个新文件夹 helpers ,添加您的帮助文件。( es. myhelper.php )
function myhelper()
{
echo 'helper';
}
in your controller add:
在您的控制器中添加:
App::make('loader')->helper('myhelper');
    myhelper();
回答by Laura Chesches
I used this tutorial and i think is the easiest method: http://laravel-recipes.com/recipes/50/creating-a-helpers-file
我使用了本教程,我认为这是最简单的方法:http: //laravel-recipes.com/recipes/50/creating-a-helpers-file
- First create the file app/helpers.php
- Then either load it at the bottom of app\start\global.phpas follows. - // at the bottom of the file require app_path().'/helpers.php'; 
- 首先创建文件 app/helpers.php
- 然后在app\start\global.php的底部加载它,如下所示。 - // 在文件底部 require app_path().'/helpers.php'; 
Or change your composer.jsonfile and dump the autoloader.
或者更改您的composer.json文件并转储自动加载器。
 {
        "autoload": {
            "files": [
                "app/helpers.php"
            ]
        }
    }
$ composer dump-auto
$作曲家转储自动
- then you can write your functions in helpers.php and call them from anywhere - function myfunction($result){ return $result; }
- 然后你可以在 helpers.php 中编写你的函数并从任何地方调用它们 - function myfunction($result){ return $result; }
回答by Colin
In L3, I would normally create a application/libraries/helpers.phpfile, and require_once()it in my application/start.php.  Similar to how L3 has a laravel/helpers.phpfile.
在 L3 中,我通常会创建一个application/libraries/helpers.php文件,并require_once()在我的application/start.php. 类似于 L3 拥有laravel/helpers.php文件的方式。
I'm assuming there is something similar you can do in L4.
我假设你可以在 L4 中做类似的事情。
EDIT:  Just looking at the source, app/start/local.phpseems like it might be the place.
编辑:只看来源,app/start/local.php似乎它可能就是这个地方。
回答by Lovro Strihi?
open root_folder/vendor/laravel/framework/src/Illuminate/Support/helpers.php
打开 root_folder/vendor/laravel/framework/src/Illuminate/Support/helpers.php
and you can add your function
你可以添加你的功能
if ( ! function_exists('display_messages'))
{
    function display_messages()
    {
        return ...
    }
}

