PHP Bootstrapping Basics

Viewed 25089

I'm writing my first PHP app. Everyone talks about having a bootstrap.php to initialize your app. This makes sense and I've put together one that I'm happy with. There's two things I don't understand, and which no one seems to mention:

  1. Where do I call my boostrap from? Do I include it in every page? Please tell me there's a better way...

  2. How do I make it so my bootstrap is not called more often than needed? I assume it only needs to be called either at the start of the app or the start of a new session.

5 Answers

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.

Related