Stupid Cake PHP mistakes 1: Assuming $model->create() returns true

|
My new routine of starting my days working on my personal project is working out quite well. The excitement over the project really allows me to work throughout the day with an increased focus. My morning goal was to have the user registration page completed for Passbook, however that did not end up being the case. All I got done was the registration form with error checking. The reason for the delay was simply due to one line of code that took about 20 minutes to debug. So to honour my crazy mistake I decided to start listing my stupid Cake PHP mistakes so that no one else has to repeat it.

The problem I had this morning was caused by my trying to make my code more elegant through the use of the code segment below as my saving code.

if ($this->User->create() and $this->User->save($this->data)) {

Cake PHP recommends calling the create function to re-initialize a model before saving a new record therefore I decided to combine it with the save call, which will also do validation for me. This turned out to be a mistake as the create() function for AppModel does not actually return true. The boolean condition returned evaluates to false therefore the correct method of creating new records remains:

$this->User->create()
if ($this->User->save($this->data)) {

I guess the lesson here is don't refactor until you have a working copy and that sometimes shortcuts aren't worth the time.

0 comments:

Post a Comment