Best Practices for Laravel 4 Helpers and Basic Functions?

My way of doing this is to create a new folder in the /app directory in the root of your Laravel 4 project. Then add this folder to the first array of the /app/start/global.php file like so:

<?php

ClassLoader::addDirectories(array(

app_path().'/commands',
app_path().'/controllers',
app_path().'/models',
app_path().'/database/seeds',
app_path().'/classes', // This line is the one I've added.

));

As long as the folder structure within the new /app/classes folder follows your namespacing convention. Laravel 4 will autoload all the classes/files within this folder. This way there's no need to dig into any composer files or run composer command.

Not sure if this is best practice but it certainly works.

If you created a simple file called /app/classes/Helpers/Helper.php such as this:

<?php namespace Helpers;

class Helper {

    public static function helloWorld()
    {
        return 'Hello World';
    }
}

All you would need to do is call Helpers\Helper::helloWorld();

You could also alias this helper class in your /app/config/app.php file. Just add something like this to the end of the aliases array:

'Helper'          => 'Helpers\Helper'

The ugly, lazy and awful way: At the end of bootstrap/start.php , add an include('tools.php') and place your function in that new file.

The clean way: Create a library. That way it'll be autoloaded ONLY when you actually use it.

  • Create a libraries folder inside your app folder
  • Create your library file, create a class in it, and add static functions to it
  • Option 1: Edit start/global.php to add app_path().'/libraries' to the ClassLoader::addDirectories( array.
  • Option 2: Edit composer.json to add "app/libraries" to the autoload array. Run composer dump-autoload
  • Call your class and static functions from your views.

About your options, quoted from the global.php file

In addition to using Composer, you may use the Laravel class loader to load your controllers and models. This is useful for keeping all of your classes in the "global" namespace without Composer updating.

You can combine both options, where the Laravel class loader will automatically search for classes in the registered directories (Option 1, easier) and Composer will keep record of all the classes but only after you update it (Option 2, might improve performance).