Friday, April 12, 2013

Laravel- Working with namespace

Starting with Laravel, soon had found that there is a lac of documentation. As a beginner, got a bunch of issues while starting with a modular Namespaced   approach for my project.

 Dont SKIP any paragraph of this doc, else one can get nasty issues.
Creating a new module, with namespace
Step 1: Namespaced directory structure
In our Laravel projects, we will separate each features/modules, with separate namespaces.  But Laravel's Autoloader class makes a difference, with the way- traditional PHP namespace works.
In Laravel, namespace works like JAVA, we have to create a directory same as namespace & keep those files for that namespace under it.

Namespace is applicable only for Models & Views. The Controllers cant be namespaced
For e.g- if we create a Ratings module in our project with 'rating' namespace, then the directory structure will be-
 - application/models/rating/ratingmodel.php
 - application/models/rating/ratingview.php
 - application/controllers/ratings.php  // no namespace for controller

 *We need to add  namespace rating;  at the very TOP of these namespaced files- ratingmodel.php & ratingview.php

Step 3: Calling the namespaced model, views from CONTROLLER

once all the namespacing done- we can call the namespaced classes from controllers like this way
 - nameSpace\Class- name.  // Else the class will not be found

class Ratings_Controller extends Base_Controller {

    public function action_getRatings()


         //set the entity of Ratings Type

         $objRatingsModel = new rating\Ratingsmodel();
         // namespace\ClassName, else the class will not be found

Step 4: Calling the Laravel default classes from namespaced files We can call the default Laravel functionalities( like- Validator::make(), DB::raw() ) from namespaced files, by adding a back-slash(\) before the class- to indicate they are from root-level namespace For e.g-
in rating/ratingmodel.php, 
namespace rating;

class RatingModel{

   public static function validateAndStoreInput($input)
      // Validate the Ratings instance...
      $rules = array(
         'type'  => 'required|alpha',
         'id' => 'required|numeric|min:1'

      $validation = \Validator::make($ratings->input, $rules); 
      // added a back-slash, else the class will not be found
- thats all. Please comment if someone has any query or confusion. Thanks.