The Separation of Concerns
The Separation of Concerns¶
One down-side of our framework right now is that we need to copy and paste the
code in
front.php each time we create a new website. 40 lines of code is
not that much, but it would be nice if we could wrap this code into a proper
class. It would bring us better reusability and easier testing to name just
a few benefits.
If you have a closer look at the code,
front.php has one input, the
Request, and one output, the Response. Our framework class will follow this
simple principle: the logic is about creating the Response associated with a
Request.
Let's create our very own namespace for our framework:
Simplex. Move the
request handling logic into its own
Simplex\\Framework class:
And update
example.com/web/front.php accordingly:
To wrap up the refactoring, let's move everything but routes definition from
example.com/src/app.php into yet another namespace:
Calendar.
For the classes defined under the
Simplex and
Calendar namespaces to
be autoloaded, update the
composer.json file:
Note
For the Composer autoloader to be updated, run
composer update.
Move the controller to
Calendar\\Controller\\LeapYearController:
And move the
is_leap_year() function to its own class too:
Don't forget to update the
example.com/src/app.php file accordingly:
To sum up, here is the new file layout:
That's it! Our application has now four different layers and each of them has a well defined goal:
web/front.php: The front controller; the only exposed PHP code that makes the interface with the client (it gets the Request and sends the Response) and provides the boiler-plate code to initialize the framework and our application;
src/Simplex: The reusable framework code that abstracts the handling of incoming Requests (by the way, it makes your controllers/templates easily testable -- more about that later on);
src/Calendar: Our application specific code (the controllers and the model);
src/app.php: The application configuration/framework customization.
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.