开发者

CakePHP - calling a component 's function from a view

开发者 https://www.devze.com 2023-01-11 08:56 出处:网络
How do I call开发者_运维百科 a function from a component from a view? (ctp file) Is that even a good practice to do that?

How do I call开发者_运维百科 a function from a component from a view? (ctp file)

Is that even a good practice to do that?

Thanks,

Tee


i suggest wrapping the component methods in a helper, and then using the usual route to access the helper.


For most components you could use something like:

App::import('Component', 'YourComponent');
$theComponent = new YourComponent();
$theComponent->yourMethod();

However, components are meant to share functionality used by controllers, so usually you should avoid calling components from views.


ALL IS POSSIBLE!

Component:

    function initialize(&$controller){
        $this->controller =& $controller;
        $this->controller->set('YourComponent', new YourComponent());
    }

View:

<?php $YourComponent->doAction() ... ?>


My opinion is it is not good practice to do that. Think of a view as something designers would work with. You want to keep your code in the models and controllers if at a possible. If it has to do with reusable view content, consider moving the controller to an element or a helper, as that is what they are intended for.

If you provide more details, we can be more specific to how to implement something if you already have a code base we can reference.


In cakephp 3

$config = new \Cake\Controller\ComponentRegistry();
$CustomComponent = new \App\Controller\Component\CustomComponent ($config);
0

精彩评论

暂无评论...
验证码 换一张
取 消