Implementing PHP Front Controller without singleton: conceptual question

I have a "conceptual" question about front controller implementation in php.

Most of the front controllers that I have seen are implemented using Singleton, I'm not a big fan of the singleton template, and I created a container that has a static property that will store a single instance of Front Controller.

In singleton, I had to put the initialization code inside the constructor (or the method called by the constructor):

$fc = FrontController::getInstance(); 

With the container, I could set the configuration outside of FrontController, that was my goal, and I still have an easy way to get FrontController.

 $fc = Container->getFrontController(); 

This code looks a lot cleaner to me, and I can get a pure subclassing without worrying about parent constructors.

This is exactly the same when loading, but in practice the difference in my previous implementation is that now I can create FrontControllers anywhere in the application (inside the DAO or inside the Action), because the constructor is no longer private / protected.

My question is, β€œBad practice” gives the user of my classes the ability to instantiate FrontController anywhere in the application? I would write documentation and deliver the container to other classes, but I'm still wondering if I should prohibit strange use.

+6
source share
2 answers

Is there a real reason to instantiate FrontController inside the application? If there is, then go ahead. Otherwise, I am a little skeptical about this, as this may complicate the situation later. I am afraid that someone will use new instances of FrontController when there is a much simpler way - either out of laziness or because they don’t know anything better. When they find something that works, some people tend to continue to do it, even if there is a better way. Never forget that you may have to work with people who are not as good as you.

Personally, I would hide it or not allow it at all. However, I will keep in mind the latest releases. If you ever stumble upon the case when it is the best option, be sure to add it to your "official" interface.

Do not forget that after you have released the function into the wild, it is painfully difficult to kill.

+2
source
 $fc = Container::getFrontController(); 

Sounds good to me.

I don’t think it would be bad practice to allow developers to retrieve an instance of Front Controller anywhere, if you correctly control what developers can do with it (for example, do not overwrite any property or do its methods in the wrong order without indication errors / warnings for the user).

+2
source

Source: https://habr.com/ru/post/885567/


All Articles