PHP Bootstrapping Basics

Have a look at the singleton pattern. You can double your bootstrap class as a resource container, e.g.:

$bootstrap = Bootstrap::getInstance();
$dbConn = $bootstrap->getPdoDbh();

You can include or require the file, or use the autoloader and make sure you have a call to instantiate the object on all your pages. You might even have a call to getInstance() on the bottom of the file, after the class definition.

Or you might use URL-based routing and have all your requests go through a single index.php file, like Zend Framework does. Or better yet, use Zend Framework.

This answer assumes you're doing OOP w/ PHP >=5, which really is the way to go.


1: Generally the bootstrap is in the "application" directory. It is called from the "public" directory which is in the same level as application (not inside of it). The index.php inside the public folder should include the bootstrap.php and that is where your Document_Root should be set to (note you may need to change / add some include paths for it to work)

2: It should only be included once via the index.php file in the public folder. Just including it there should be enough, if it was done correctly.

Hope that helps.


One of the more elegant means by which to bootstrap a PHP application is to do so using Composer.

Almost every PHP library uses Composer nowadays, and requiring a Bootstrap.php-like file is as simple as:

"autoload": {
    "psr-4": {
        "Acme\\Rocket\\": "src/"
    },
    "files": ["src/Bootstrap.php"]
},

Note the second property, files. (The first, psr-4, is standard PSR-4 boilerplate auto-loading, and is included only to make the example more real-world.)

Including the bootstrap file in this way doesn't make the naive assumption that the PHP application is executed in a web-server context, via index.php, or similar; the application could very well be a command-line application (or both, like Laravel/Artisan). Bootstrapping via the auto-loader makes this distinction a non-issue.


It depends on your application architecture.

If your architecture is the good old "flock of php scripts" - PHP scripts called directly from the browser - then you'll be including it at the top of each script, one way or another.

Most developers (and frameworks) these days marshall all their requests through /index.php one way or another, usually with some URL rewriting going on to make nice, pretty URLs for users to see.

In this day and age, you should probably be doing the latter, or at least thinking about it. It leads to much better organization, and even more importantly, allows you to keep all your code outside of the web server's document root, which is a good security practice for several reasons that are outside the scope of this answer.