Cakephp在帮助器内调用组件方法

时间:2012-06-30 10:24:55

标签: php cakephp components helper

我使用Cakephp 2.1,我需要从一个视图帮助器中调用一个驻留在插件中的组件方法:

组件在这里:

  

/app/Plugin/Abc/Controller/Component/AbcComponent.php

帮助者在这里:

  

/app/View/Helper/SimpleHelper.php

我试过帮帮人:

App::import('Component', 'Abc.Abc');
$this->Abc = new Abc(); or $this->Abc = new AbcComponent;

$this->Abc = $this->Components->load('Abc.Abc');

在控制器内部,该组件可以正常工作。 我知道这不推荐(MVC设计等),但如果我不这样使用它,我需要复制很多代码。我需要做一些像:

MyHelper extends Helper{
   $simpleVar = Component->get_data();
}

3 个答案:

答案 0 :(得分:8)

我使用CakePHP 2.4

这就是我成功从Helper调用Component的方法:

App::uses('AclComponent', 'Controller/Component');
class MyHelper extends AppHelper {
    public function myFunction() {
        $collection = new ComponentCollection();
        $acl = new AclComponent($collection);
        // From here you can use AclComponent in $acl
        if ($acl->check($aro, $aco) {
            // ...
        }
    }
}

答案 1 :(得分:0)

Passing data from CakePHP component to a helper

这似乎是处理这个问题的一种非常好的方法。

我尝试过以前的工作方式,虽然它似乎是一个很好的直接解决方案,但从长远来看,最好只使用组件和帮助器作为控制器中的两个独立实体。

答案 2 :(得分:0)

如果要在不同的地方使用相同的业务逻辑,则可以将逻辑置于特征中,并从组件和助手中使用它,以避免重复代码。

通过示例

特征(文件app / Lib / NameOfTrait.php或app / PluginName / Lib / NameOfTrait.php)

trait NameOfTrait {

   public function theTraitFunc($a, $b) {
       // Code here
   }
 }

组件:

App::uses('Component', 'Controller');
App::uses('NameOfTrait', 'PluginName.Lib');
class NameOfComponent extends Component {
use NameOfTrait;
private $member;
private $controller;

public function __construct(ComponentCollection $collection, $settings = array()) {
    parent::__construct($collection, $settings);
    $this->member = $settings['memberName'];
}    
 function startup(Controller $controller) {
    $this->controller = $controller;
}
/**
 * Wrap function call of trait function,
 * I think the function doesn't have the same name, 
 * I don't try this  but I think  is obvious, 
 * to avoid the function to call itself
 */
public function theTraitFuncWrap($a) {
    return $this->theTraitFunc($a, $this->member);        
 }
}

对助手进行相同的操作。

我希望这可以帮助某人,再见:)