Most of my programming over the past decade has been within the context of WordPress. Before that I had started out with “vanilla” PHP. That was before PHP had any object oriented capabilities.
Returning to non-WordPress PHP after all this time has forced me to rethink some pretty basic stuff. For instance, What’s the best way to launch an app if you’re writing one from scratch?
When you have a framework, all that is taken care of for you. And you might wonder why anyone would even care. Most of the time you’re going to use a framework rather than build absolutely everything from the ground up.
And yet, inquiring minds want to know.
Other languages, Java for example, have a
Main class that provides for initiation. In PHP, we can start wherever. Point a web browser to
index.php and include whatever else you need. Looking over various tutorials for “projects to learn PHP”, most of what I find is either long outdated or still jumps from one file to another, piecemeal. Need to process a form that adds a todo? Send the request to
It’s no wonder PHP still has a reputation for being for amateurs, given the advice I’m finding over internet searches. (And yet, here I am still wondering how to launch an app, absent a framework!)
I rather like the way the CakePHP framework resolves the issue. Assuming an app that’s running over an HTTP connection, the web root index loads the Composer autoloader, binds the app to the framework server, and calls the server’s method to render whatever the app sends to the server for a response. It’s an elegant little piece of code:
... require dirname(__DIR__) . '/vendor/autoload.php'; use App\Application; use Cake\Http\Server; $server = new Server(new Application(dirname(__DIR__) . '/config')); $server->emit($server->run());
Without the framework, it seems possible to do a similar thing, creating your own Main class, in the way other OOP languages might do it:
<?php // index.php use MyApp\Main; require dirname(__DIR__) . '/vendor/autoload.php'; $config = include './path/to/configfile.php'; $app = new Main($config); $app->run();
I’m curious. If you’ve written an app from scratch, or if you work with one that doesn’t rely on a framework for bootstrapping, how do you go about it?
Or, if you work in a language other than PHP, how does that language handle application launch?