Contact Us

How to properly create a Model instance manually

Posted on 22/1/07 by Felix Geisendörfer

Deprecated post

The authors of this post have marked it as deprecated. This means the information displayed is most likely outdated, inaccurate, boring or a combination of all three.

Policy: We never delete deprecated posts, but they are not listed in our categories or show up in the search anymore.

Comments: You can continue to leave comments on this post, but please consult Google or our search first if you want to get an answer ; ).

Hey folks,

sorry for my low activity on here again. The 2nd part of my A PHP developers guide to JavaScript series is in the works but I might need some more days to finish it since I'm still very busy. I've just done 2 little side projects next to my big client project and I'm also working hard on releasing my first own web application (it's still secret - somewhat) so there was little time for blogging.

However, over the past days my work has shifted from heavy JS/AJAX/DOM scripting to more PHP related stuff. This means I had some inspirations for PHP-posts again. However, some of them would have been so short that the code would have collided with the rectangular Google-Ad that I used to run. So I finally got tired of it and removed it. I'm thinking of removing the ads on here completely, but I'll wait for my next check from Google before I do so (~$30 left). For the meantime, I've tweaked the ad layout a little. I'm particularly proud about the ad next to the comment box ; ).

Anyway, before this goes totally off-topic, here comes the actual post: When doing more advanced stuff in CakePHP you sometimes need to work with a particular Model outside of a Controller. A good example for this would be a smart helper that creates input fields / widgets based on the field types in the DB like there will be one in Cake 1.2. Now often you'll see people do something like this:

$MyModel =& new MyModel();

Now this one will get the task done - no question about it. But if you aim for better performance or even need some error handling, this won't quite cut it. Therefor I've created a little function that actually will. You pass it the name of any Model, and it will either return you an instance of it or 'false' indicating that it's not possible to get a reference of this Model:

function &getModel($model)
  // Make sure our $modelClass name is camelized
  $modelClass = Inflector::camelize($model);

  // If the Model class does not exist and we cannot load it
  if (!class_exists($modelClass) && !loadModel($modelClass))
    // Can't pass false directly because only variables can be passed via reference
    $tmp = false;
    // Return false
    return $tmp;
  // The $modelKey is the underscored $modelClass name for the ClassRegistry
  $modelKey = Inflector::underscore($modelClass);
  // If the ClassRegistry holds a reference to our Model
  if (ClassRegistry::isKeySet($modelKey))
    // Then make this our $ModelObj
    $ModelObj =& ClassRegistry::getObject($modelKey);
    // If no reference to our Model was found in trhe ClassRegistry, create our own one
    $ModelObj =& new $modelClass();
    // And add it to the class registry for the next time
    ClassRegistry::addObject($modelKey, $ModelObj);  

  // Return the reference to our Model object
  return $ModelObj;

A sample usage would be this:

$User =& $this->getModel('User');

If ($User!==false)
    debug('Oh no!');

This of course is not invitation to break up with the MVC pattern, but just a good approach to something you might need for a complex component/helper/etc. If you wonder were to place this function: I like using a component named 'Common' for things like that. This allows you to make static calls like Common::getModel in your project. But AppController, or bootstrap.php should work just as well.

Alright, I hope somebody finds this helpful and that I'll be able to do more postings again ; ).

-- Felix Geisendörfer aka the_undefined


You can skip to the end and add a comment.

Max said on Jan 22, 2007:

Nice, this will be useful for my idea of 'registration' helper/component.

Grant Cox  said on Jan 23, 2007:

Thanks for the tip Felix - my "attachModel" function is now using the ClassRegistry. I don't have any benchmarking, but I'm sure it'll make a small difference :)

One question though - you have a comment "Can't pass false directly because only variables can be passed via reference". What versions / configurations of php does this affect? While I realise that false won't actually be passed by reference (rather a copy) - I don't see how this will affect your application, and I didn't get any errors when I tested it locally...

Anonymous  said on Jan 23, 2007:

Keep it up Felix!

I can't wait until full rss feed access =)

/me quietly hints for people to click there on the left to get them off sooner.

While I still wear an anonymous mask I find my development ideas and approaches very similar to your and while I've been keen to the internets for a long while and resisted blogs and syndication this blog is one of the first I added to my reader.

Three cheers for Felix !

I thought you were php4, the passing by reference error is 5-centric no?

Felix Geisendörfer said on Jan 23, 2007:

The passing by reference errors is php4 centric. I initially wrote this function for my client project which is PHP5 and unless I'm wrong you don't need any of the '&'-reference magic in there because objects are passed by reference on default. However, when rewriting it for php4 I needed to declare my function to return something by reference and this means that I cannot directly return 'false' because php will protest. Therefor I'm using the $temp variable. Hope that makes sense ; ).

Anonymous: Maybe I can get the full feed working before the ads are gone, after all it's a feed burner problem with the maximum size a feed can have.

Daniel Hofstetter said on Jan 23, 2007:

Hm, what's the problem with FeedBurner? Up to now I didn't encounter any problems with it. And as Anonymous I hope you will switch to full feed mode ;-)

[...] Alright, before I start to bore you, here comes the code for it. (You might remember my old friend the getModel function) PLAIN TEXT PHP: [...]

This post is too old. We do not allow comments here anymore in order to fight spam. If you have real feedback or questions for the post, please contact us.