Recess Developer Forums: Existence of Blank Objects - Recess Developer Forums

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Existence of Blank Objects Behavior of Model::exists()

#1 User is offline   KevBurnsJr Icon

  • Icon
  • Group: Administrators
  • Posts: 86
  • Joined: 25-August 09
  • LocationSilicon Valley, CA

Posted 09 March 2010 - 03:41 PM

Currently, the exists method on Model instances with no set properties returns true.
This results in the blank object being hydrated with data from the first row in the db.
This seems wrong. Blank objects should not be considered to exist.

/**
 * Shortcut method which will determine whether a row
 * with the current instances properties exists. If so, it will
 * preload those values (side effects).
 * 
 * Usage:
 * $model->id = 1;
 * if($model->exists()) {
 *  die('a lonesome death');
 * }
 *
 * @return boolean
 */
function exists() {}

Here's how Model::exists() used to behave.

$user = new User();
echo ( $user->exists() ? $user->id : 0 );

1

Here's how it behaves now

$user = new User();
echo ( $user->exists() ? $user->id : 0 );

0

If there are no model column properties set, Model::exists() returns false.

Old code:

function exists() {
    $result = $this->select()->first();
    if($result !== false) {
        $this->copy($result, false);
        return true;
    } else {
        return false;
    }
}


New code:

function exists() {
    $descriptor = self::getClassDescriptor($this);
    $blank_object = true;
    foreach($this as $column => $value) {
        if(in_array($column, $descriptor->columns) && isset($value)) {
            $blank_object = false;
        }
    }
    
    if(!$blank_object) {
        $result = $this->select()->first();
        if($result !== false) {
            $this->copy($result, false);
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

Logically it's the diff between

... WHERE 1 [&& (...)]
... WHERE 0 [|| (...)]


Kris, have you considered this use case?
Do you agree with my assessment?
Less Talk, More Code.
1

#2 User is offline   KrisJordan Icon

  • Administrator
  • Icon
  • Group: Administrators
  • Posts: 78
  • Joined: 25-August 09
  • LocationNorth Carolina, USA

Posted 09 March 2010 - 03:46 PM

This makes complete sense here. Is there a commit I can pull from? Thanks for coding this up Kev.
0

#3 User is offline   KevBurnsJr Icon

  • Icon
  • Group: Administrators
  • Posts: 86
  • Joined: 25-August 09
  • LocationSilicon Valley, CA

Posted 12 March 2010 - 01:26 AM

No but I'll throw it on github now....

Here it is
http://github.com/Ke...26eb27b30533b5e
Less Talk, More Code.
0

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users