Tuesday, December 22, 2015

Laravel : Organize Controllers in Modules

Working on any PHP Framework I like to organize my Controllers in sub-folders. Here is how I do it in Laravel. For the most common scenario where you have  - unauthenticated pages and an authenticated admin panel, I create sub-folder named admin and site for both views and controllers. So the folder structure would be something like this -
app-
    controllers -
        admin
            LoginController.php
            ProductController.php
        site
            SiteController.php
    views -
        admin
            login.blade.php
            admin.blade.php               
        site
            site.blade.php
I put the Controllers in their respective namespaces.
<?php
namespace Admin;

class ProductsController extends \BaseController {
...............................
and for the site
<?php
namespace Site;

class ProductController extends \BaseController {
...............................
To access these controllers from the routes.php there are two ways - one to use get directly like -
Route::get('/', 'Site\SiteController@getIndex');
and for the admin we will use group
Route::group(array('prefix'=>'admin',
                   'namespace' => 'Admin'),function() {
 Route::get('/','LoginController@getLogin');
 Route::get('login', 'AuthController@getLogin');
 Route::post('login', 'AuthController@postLogin'));
        Route::get('logout', 'AuthController@logout'));
});

Route::group(array('prefix'=>'admin',
                   'namespace' => 'Admin',
                   'before' => 'auth'),function() {
 Route::resource('product', 'ProductsController');
});
Now very importantly, after writing the controllers run the composer dumpautoload. Or you will get a error saying Class Site\SiteController not found.

No comments: