tags:

views:

508

answers:

2

I'm working on integrating authentication and authorization into my CakePHP application now and am having some difficulties.

First up, I'm not using ACL. It scares me.

In my AppController I have this:

var $components = array("Auth");

So, any time I want to check the logged in user, I call this from one of my controllers:

$this->Auth->user();

And I get an array which is the information from my usrs table (my table is called usrs with model Usr).

The issue is that I'll often want to call functions on the Usr model, so I have to do this in my controller:

$usr = ClassRegistry::init('Usr');
$usrInfo = $this->Auth->user();
$usr->set($usrInfo);
// -- or --
$usr = ClassRegistry::init('Usr');
$usrId = $this->Auth->user('id');
$usr->id = $usrId;

This doesn't seem very cakey and it's been bugging me since I know there must be a better way. Should I add var $uses = array("Usr") into my AppController so I don't have to use the ClassRegistry all the time? What's the best way to do this?

A: 

I've just discovered one way to do it in one line:

$this->loadModel('Usr', $this->Auth->user('id'))

I still don't know if this is best practice though...

nickf
`Controller::loadModel` is best practice for controllers if you only need the model for that controller action and not all actions in the controller. Outwith controllers you would need to resort to `ClassRegistry::init` and `App::import`, and when using those you should ask yourself if you are still following MVC. This post sums up Gwoo's stance on these approaches: http://techno-geeks.org/2009/05/models-inside-controller/
deizel
+1  A: 

Why don't you just use the model?

// in Controller
var $uses = array('someModel', 'User');

This makes the model available as usual:

$this->User->someFunction($this->Auth->user('id'));  // for example
deceze
would that work if I put it on the AppController? It wouldn't overwrite the default value? (eg: PostsController by default has `$uses = array("Post");`)
nickf
Yes. http://book.cakephp.org/view/829/The-App-Controller
deceze
$uses will load the Usr model for all actions, the loadModel approach will only load it when needed. So it's a toss up really between more objects in memory or more code in controller actions.
deizel