Wednesday, 16 November 2016

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:


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:


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'

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...