1

我想在 cakePHP 中动态加载组件在这个例子中,动态加载 RequestHandler 组件以进行 json 响应

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点击​​上面的代码时

{"code":500,"url":"/resources/xyz.json","name":"查看文件 "/var/www/disecake/app/View/Resources/xyz.ctp" 丢失。"}

当我使用

公共 $components = array('RequestHandler');
在我的控制器中比输出

{"abc":["你好","世界"]}

我认为现在问题更清楚了。

4

1 回答 1

12

CakePHP 书中确实有一节叫做“动态加载组件”。

CakePHP 2.x:

http://book.cakephp.org/2.0/en/controllers/components.html#loading-components-on-the-fly

CakePHP 3.x:

http://book.cakephp.org/3.0/en/controllers/components.html#loading-components-on-the-fly

(它的完成方式与您尝试的方式不同)

于 2013-06-25T14:54:59.860 回答