views:

116

answers:

4

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.

+2  A: 

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.

Brad F Jacobs
+1  A: 

it depends on what your bootstrap file does. If it's just a file that sets some ini settings and such to create a sane execution environment and establish a database connection, then simply including it with require_once in your scripts should be enough. If it's more of a single-point of entry then you can configure your server to filter all requests to it and have it dispatch to appropriate controller scripts.

Timothy
+2  A: 

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.

aib
+2  A: 

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.

timdev