How to create custom component in cakephp

How to create custom component in cakephp. Now create custom component in cakephp.Here i am going to cover how to create component and call it to your controller.
Component is small chunk of utility code to perform common action on your cakephp controllers.
Cakephp already has some default component but you can also create your own customize component very easily. Creating components keeps controller code clean and allows you to reuse code between multiple controllers.

 

Here is step for create custom component in cakephp

In this example i am going to create a simple component to export mysql data into excel.

Step-1: Go to app/Controller/Component and create file name ExportXlsComponent.php

Step-2: Write basic structure of your component, Your class name and file name should be same and in camel case.

<?php
App::uses('Component', 'Controller');
class ExportXlsComponent extends Component {
 
 
}
?>

Step-3: Put your common mysql to excel export function in this component.

function export($fileName, $headerRow, $data) {
 ini_set('max_execution_time', 1600); //increase max_execution_time to 10 min if data set is very large
  $fileContent = implode("\t ", $headerRow)."\n";
  foreach($data as $result) {
   $fileContent .=  implode("\t ", $result)."\n";
  }
 header('Content-type: application/ms-excel'); /// you can set csv format
 header('Content-Disposition: attachment; filename='.$fileName);
 echo $fileContent;
exit;
}

Now your complete component file will be

ExportXlsComponent.php

<?php
App::uses('Component', 'Controller');
class ExportXlsComponent extends Component {
 
function export($fileName, $headerRow, $data) {
 ini_set('max_execution_time', 1600); //increase max_execution_time to 10 min if data set is very large
  $fileContent = implode("\t ", $headerRow)."\n";
  foreach($data as $result) {
   $fileContent .=  implode("\t ", $result)."\n";
  }
 header('Content-type: application/ms-excel'); /// you can set csv format
 header('Content-Disposition: attachment; filename='.$fileName);
 echo $fileContent;
 exit;
 }
}
?>

Leave a Reply