This is a question regarding best practice for storing and accessing an object from another class.
I'm using a simple homemade MVC paradigm in PHP, the class is called User and has its own methods and vars that essentially works as a database abstraction layer.
This class is instantiated by calling new
User($userID)
which retrieves the data from a database given $userID or throws an exception if there is no user with that ID.
Every page has its own WebViewController
class governing the content of the page, and in some instances the page needs to call $loggedInUser
dependent functions such as WebViewController->displayUserFriends()
, which might look like this:
<?php
class WebViewController extends WVCTemplate
{
// Class vars and methods
// ...
public function displayUserFriends()
{
foreach($loggedInUser->getFriends() as $friend) {
// Do something
// ...
}
}
}
?>
Is there a (best practice compliant) way to store LoggedInUser as a sort of global object, so it could be accessed inside of any class or WebViewController
without instantiating it inside every class it's used?