Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing data from CakePHP component to a helper

Tags:

helper

cakephp

I need to share data between a component and helper. I'm converting my self-made payment service formdata generator to a CakePHP plugin and I'd like to be able to fill in the payment data from the controller(using a component) and use a helper to print out the data.

Everything I've tried so far have felt a little too hacky, so let me ask you: Is there any elegant way to pass data from a component to a helper?


edit:

I solved this particular situation by adding the original formadata class instance to ClassRegistry during the component initialization. This way the helper too can access the instance using ClassRegistry.

However, this only works for objects, so the question remains open.

like image 236
jpeltoniemi Avatar asked Dec 27 '22 18:12

jpeltoniemi


1 Answers

Having a similar problem, I found this solution to work best for me.

You could use the helper's __construct method in pair with $controller->helpers array.

Since the Helper::_construct() is called after the Component::beforeRender, you can modify the $controller->helpers['YourHelperName'] array to pass the data to your helper.

Component code:

<?php

public function beforeRender($controller){
    $controller->helpers['YourHelperName']['data'] = array('A'=>1, 'B'=>2);
}
?>

Helper code:

<?php

function __construct($View, $settings){
    debug($settings);       
            /* outputs:
                array(
                    'data' => array(
                        'A' => (int) 1,
                        'B' => (int) 2
                    )
                )
            */
}

?>

I am using CakePHP 2.0, so this solution should be tested for earlier versions.

like image 65
Vanja D. Avatar answered Jan 05 '23 07:01

Vanja D.