Welcome Guest, Not a member yet? Register   Sign In
sub-models? Getting objects out of database
#1

[eluser]alexmiller[/eluser]
I am slowly getting to grips with CI.

I have a model for people. It has fields for first_name, last_name etc. So I have set up person_model as a CI model eg. (pseudo-code)

Code:
class person_model extends Model
{
    function getPersonById($id)
    {
        $Q = $this->db->get_where('people',array ('user_id'=>$id),1);
        return $Q->row();
    }
}
I can then call this in my controller:

Code:
$person = $this->person_model->getPersonById(1);
But here's the question:
I want to be able to do things like:
Code:
echo $person->possessive(); // adds 's to end of first_name
echo $person->full_name(); // concats first_name and last_name

I know I can get an object out of my database result, but how can I add methods to that object? More importantly, am I circumventing the MVC structure here? In a way, I am creating another model layer.
#2

[eluser]xwero[/eluser]
The person variable you create is an object but it has only properties and no functions. In order to do this you need to use a class that has the functions you need.
Code:
class Person
{
  
   var $person;

   function Person($person)
   {
      $this->person = $person;
   }

   function possessive($prop = 'firstname')
   {
      if(isset($person->$prop))
      {
         $person->$prop .= "'s";
      }
   }

   function show($props = array('first_name','last_name'))
   {
      $temparr = array();
      foreach($props as $prop)
      {
         if(isset($person->$prop))
         {
             $temparr[] = $person->$prop;
         }
      }
      return implode(' ',$temparr);
   }
}
Then you can do in your controller
Code:
$this->load->library('person');
$person = new Person($this->person_model->getPersonById(1));
And then the methods should work as in your snippet.
#3

[eluser]richthegeek[/eluser]
you could change your model structure so it acts more like an representative Object

Have a class structure like this:
Code:
person_model
---------------------------------
   -> Array persons
   -> Reference activePerson
---------------------------------
   -> function getPersonById( $id )
   -> function setActivePerson( $id )
   -> function getActivePerson()
   -> .. other functions

When getPersonById is called, it loads that person's data from the database and adds it to the persons array with the key eqaul to the ID. It also sets activePerson to be a reference (=& $this->persons[$id]) to the persons array item.

set* and getActivePerson simply change the target of the activePerson reference.

All other functions then act upon the $this->activePerson variable.
#4

[eluser]alexmiller[/eluser]
Excellent that makes sense. It seems that the first reply is likely to be the easier one to work with, while the latter has the advantage of keeping everything within the model.

Thanks, I will crack on and see where I get to!




Theme © iAndrew 2016 - Forum software by © MyBB