Hi Reader's,
Welcome to FindNerd, today we are going to discuss How to create and add component in CakePHP in 2.4.1 version?
If you want to create or add a component in your web application then you should add your component inside a variable in your controller. Components are packages of logic and these packages are shared between controllers. In CakePHP, there are a good set of components in which you can use various common tasks.
The main advantage of a component is that if you keep clean code of your controller then you can reuse component code between projects.
Note:- you should always configure components in your controller’s beforeFilter() method.
let create a PopupComponent in which we write a function for showing pop box for editing a client profile like photos editing,services editing, working_hours editing,requests editing.
you can follow below code for creating a component.
<?php
App::uses('Component', 'Controller');
class PopupComponent extends Component {
public $components = array();
var $Controller;
public function startup(Controller $controller) {
$this->Controller = $controller;
}
/*
* @Show Popup.
* @Created date: 2014-August-8.
*/
public function showPopup($webPage, $userId) {
App::import('Model', 'Popup');
$this->Popup = new Popup();
$result= array();
if(!isset($userId) || ($userId =="")){return $result;}
//Check for if popup/message exist for that page
$popupDetail = $this->Popup->find('first', array('conditions' => array('Popup.webpage' => $webPage, 'Popup.status' => 1), 'order' => 'Popup.popup_order'));
if (!empty($popupDetail)) {
switch ($webPage) {
case 'working_hours':
$result = $this->getPopups($webPage, $userId);
break;
case 'requests':
$result = $this->getPopups($webPage, $userId);
break;
case 'photos':
$result = $this->getPopups($webPage, $userId);
break;
case 'services':
$result = $this->getPopups($webPage, $userId);
break;
}
}
return $result;
}
?>
Now you have a component 'PopupComponent' and you want to add this component in your controller, for that you should follow below code.
<?php
class BlogController extends AppController {
//here add compnent
public $components = array('PopupComponent');
public function beforeFilter() {
$this->Auth->autoRedirect = false;
parent::beforeFilter();
$this->set('loggedUserDetail', $this->Auth->user());
$this->Auth->allow('signup', 'client_register');
}
}
}
?>
Hope this blog will help to you for creating and adding a component in your controller.
0 Comment(s)