错误:无法在cakephp中重新声明类

时间:2013-05-29 11:24:37

标签: php cakephp

我是cakephp的新手。我有一个名为Rest的类,由两个控制器共享:Pages和Categories。

因此我考虑在AppController中创建类的实例:

class AppController extends Controller {
    public $rest;


    public function DoRest() {
        require 'Component/Rest.php';

        if(!isset($this->rest))
        $this -> rest = new Rest();

        return $this -> rest;
    }
}

然后我可以在categoriesController上访问它:

public function index() 
    {
        if ($this->request->is('requested')) {
            return $this -> DoRest() -> getCategories();
        } else {
            $this -> set('categories', $this -> DoRest() -> getCategories());
        }
    }

并在页面控制器中:

public function category() {

        $this -> set('items',$this -> DoRest() -> getCategoryById($this->request->query['id']));
    }

在category.ctp中我可以通过以下方式访问类别:

$categories = $this->requestAction('categories/index');

然而现在我得到这个错误: Error: Cannot redeclare class Rest

我做错了什么?

2 个答案:

答案 0 :(得分:1)

require 'Component/Rest.php';

这不是它在蛋糕中的表现。请阅读文档。如果您使用App :: uses()。

但是对于组件,你应该按照官方的方式:

public $components = array('Rest');

,组件类文件应该再次命名为RestComponent.php。

如果你正在使用别的东西,它不是一个组件,而是一个lib,需要上面的app :: uses()(然后将你的文件放在/ Lib文件夹中):

App::uses('Rest', 'Lib');

答案 1 :(得分:1)

你有几个问题。首先,你没有包含“蛋糕”方式的文件;第二,你也没有以“蛋糕”的方式命名组件。

组件应该加上后缀。因此,您的Rest组件应如下所示:

<?php
class RestComponent extends Component {
}

其次,应该通过relavant属性将组件加载到控制器中:

<?php
class YourController extends AppControler {
    public $components = array('Rest');
}

一切都应该有效。但是,我要问你是否需要创建一个Rest组件。 CakePHP内置REST handling,还有一个HTTP component,用于通过HTTP向第三方服务发出请求。