{1917} - 3.6.2 Creating Custom Components

Suppose our online application needs to perform a complex mathematical operation in many different parts of the application. We could create a component to house this shared logic for use in many different controllers.

The first step is to create a new component file and class. Create the file in /app/controllers/components/math.php. The basic structure for the component would look something like this.

<?php

class MathComponent extends Object {
    function doComplexOperation($amount1, $amount2) {
        return $amount1 + $amount2;
    }
}

?>
  1. <?php
  2. class MathComponent extends Object {
  3. function doComplexOperation($amount1, $amount2) {
  4. return $amount1 + $amount2;
  5. }
  6. }
  7. ?>

Once our component is finished, we can use it in the application’s controllers by placing the component's name (minus the "Component" part) in the controller’s $components array. The controller will automatically be given a new attribute named after the component, through which we can access an instance of it:

/* Make the new component available at $this->Math,
as well as the standard $this->Session */
var $components = array('Math', 'Session');
  1. /* Make the new component available at $this->Math,
  2. as well as the standard $this->Session */
  3. var $components = array('Math', 'Session');

{3819} - 3.6.2 Creating Custom Components

Suppose our online application needs to perform a complex mathematical operation in many different parts of the application. We could create a component to house this shared logic for use in many different controllers.

The first step is to create a new component file and class. Create the file in /app/controllers/components/math.php. The basic structure for the component would look something like this.

<?php

class MathComponent extends Object {
    function doComplexOperation($amount1, $amount2) {
        return $amount1 + $amount2;
    }
}

?>
  1. <?php
  2. class MathComponent extends Object {
  3. function doComplexOperation($amount1, $amount2) {
  4. return $amount1 + $amount2;
  5. }
  6. }
  7. ?>

Differences

Lines: 14-26Lines: 14-18
  }  }
 } }
 ?&gt; ?&gt;
-</pre> 
-<p> 
- Once our component is finished, we can use it in the application’s controllers by placing the component's name (minus the "Component" part) in the controller’s $components array. The controller will automatically be given a new attribute named after the component, through which we can access an instance of it: 
-</p> 
-<pre> 
-/* Make the new component available at $this-&gt;Math, 
-as well as the standard $this-&gt;Session */ 
-var $components = array('Math', 'Session'); 
 </pre> </pre>