0

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?

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.