如何在模型中使用:$this->Auth->user('id')? CakePHP 3.0

How to use: $this->Auth->user('id') in a model? Cakephp 3.0

我一直在研究瘦控制器胖模型方式。之前,我在我的控制器中使用了这个:

$this
    ->find('all')
    ->contain(['Declarator'])
    ->where(['user_id' => $this->Auth->user('id')])
    ->order(['Declarations.created' => 'DESC']);

但是,$this->Auth->user('id') 在模型中不起作用。

还有什么其他方法可以从模型中经过身份验证的用户那里获取 ID?

What other way is there to get the id from the authenticated user in a model?

只需将其传递给模型方法:

public function someModelMethod($userId, array $postData) {
    // Do something here, move your code from the controller here
    return $something;
}

public function someControllerAction() {
    $this->set('data', $this->Model->someModelMethod(
        $this->Auth->user('id'),
        $this->request->data
    );
}

Cake 没有采用业务逻辑的层,因此大部分时间它都放在模型层中。 Cake 也不使用依赖注入,因此像 auth 对象一样传递整个实例有时很麻烦。此外,我认为 auth 对象本身不应与模型层相交。我们要避免紧耦合。为了简化这一点(也用于测试),将所需的值传递给方法要容易得多。

在 CakePHP 2.x 中,它是按如下所述完成的。我很确定,即使它不在文档中,也可以以相同的方式完成。

// Use anywhere
AuthComponent::user('id')

// From inside a controller
$this->Auth->user('id');

来源: http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#accessing-the-logged-in-user

版本 3.x 的文档: http://book.cakephp.org/3.0/en/controllers/components/authentication.html#accessing-the-logged-in-user

也许这不是个好主意,但在 cake 的模型中您可以使用 $_SESSION['Auth']['User']['id']

获取用户 ID

或者只是 use Cake\Routing\Router;Table class 的顶部,然后,您可以使用以下方法访问会话:

Router::getRequest()->getSession()->read('Auth.User.id');