tags:

views:

40

answers:

1

Hi,

i've a little problem with the proper design for some simple database models. Lets say i have an User Object with getter/setters and an read method. Read querys the database and sets the properties.

class User extends MyDbBaseClass
{

protected $_id;
protected $_name;

public function setId($id)
{
 $this->_id = $id;
}

public function setName($name)
{
 $this->_name = $name;
}

public function getId()
{
 return (int) $this->_id;
}

public function getName()
{
 return (string) $this->_name;
}

public function read($id)
{
 // fetch ONE record from Database
 $this->_id = $this->setId($sqlResult['id');
 $this->_name = $this->setName($sqlResult['name']);
}

public function save()
{
 // do some sql stuff to save user to database
}

}

My Problem is, how to return multiple users?

public function getCollection()
{
    // fetch all user records from database
    forearch ($sqlResult as $result) {
     // ... no idea..
    }
}

Goal:

// works
$u = new User();
$u->read(1);
echo $u->getName();

// dont know the best way
$u = new User();
$uC = $u->getCollection();

foreach ($uC as $u)
{
    echo $u->getName();
}

Any best practices for this?

Greetings,Arne

+1  A: 

You could just return an array with users

public function getCollection()
{
  // fetch all user records from database
  $users = array();
  forearch ($sqlResult as $result) {
    // ... no idea..
    $user = new User();
    $user->_name = $result->name; // just an example
    $user[] = $users;
  }
  return $users;
}
Robert Cabri