I'm trying to understand OOP and having some trouble with a couple of concepts as I try to make the code workable and testable.
What if I have two tables: users and logins and I want to get all the logins for a specific user but also the user information, like name, job title, whatever.
$mdlLogins= new Logins();
$mdlUsers = new Users();
$mdlUsers->setMdlLogins($mdlLogins);
$mdlUsers->getAll();
class Logins
{
function getLogins($user_id)
{
// db query by $user_id and fetch loop into $logins
return $logins;
}
}
class Users
{
function setMdlLogins($model)
{
$this->mdlLogins = $model;
}
public function getAll()
{
// db query
foreach ($user=mysql_fetch_object($result))
{
$this->users[] = $this->mdlLogins->getLogins($user->getID());
}
}
}
Is that right? Or, should I be using static methods (skip the ->setMdlLogins()
and change getLogins to Logins::getLogins($user->getID())
)? Why not just use a regular function: get_user_logins()
?
What if I wanted to create a User object with Logins and each logins shows the Posts during that login and each Post shows the number of people who Viewed the post? Would it be best to use static methods to pull all that in, or create empty objects and inject them as dependencies:
$mdlViews = new Views;
$mdlPosts = new Posts;
$mdlPosts->setViews($mdlViews);
$mdlLogins = new Logins;
$mdlLogins->setPosts($mdlPosts);
$mdlUsers = new Users;
$mdlUsers->setLogins($mdlLogins);
$mdlUsers->getAll();
seems like a lot of work ... is that just too much for one object or it that typical of an object but maybe I should be less worried about unit testing and just use static methods instead of setting so many models the original model depends on?
How to keep things OOP, Unit Testable, but not make it so complicated?!?
I'm pretty dense about this stuff but I really want to understand it before starting my next probjects in January so I don't create a nightmare.
Thanks, Hans