views:

26

answers:

1

Say I have a very simple model that looks like this:

class Model_Person extends ORM
{
 /*
     CREATE TABLE `persons` (
   `id` INT PRIMARY KEY AUTO_INCREMENT,
   `firstname` VARCHAR(45) NOT NULL,
   `lastname` VARCHAR(45) NOT NULL,
   `date_of_birth` DATE NOT NULL,
  );
 */
}

Is there a way I can I add sort of a pretend property with the full name?

So that I for example could do this:

$person = ORM::factory('person', 7);
echo $person->fullname;

instead of this:

$person = ORM::factory('person', 7);
echo $person->firstname.' '.$person->lastname;

Another example could be an is_young property that would calculate the persons age and return true if the age was below a certain number.

A: 

You can use "magic" __get() method like this:

public function __get($column)
{
    switch($column)
    {
        case 'fullname' : 
            return $this->firstname.' '.$this->lastname;

        case 'is_young' :
            // calculate persons age
    }
    return parent::__get($column);
}

Or you can create additional methods like fullname() and age() (seems better to me).

biakaveron
Yup, that's what I ended up doing. And even though the magic __get is a bit uglier than a method, I still like to keep properties as properties and methods as methods. Maybe cause I'm used to C#... Removed the break statement. Don't need that when you have a return :)
Svish
~offtop~ Yes, I know about `break`, but I always add it in the end of `case` - its like a little habit :) For example, if I change this method and remove `return` (for example: `$result = ...`), I can easily forget about `break`...
biakaveron