开发者

PHP OOP Design for simple Models

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 Dat开发者_运维问答abase
    $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?


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜