I am attempting to create my first object orientated web app and have a question regarding how to globally reference an object. Not sure if it is necessary or not, but here is a bit of background. The app is a single page app.
Index.php creates a new instance of the "Page" class. This instance checks for a url parameter (page=???) and then checks for the existence of an appropriate content class and calls a function within it. If that page class doesn't exist, it calls another 404 class and displays that instead.
Each page content class is extended from a BasePage class. So for example index.php?page=Home
would work like this
+---------+ +----------+
| | creates instance of Page.php | |
|index.php|----------------------------->| page.php |
| | | |
+---------+ +----------+ +----------+
| | /
| base.php | /
| | / "Page" loads the relevant class
+----------+ / and calls a function within it
home.php | |/_
extends base.php +----------+
| |
| home.php |
| |
+----------+
Hopefully that makes sense so far. The problem I have hit now is I need a "User" object which is created from an instance of a "User" class. This User object will be referenced in almost every page, Index.php, page.php and home.php. What has been happening up to now is I have created instances of the User class in every other class. This works but often results in multiple calls to a database and multiple User objects being created. I think the best approach would be to make the User class a singleton class, but where do I create that singleton object. If I create the instance in base.php, home.php has reference to it, but page.php and index.php do not. If I create the instance in index.php, no other page has access to it unless I pass it to every class - which gets messy. (I know, i have tried).
So my question is, how do I make a singleton object that is reachable by every page? I thought putting it in the global scope would help, but a) i don't know how to do that and b) i have read scores of articles about why globals are a bad thing.
Can anyone offer any advice? How should I be creating my User object?
Thanks