tags:

views:

56

answers:

3

Hi,

I have an index action in my users_controller that get a list of users. For each user i want to calculate the number of projects they have associated (one user => many projects). I was thinking of using a method like getProjectTotal and calling it for each user. Would I put this method in the users_controller and call it like

$this->getProjectTotal($id) 

in the view?

Thanks,

Jonesy

+2  A: 

Sure. It sounds like this is just a helper method based on the call. I do that all the time. I'll typically set the method visibility to private or at least protected to keep it from being called accidentally in a rendering scenario.

Rob Wilkerson
is it possible to do a findby in the helper? I've created a helper that I'm trying to do $user = $this->User->findById($id); but I;m getting an error "Undefined property: UsernameHelper::$User"
iamjonesy
Helpers are view elements and don't have direct access to the model.
Rob Wilkerson
+1  A: 

I'm still relatively new to CakePHP, but I've been using the built-in counterCache in Cake 1.2 to track the number of hasMany records for a parent Model in one of my apps. Create a field in your parent Model to store the hasMany count, and enable counterCache in the $belongsTo property for the child Model, and you're good to go. It automatically updates the counterCache count field in the parent model whenever the # of "hasMany" records increases/decreases. I like this method of tracking as it keeps the controller a little cleaner if all you need is the count without any other conditions.

Docs: http://book.cakephp.org/view/816/counterCache-Cache-your-count

Also, I'm still new to MVC, but I think if you're going to gather the count via a private/protected controller method, you'd want to call it in the controller and then send the data to the view, not perform the actual method from the view, in this scenario.

whelanska
thanks man! never knew how to use counterCache before. Works a treat! Cheers. Can't really mark as answer though as it's not what my question was about.
iamjonesy
A: 

Also - yes you can make a controller method for work that isn't going to render a view - BUT - in your case you should use counterCache / a Model function since you are either fetching / counting / manipulating actual data related to the Project model and it's relationship with the User model and current logged in User specifically.

When building out my controllers I tend to stick to methods that render a view or return data for an element called from requestAction. If the method is computational or setting up variables but doesn't require a template or isn't called from an element I move it to a component / helper / model / behavior. Combined with a docblock with @requestAction in the flags for introspection and I can get a list of regular actions, and data returning actions without worrying that a controller is full of other methods.

Abba Bryant