Where do I put Laravel 4 helper functions that can display flash messages?

走远了吗. 提交于 2019-12-21 03:18:24

问题


I've written a simple display_messages() function that will search Session::get('errors') for flash data and echo it to the screen.

Where do I put this function? In Codeigniter, you had a helpers folder where you could stick all your little global helper methods.


回答1:


As Usman suggested,

  • create a file /application/libraries/demo.php
  • define a class Demo() { inside it
  • call the function like so: {{ Demo::display() }}

Works because libraries and models are autoloaded in start.php line 76. I believe that filenames must match Classnames (note capital).

<?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)...




回答2:


Create a folder helpers within your app folder and create a file application_helper.php. With such code:

// app/helpers/application_helper.php

function display_messages()
{
  exit('Yes');
}

Then open your composer.json file in root. autoload app/helpers/application_helper.php with composer files.

"autoload": {
....

    "files": [
        "app/helpers/application_helper.php"
    ]

Done, you can now call display_messages().

Some autoloaders may require you to run composer dump command for the first time.




回答3:


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 start folder with global.php, local.php, and 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 libraries folder to the directory list.

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.php can be called via CLASSNAME::methodName($someVar); in your controllers.

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.

Thanks again to memeLab and Usman, I would not have gotten as far without their answers. :)




回答4:


For loading Classes:

Create app/libraries/class/Message.php, and add class in file

class Message {
    public static function display() {

    }
}

Add "app/libraries/class" to 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-autoload in command line.

You can access that by Message::display()

For loading plain non-object php Functions:

Create app/libraries/function/display_messages.php, and add function in file

function display_messages() {

}

add one line in start/global.php

require app_path().'/libraries/function/display_messages.php';

You can access that just by display_messages()




回答5:


Add this in 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:

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:

$autoload['helpers'] = array('functions'); // my autoload helpers!

create a new folder helpers in app/ , add your helper files. ( es. myhelper.php )

function myhelper()
{
echo 'helper';
}

in your controller add:

App::make('loader')->helper('myhelper');
    myhelper();



回答6:


In L3, I would normally create a application/libraries/helpers.php file, and require_once() it in my application/start.php. Similar to how L3 has a laravel/helpers.php file.

I'm assuming there is something similar you can do in L4.

EDIT: Just looking at the source, app/start/local.php seems like it might be the place.




回答7:


I used this tutorial and i think is the easiest method: http://laravel-recipes.com/recipes/50/creating-a-helpers-file

  1. First create the file app/helpers.php
  2. Then either load it at the bottom of app\start\global.php as follows.

    // at the bottom of the file require app_path().'/helpers.php';

Or change your composer.json file and dump the autoloader.

 {
        "autoload": {
            "files": [
                "app/helpers.php"
            ]
        }
    }

$ composer dump-auto

  1. then you can write your functions in helpers.php and call them from anywhere

    function myfunction($result){ 
         return $result;
        }
    



回答8:


open 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 ...
    }
}


来源:https://stackoverflow.com/questions/14902589/where-do-i-put-laravel-4-helper-functions-that-can-display-flash-messages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!