I currently design all of my websites with a file for each page, then include common elements like the header, footer and so on. However, I've noticed that many frameworks and CMSs use the Front Controller pattern.
What are the advantages and disadvantages of using a Front Controller? Is the pattern simply used in frameworks and CMSs because it's not known which pages will exist in the final system?
The front controller design pattern means that all requests that come for a resource in an application will be handled by a single handler and then dispatched to the appropriate handler for that type of request. The front controller may use other helpers to achieve the dispatching mechanism.
The front controller design pattern is used to provide a centralized request handling mechanism so that all requests will be handled by a single handler. This handler can do the authentication/ authorization/ logging or tracking of request and then pass the requests to corresponding handlers.
DispatcherServlet is the front controller in Spring Web MVC. Incoming requests for the HTML file are forwarded to the DispatcherServlet.
Srikanth has a good answer. I'd like to elaborate on the alternative, though. Suppose you have this simple URL hierarchy:
/gallery /blog /admin/login /admin/newpost
If this is implemented with Page Controllers (PHP, for example), both gallery.php
and blog.php
will need to include some common.php
at the beginning (or nearby). However, both login.php
and newpost.php
may include admin-common.php
, which itself pulls in 'common.php' and does '/admin/'-specific setup, like verifying the user is authenticated.
In general, if you have a hierarchy of URLs, it ends up looking a lot like object inheritance trees. Except instead of using language-level inheritance, you're inheriting the environment of whatever foo-common.php
you include.
I can't imagine how a Front Controller is increasing testability, In the end, the exact same tests from an automated HTTP user-agent are required, regardless of implementation.
One major downside of Page Controllers is it does make your web application dependent upon its hosting environment. It also forces your developers to "see" the same structure as end users, but I consider that a good thing, considering the number of sites I see that have absolutely atrocious URLs.
These are the reasons why i would never use a front controller.
The front controller pattern simply doesn't fit IMHO. Build applications much the same way as UNIX, break a larger problem into small units that do one task, and do that task really well. Most of the frameworks are pushing developers to use front controllers and they are simply wrong.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With