CakePHP用$ this引用这个控制器

时间:2012-12-16 23:38:18

标签: cakephp

使用CakePHP如何在不指定名称的情况下获得对该控制器的引用?

2 个答案:

答案 0 :(得分:2)

为什么要按名称引用控制器? Cake只有一个控制器加载,你不应该在一个请求中加载其他控制器。 1个请求== 1个控制器。

如果您想在没有名称的情况下引用模型,则默认模型名称位于$this->modelClass

$这 - > {$这 - > modelClass} - GT;方法();

接受的答案(如果是模型你想要的话)错误

class UsersController extends AppController {
    public $uses = array('People');

    public function method() {
        $this->{$this->modelClass}->method(); // works

        $controller = Inflector::singularize($this->name);
        $this->$controller->someMethod(); // fatal error
    }
}

答案 1 :(得分:1)

我认为我需要引用此控制器来创建以下公共函数。 但是dogmatic69方式更好。

// Controller/AppController.php

public function dumpData() {
    if(!Configure::read('debug') > 2)
        throw new Exception(".dumpData() can only be accessed in debug mode.");

    // $controller = Inflector::singularize($this->name);
    // $data = $this->$controller->find('first');
    $this->{$this->modelClass}->find('first');
    die(debug($data));
}