Yapaf Introduction - how to write your own mvc in PHP

Back in the day before Symfony, ZF, Cake, Yii, Typo3 Flow and Laravel (and all the others) - you had to roll your own framework if you wanted to do something big in php. I had an app that I needed to write, and none of the early versions of MVC frameworks in PHP was appealing to me. I decided to write my own. Even though that framework was never released, and never intended to be used for anything else - I believe it has taught me (and a couple of other people) a bit or two about how to (and how not to) build mvc’s in php.

I decided at some point to extract code, rewrite code, and construct a very simple mvc based on this 7+ years old code to teach some lessons about how you could do something similar in todays modern php world. The project is a work in progress, and I will release more posts in this series in the near future - and I might even fix some of the issues I know to be in the current version of this mvc - however it is not my intention to build a production quality mvc.

The project currently consists of only 9 classes - all of which will be explained in upcoming posts.

yapaf\Application The entry point of the application which creates a configuration object. And on a run call (which happens on all web-requests) instantiates a DevServer and a RequestHandler.

yapaf\Configuration This object is a singleton (and kind of a god object… bad form, I know). This can be used to get the current Request, Response and Controller objects as well as read settings from a settings file. Last but not least it can register it’s routes (from the settings file) into a global variable, which is used by the router, to mutate the Request object to select the correct controller based on the current request.

yapaf\DevServer A simple class which just sets up a simple rule that if the current application is run as cli-server it returns static files directly.

yapaf\Request This object is the entry point to all state in the current request. That is environment vars, path segments, get/post vars and the document body of the incoming request.

yapaf\Response This object holds the output data, and handles headers.

yapaf\RequestHandler This instantiates a (subclass of) Controller, calls it with Request data, lets it mutate the Response, and renders the Reponse to the output.

yapaf\Router Mutates request data according to current input, and the routes set in settings.

yapaf\Controller Calls the current action, and returns data directly if the action returns anything, otherwise it renders the view, in the current controller methods context.

yapaf\View Handles view data, and renders a template with this data avaible. (The view engine is just basic php files rendered to the output buffer)

The yapaf [yet another php application framework] project is located on github.