CakePHP Model::read() vs Model::find()

 Apr 26, 2013

One of the things to be careful of in CakePHP development is the minor differences between these 2 methods and what they actually do.

The key thing to remember here is that Model::read() will mutate the models state as well as returning the data. Model::find() will not.

I’ve fallen foul of this one a couple of times recently (yeah I know, more fool me), so I just wanted to get a quick post up here. Share the knowledge and, by writing it down, get it to stick in my own mind.

Model::read()

<?php
// in model Widget for example

$widget = $this->read(null, $id);

// $widget will be assigned with the data from the row 
// with id $id

// $this->data instance var will also be assigned with returned
// data, overwriting anything that was in there before

Model::find()

<?php
// in model Widget for example

$widget = $this->findById($id); // the findByX methods use Model::find()

// $widget will be assigned with the data from the row 
// with id $id

// $this->data instance var will still hold the same value it had before the find() call

I was caught out with this recently when looking up a value in the database during a custom validation method. I accidentally used the read() method, which overwrote the data from the form that was in $this->data and replaced it with the data from the database, which in fact caused validation to pass when it shouldn’t

There is a time and place for both methods, just don’t get them mixed up otherwise they can cause some strange effects.

And if you’re like me, it could take a couple of hours debugging to notice the mistake!