• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
ActiveRecords x Model Mapping Fields

#1
[eluser]Marcus Cavalcanti[/eluser]
Hi CI People,

I have one question about of the use of models and active records simultaneously.

Ih i have a entity called "user" and the "user" entity have 5 properties like a: id, user, password, name, status.

In my model i would have something like a:

Code:
class User extends Model {
  
  var $id;
  var $login;
  var $pass;
  var $name;  
  var $status;

  function getUserByName () {
$query = $this->db->getwhere('user', array('name' => $this->name));
return $query->result();
  }

}

The problem is when i using the result of model in my controller, the properties of model the is equal the name of fields of table user in my database and is not right. The correct is mapping the fields through the model and if the name of the fields database has change, the unique place that i change is the model, not the controllers.

I thought to solve this using beans (getters and setters methods), like a suggest in this thread: http://ellislab.com/forums/viewthread/45754/

My idea is return the objects (beans) that represents my fields in database.

Example of using beans:
Code:
function getUserByName () {  
   $query = $this->db->getwhere('usuario', array('nm_name' => $this->name));
  
   $arrObj = array();
   foreach ($query->result() as $row) {
    $obj = new User_Model();
    $obj->setId($row->id_user);
    $obj->setLogin($row->nm_login);
    $obj->setPass($row->nm_pass);
    $obj->setName($row->nm_name);
    $obj->setStatus($row->bo_status);
    $arrObj[] = $obj;
   }
  
   return $arrObj;
  }

Anyone knows if the CI have's a more ellegant solution for this?

#2
[eluser]fMertins[/eluser]
Hi... I´m guess i´m thinking like you, because I wanna retrieve from my models/persistence objects (beans) from my own classes, like "Customer", "Product", "City", "Invoice", etc... and not stdClass objects with props identicals to MySQL fields tables... :-)

But I suggest you don´t use setters & getters, instead of use magic methods __set() & __get().

Greetings

PS.: from Brazil? Because "usuario" word in your post... :-P

#3
[eluser]Marcus Cavalcanti[/eluser]
Yes, i am from braSil, hehe =)


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.