Sunday, February 22, 2015

Laravel 4 Custom Class

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 folder

My Solution 

  • We Create folder inside app. For example app/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 new app/classes folder follows your namespacing convention, Laravel will autoload all classes / files within this folder. 
  • Write your class
    For example, we want to add EmailNotifier which handle about email sending. We createEmailNotifier.php on app/classes/Notifier/EmailNotifier.php
    <?php namespace Notifier;
    
    class EmailNotifier {
    
        public static function notify()
        {
            return 'User Notified';
        }
    }
    

    Please note that we are using Notifier namespace as the same folder with Notifier
  • 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 ofaliases array.

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: