Passing data from CakePHP component to a helper

前端 未结 3 1878
萌比男神i
萌比男神i 2020-12-18 10:27

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

相关标签:
3条回答
  • 2020-12-18 10:50

    In addition to what @Vanja, you can also do this just prior to instantiating a new view in your controller:

    // In your controller method
    // must be set prior to instantiating view
    $this->helpers['YourHelperName']['paramsOrAnyName'] = ['var' => $passed_var];
    
    $_newView = new View($this);
    $return_result = $_newView->render($element_to_view, $layout);
    
    0 讨论(0)
  • 2020-12-18 10:51

    Is there any elegant way to pass data from a component to a helper?

    Yes, the same way you pass any data to the helper. In your view.

    Inside your component I would do something like the following. The beforeRender() action is a CakePHP component callback.

    public function beforeRender(Controller $controller) {
        $yourVars = 'some data';
        $goHere = 'other stuff';
    
        $controller->set(compact('yourVars', 'goHere'));
    }
    

    Then in your view you can pass the data off to your helpers just like normal.

    // view or layout *.ctp file
    $this->YourHelper->yourMethod($yourVars);
    $this->YourHelper->otherMethod($goHere);
    
    0 讨论(0)
  • 2020-12-18 10:59

    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.

    0 讨论(0)
提交回复
热议问题