I am making a simple PHP application with an MVC design. All of the requests are being sent to index.php and then routed to the appropriate controller. Because all of the requests go through index.php, I want to create some objects there and be able to use them globally, regardless of which controller handles the request. Namely, these objects are of type User, ErrorHandler, and Database.
Having a global User class, for example, allows any controller to check if the user is logged in by checking $user->loggedIn (or something like that) where $user is instantiated in index.php.
Here is what I am describing in code:
// index.php:
<?php
include('lib/User.php');
$user = new User();
// other stuff that index.php needs to do, perhaps route to FooController
?>
// FooController.php:
<?php
class FooController {
function __construct() {
global $user;
if ($user->loggedIn) {
// do whatever
}
}
}
?>
This is just random code I just typed up so please excuse any stupid errors — but I hope you get the idea. This code will work, but the global $user; line must be included in every function inside FooController.php.
This will get annoying when every function must have three global statements, one for User, ErrorHandler, and Database. Is there a better way to go about this, while preserving my MVC design?
I ended up doing this:
Every controller extends the BaseController (which has some abstract functions as well, this is just an example of a BaseController which solves this specific problem). This way I only had to use
globalonce, and then I could use the user, db, and error handler instances across every controller by simply callingparent::__construct()in each controller’s constructor and then referring to them by$this->user, etc.