我想在cakeHP中动态加载组件在本例中,为json响应动态加载RequestHandler组件
public function xyz() {
$this->components[] ='RequestHandler';
$this->Components->load('RequestHandler');
$this->RequestHandler->initialize($this);
$abc = array("hello","world");
$this->set('abc', $abc);
$this->set('_serialize', array( 'abc'));
}
初始化函数时生成的错误显示未定义。
为了更清晰的画面而进行的修改:
public function xyz() {
$this->components[] ='RequestHandler';
$this->RequestHandler = $this->Components->load('RequestHandler');
$this->RequestHandler->initialize($this);
$abc = array("hello","world");
$this->set('abc', $abc);
$this->set('_serialize', array( 'abc'));
}
我也试过
public function xyz() {
$this->RequestHandler = $this->Components->load('RequestHandler');
$abc = array("hello","world");
$this->set('abc', $abc);
$this->set('_serialize', array( 'abc'));
}
我不能使用这样的组件#$this->RequestHandler->getTime();因为cakephp自动处理json响应。当我使用http://disecake.localhost/resources/xyz.json
{"代码":500,"url":"/resources/xyz.json","名称":"查看文件";/var/www/diescake/app/View/Resources/xyz.ctp";缺少。"}
当我使用
public$components=数组("RequestHandler")在我的cotroller比输出
{"abc":["你好","世界"]}
我想现在问题更清楚了。
CakePHP书中有一节叫做"动态加载组件"。
CakePHP 2.x:
http://book.cakephp.org/2.0/en/controllers/components.html#loading-飞行中的组件
CakePHP 3.x:
http://book.cakephp.org/3.0/en/controllers/components.html#loading-飞行中的组件
(这与您尝试的方式不同)