How to organize base controllers

Situation: we have an application with multiple modules, each one needs a base controller that will handle common stuff for them, I prefer having a folder called “base_controllers” in application folder to keep it organized.

By default, Laravel’s base controller is in controllers folder(base.php) and it’s mapped in start.php with Autoloader::map().

To implement my way follow these 3 simple steps:

1. Delete base.php from controllers(if you don’t need it anymore)

2. Create base_controllers folder in /application/base_controllers and create the base controllers you need e.g. Base1.php and Base2.php:


Base1_Controller extends Controller {}
Base2_Controller extends Controller {}

3. To make it work(controllers to extend them) we have to ways:

3.1 In start.php with Autoloader::map() each one individually:


Autoloader::map(array(
     'Base1_Controller' => path('app').'base_controllers/Base1.php',
     'Base2_Controller' => path('app').'base_controllers/Base2.php',
));

3.2 In start.php with Autoloader::directories():


Autoloader::directories(array(
       path('app').'models',
       path('app').'libraries',
       path('app').'base_controllers',
));

Note: Laravel’s autoloader will search the directories using the PSR-0 naming convention.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s