What I didn’t knew about controllers without models

Published on and tagged with cakephp  controller  model

Up to now I thought the two ways to create a controller without a model are equivalent:

class MyController extends AppController {
    var $uses = null;


class MyController extends AppController {
    var $uses = array();

And so whenever I had to create such a controller, I simply used one of those approaches without much thought.

Recently, I had a controller using the first approach with null. Everything worked fine. Then a model got added to the AppController’s $uses array to do some stuff with that model in the beforeRender() method. This worked fine with the controllers using models, but it caused an “undefined property” error when I called the controller without model.

The reason for this “problem” is, that var $uses = null; overrides the value from the parent class and so the model is no longer defined in the AppController, hence the error. This behavior is correct from an object-oriented point of view, but it is unexpected in CakePHP (at least for me). Because if it would work in the object-oriented way, there would be errors in the other controllers, too. But due to Cake’s magic, a $uses array defined in a controller doesn’t override the $uses array of the AppController, instead those arrays get merged. And so I expected that something like that would happen when using null as value for the $uses variable ;-)

So the solution to fix the “undefined property” error was to use var $uses = array();

4 comments baked

  • phpcurious

    Actually, it made me think to realize that where did I get the idea to set the $uses variable to null if I am not connecting my controllers to models in the first place?

    I looked at the pages_controller.php in cake/scripts/template/skel/controllers and there I found …

    $uses = null;

  • $uses=null vs. $uses=array matters « FilChi Weblog

    […] $uses=null vs. $uses=array matters 31 10 2007 In daniel hoffster’s blog, he pointed out the difference of behavior when setting your $uses variable in your controllers to null against array(). […]

  • cakebaker

    @phpcurious: Thanks for your comment!

    Yes, you are right, it was used in this way in the PagesController. At least in CakePHP 1.2 this has been fixed some time ago.

  • Cakephp Static Views

    […] can see more on this solution in the cakephp blog.One final thought, be sure to set you page titles using the set […]

© daniel hofstetter. Licensed under a Creative Commons License