[英]Cakephp call an component method inside a 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();
}
我使用CakePHP 2.4
這是我從幫助程序成功調用組件的方式:
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) {
// ...
}
}
}
這似乎是處理此問題的一種非常不錯的方法。
我嘗試了以前的工作方式,盡管從長遠來看,這似乎是一個不錯的立即解決方案,但最好將組件和幫助程序作為兩個單獨的實體在控制器中一起使用。
李
如果您要在不同的地方使用相同的業務邏輯,則可以將邏輯置於特征中,並從組件和幫助程序中使用它,以避免重復代碼。
舉個例子
特征(文件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);
}
}
對助手執行相同的操作。
我希望這可以幫助某人,再見:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.