As things are now, the logic in our page scripts is highly repetitive. They all look very similar. Each one loads a setup script, instantiates a series of dependencies for a page controller, invokes that controller, and sends the response.

Our front controller gives us a place where we can execute the common elements of each page script and remove that repetition. Once the repetition has been removed, we can begin to eliminate the page scripts themselves.

In essence, each of our page scripts follows this organizational flow:

Because we have been diligent about always using the same variable name for our controller object ($controller), always using the same method name for invoking it (__invoke()), and always using the same variable name for the response ($response), we can see that the only part of each page script that is different is the central section. That central block builds the controller object. Everything before and after is identical.

Further, because we have a front controller to handle all incoming requests, we now have a place to put the common before and after logic of every page script. That is what we will do here.

First, we modify the front controller logic to perform the logic common to every page script. We change it from the code listed in the previous chapter to something more like this:

We have replaced the line that requires the Router class file with a line that requires the setup script. (Way back in the chapter on autoloading, we put the autoloader into our setup script, so it should be autoloading the Router class for us now.)

We have also added two lines after requiring the file $route to the page script. These invoke the controller and set the response. We use the common variable names for the controller and response objects in this shared logic. (If you chose something other than $controller and $response in the page scripts, replace those in the above script. Similarly, if you used a common controller method other than __invoke(), replace that as well.)