The Problem
How to add custom class on Laravel 4 Application?
In most case, we want to leverage our Laravel 4 application capabilities by adding custom class. We don’t want to insert class inside
Controller and Model to do this, so we have to write our class in separate files and group it by folderMy Solution
- We Create folder inside
app. For exampleapp/classes - Register ClassLoader to
app/start/global.ClassLoader::addDirectories(array( app_path().'/commands', app_path().'/controllers', app_path().'/models', app_path().'/database/seeds', app_path().'/classes', // we've added classes folder on Laravel ClassLoader ));
As long as the folder structure within newapp/classesfolder follows your namespacing convention, Laravel will autoload all classes / files within this folder. - Write your class
For example, we want to addEmailNotifierwhich handle about email sending. We createEmailNotifier.phponapp/classes/Notifier/EmailNotifier.php<?php namespace Notifier; class EmailNotifier { public static function notify() { return 'User Notified'; } }
Please note that we are usingNotifiernamespace as the same folder withNotifier - Call your class using
Notifier\EmailNotifier::notify() - If we want to add it on alias so you can do
EmailNotifier::notify(), we have add alias to app/config/app.php .Add 'EmailNotifier' => 'Notifier\EmailNotifier' at the end ofaliasesarray.
Another Solution
Don’t forget that we have Composer. We can always utilze Composer to load our classes. You can refer to http://laravel.com/docs/packages for package development and if you want to publish your class topackagist.
No comments:
Post a Comment