Changes to Model:find('first') in CakePHP 2.3

Published on Jan 30, 2013 by Jamie Munro

A new stable release of CakePHP has just been released a few days ago, version 2.3.  With this many great new changes have come out of it.  You can read the full change log here:
http://bakery.cakephp.org/articles/lorenzo/2013/01/28/cakephp_2_3_0_is_out

One of the things that immediately caught my mind was this great big bolded sentence:
IMPORTANT: Model::find('first') will now return an empty array when no records are found. Make sure you update your tests!

Immediately after reading this I thought major code changes were going to be required; however, luckily my fear was unfounded.  Let me provide an example...




Here is a typical query that I would perform:


$user = $this->User->find('first', array('conditions' => array('id' => $id)));


Previously this function would return null if no results were found; however, no as you can see it will return an empty array.  After performing this function I would either in my controller or in my view execute the following code to detect if a user was found or not:


if ($user) {
// User found, do something
} else {
// No user found
}


Have no fear, even after this subtle change, the code still works as expected.

HOWEVER!

If your unit tests are asserting that the variable is null these will fail as it now must assert that count array is equal to 0.  Nice and simple, so remove panic :)

Tags: CakePHP | cakephp 2.3

Related Posts

blog comments powered by Disqus