使用$的非直观行为在CakePHP中使用继承

时间:2011-06-17 15:46:12

标签: php cakephp

我在PagesController抛出以下错误的另一天遇到了问题:

  

致命错误:调用成员函数   find()在非对象中   /home/jmccreary/www/thoroughbredsource.com/cakephp/app/app_controller.php   第20行

app_controller.php第20行:

$this->current_user = $this->User->find('first', array('recursive' => 0,
  'conditions' => array('User.id' => $this->logged_in_user_id)));

在这种情况下,$thisPagesController的一个实例,但无论出于何种原因,都没有从app_controller.php继承User模型。

为完整起见,这是相关代码:

pages_controller.php

var $name = 'Pages';
var $uses = null;

function beforeFilter() {
    parent::beforeFilter();

    $this->Auth->allow('*');
}

app_controller.php

var $uses = array('User');
var $components = array('Session', 'Cookie', 'RequestHandler', 'DebugKit.Toolbar', 'Auth' => array('autoRedirect' => false, 'loginRedirect' => array('controller' => 'users', 'action' => 'dashboard'), 'flashElement' => 'error', 'loginError' => 'The username or password you provided are incorrect.', 'authError' => 'Please log in first.', 'fields' => array('username' => 'email', 'password' => 'passwd'), 'userScope' => array('User.active' => 1)));
var $helpers = array('Html', 'Form', 'Session');

function beforeFilter() {
    parent::beforeFilter();

    // configure Cookie Component
    // ...

    $this->logged_in_user_id = $this->Auth->user('id');
    if ($this->logged_in_user_id) {
        // NOTE: the following runs on each request for the logged in user
        $this->current_user = $this->User->find('first', array('recursive' => 0, 'conditions' => array('User.id' => $this->logged_in_user_id)));
    }
}

我通过将var $uses = null;更改为var $uses = array();来解决此错误。请注意,完全删除此行会导致相同的错误。

最后,我不完全理解原始问题或我的解决方案。我希望有一个更好的解释或适当的解决方案应该是什么。顺便说一下,运行CakePHP 1.3.10。

2 个答案:

答案 0 :(得分:3)

根据您在http://api.cakephp.org/view_source/controller/可以看到的Controller类的源代码:

/**
 * An array containing the class names of models this controller uses.
 *
 * Example: `var $uses = array('Product', 'Post', 'Comment');`
 *
 * Can be set to array() to use no models.  Can be set to false to
 * use no models and prevent the merging of $uses with AppController
 *
 * @var mixed A single name as a string or a list of names as an array.
 * @access protected
 * @link http://book.cakephp.org/view/961/components-helpers-and-uses
 */
    var $uses = false;

通过使用$uses = array(),您告诉PagesController“不使用模型并与AppController'$ uses合并”,因此它可以工作。您可以在第399行开始看到源代码中的合并。从我所看到的,它将“null”视为“false”,这意味着它不会加载任何模型,包括来自AppController的模型。

您还可以查看http://book.cakephp.org/view/961/components-helpers-and-uses以获取有关$uses

的其他信息

答案 1 :(得分:0)

您正在扩展AppController,然后将uses变量设置为false / null,这表示它根本不使用任何模型。

如果将其设置为空数组(),您将从与AppController中的数组合并的PagesController中获取一个空数组,它将按预期运行。

本手册中明确