PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, February 16, 2022

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

 February 16, 2022     authentication, cakephp, cakephp-3.0, model     No comments   

Issue

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?


Solution

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.



Answered By - floriank
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing