When to use Front Controller pattern in PHP?

Using the Front Controller pattern in PHP always seemed fairly pointless to me.

I believe that using PHP’s native features with care usually leads to the best code; simple, re-usable components. For example, passing in an object of class ‘MyLogger’ to every object in the system not only ties all the components to using MyLogger, making their use in a system without MyLogger awkward, but the reverse too: any imported code would need to some how be converted to use MyLogger. It’s better to just properly use PHP’s native methods.

The same goes for MVC patterns and so on. Specifically, the front-controller pattern. The paths-to-controller mapping is very effectively done by having one publicly accessible php file for each page, meaning no logic necessary for mapping.

But there was one issue with this that always bugged me. The code in those publicly visible php files, as simple as they may be, (requiring a core bootstrap file and instantiating a couple of objects that do the heavy lifting), were a pain to write automated tests for. Every page would need a test, to check that the cut-and-paste between them had not been broken. Every new page introduced a new weak spot.

But with the Front Controller, all that was reduced to a single page. So there’s the biggest advantage for a front-controller, in my opinion.

Saying that, I don’t think that Front Controller is always the best idea. It can still involve very complex code, or complex debugging. Most who’ve used Apache’s mod_rewrite would agree, I’m sure.

In Martin Fowler’s book, “Patterns of Enterprise Application Architecture”, he points out that it is fine to have a system that uses both Front Controller(s) and Page controllers. There’s a trade-off, and like I’ve heard a thousand times in programming, it ‘depends’. On the requirements, the developers, the technology, and so on. But at least I have now consolidated what to me is the most significant reason for considering the Front Controller, yet why I am unlikely to use it exclusively.

 

Loading Facebook Comments ...

Leave a Reply

Your email address will not be published. Required fields are marked *