Static Controllers in PHP MVC

mvcobject-orientedPHP

I have built myself a PHP MVC framework to meet my needs. As pretty much all of the core classes are static, I just stumbled upon the idea of having static controllers. I know that for some reason static classes are not perceived well by programmers, however if a class makes no sense to have an instance I really can't see any good reason to create one.

For example the System class ( b.k.a. App in other frameworks ) that initializes the whole framework includes configuration files and calls the front controller. There cannot be two instances of this class – the system is only initialized once. Yes it does have other functions as well but none of them relate to an instance – getClientIP, handleException, handleError etc.

So following the same path of logic, my controllers have no properties and are generally used once per request. However when I think about it, I have never seen a framework with static controllers. Static library classes – yes, but static controllers – never. Is there any good reason not to have static controllers in an MVC framework?

P.S.: And yes I know there's no such thing as static classes in PHP yet, basically what I call a static class is a class with private constructor and only static methods.

Best Answer

In a complex routing system, generally a controller should be looked up by a name that is based on what its job is or what route it handles. When your app "boots up" you register controllers under those names so that the class name isn't hard coded everywhere, allowing you to swap out controllers easily. This is what the App facade in Laravel does.

There is nothing wrong with using static classes (abstracts with final private constructors) in place of singletons (I personally think they are preferable to singletons), and if you know your core won't grow too much then this is fine. The drawback is if you ever want to switch to the more dynamic way of doing it you're going to have to refactor.

An ideal MVC is thin. As Laravel's creator Taylor Otwell put it, be careful not to box yourself in to a "pure MVC" paradigm. A web service consists of more than MVC; MVC is just a pattern, not an architecture.