Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've been working on the skinny controller fat model way. Before, I used this in my controller:

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

However, $this->Auth->user('id'), doesn't work in a model.

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

like image 868
Mennauu Avatar asked Sep 27 '22 19:09

Mennauu


1 Answers

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

Simply pass it to a model method:

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 doesn't have a layer that would take the business logic so most of the time it's put in the model layer. Cake also doesn't use dependency injection so passing whole instances around like the auth object is sometimes cumbersome. Also I don't think the auth object itself should intersect with the model layer. We want to avoid tight coupling. To simplify this (also for testing) it is much easier to just pass the required values to the methods.

like image 93
floriank Avatar answered Oct 06 '22 00:10

floriank