[Cakephp] Component

Description
      What is component ? component is a separate class or function from cakephp that define by user. it's very usefull if you have class that you want to include in cakephp.

How To
1. Create file component in : app/controller/component/[your files here].
the rules : - name file same as name class
               - the class must extend "component"
               - outside class must be define : App::uses('Component', 'Controller');

for example i want to create custom function for ACL (access control list) :
[1]. create file with name : AclComponent.php
    // the path : app/controller/component/AclComponent.php
[2]. copy paste the code below :
 <?php   
 App::uses('Component', 'Controller');  
 class AclComponent extends Component {  
   public function authorization($role)   
   {  
     switch($role)  
     {  
     case 'ADMIN':   
       return true;  
       break;   
     case 'ROLE1':  
       return false;  
       break;   
     case 'ROLE2':   
       return false;  
       break;  
     }       
   }  
 }  
 ?>  

2. Include your custom class (component) on variable $components, make sure $components declare on app controller , so you not always declare $components in every controller.
 public $components = array('Acl','DebugKit.Toolbar','Session',......);  

3. Now you can access components in any controller , for example because we create ACL we can validate every user from the role they have in beforeFilter function. here's my custom code using for ACL.

 public function beforeFilter(){  
     parent::beforeFilter();  
     // ACL Function based on role  
     if($this->Acl->authorization('YOUR ROLE HERE'))  
     {  
       //if true then do nothing or bypass  
     }  
     else  
     {  
       // if false then force to logout (user attempt hijack from URL)  
       $this->redirect(array('controller'=>'auth','action'=>'logout'));  
     }  
   }  

done , that's all how to create a component using cakephp

Post a Comment

Harap gunakan bahasa yang baik dan sopan, terima kasih