Question

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.

Was it helpful?

Solution

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).

OTHER TIPS

Why not use this solution?

class Model_Person extends ORM 
{
      public function fullname()
      {
           return $this->firstname.' '.$this->lastname;
      }
 }

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

You can do the following in application/classes/ORM.php (application/classes/orm.php for Kohana prior to 3.2):

<?php
class ORM extends Kohana_ORM {
    public function __get($name) {
        $getter = 'get_' . $name;
        if (method_exists($this, $getter)) {
            return $this->$getter();
        }

        return parent::__get($name);
    }
}

Then you can just add a method to your model class:

public function get_fullname() {
    return $this->firstname . ' ' . $this->lastname;
}

And be able to access it as a property.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top