0

我使用 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();
}
4

3 回答 3

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) {
            // ...
        }
    }
}
于 2014-04-22T22:58:17.217 回答
0

将数据从 CakePHP 组件传递给助手

这似乎是一个很好的处理方式。

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

于 2012-06-30T11:43:28.830 回答
0

如果您的 porpouse 是在不同的地方使用相同的业务逻辑,您可以将逻辑放入 trait 并从组件和助手中使用它,以避免重复代码。

举例

特征(文件 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);        
 }
}

对 Helper 执行相同的操作。

我希望这对某人有所帮助,再见:)

于 2018-07-19T08:47:23.347 回答