Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly pass settings to component in CakePHP

Tags:

php

cakephp

I'm using CakePhp 2.2.3 and I'm making a component.

Component:

App::uses('Component', 'Controller');
class ExampleComponent extends Component {

public $settings = array();

protected $_defaults = array(
    'a1' => null,
    'a2' => 2
);

public function __construct(ComponentCollection $collection, $settings = array()) {

    $settings = array_merge($this->_defaults, $settings);
    $this->settings = $settings;

}

public function sum() {
    $sum = $this->settings['a1'] + $this->settings['a2'];
    return $sum;
}

}

Controller:

class ExampleController extends AppController {
public $components = array('Example');

public function index () {
    $this->set('sum', $this->Example->sum(array('a1' => 2, 'a2' => 3)));
}
}

I got back (int) 2 as the result. But I think it should be 5. What I do wrong?

like image 634
Derp Avatar asked Dec 12 '12 18:12

Derp


1 Answers

You are passing the default settings at the wrong time. __construct gets called when you instantiate your component with the following line.

public $components = array('Example');

So if you want to pass parameters to the component initialization you do it like this:

public $components = array('Example'=>array('a1'=>'2', 'a2'=>'3'));

If you want to continue to pass the parameters with the following line:

$this->set('sum', $this->Example->sum(array('a1' => 2, 'a2' => 3)));

Then you will have to adjust your sum() function to:

public function sum($new_settings) {

    $sum = $new_settings['a1'] + $new_settings['a2'];
    return $sum;
}
like image 139
Tim Joyce Avatar answered Nov 14 '22 18:11

Tim Joyce