When to use a singleton?

旧时模样 提交于 2019-12-25 00:42:31

问题


I have this code:

class MyController {
public function newUserAction()
{
    $view = new View('myfrontend');
    if($this->request->isPost())
    {
        $form = new MyForm;
        $posts = $this->request->getPosts();
        if($form->isValid($posts))
        {
            //...
        }
    }
    $view->display();
}

}

So, everytime the form is not filled in correctly, the process starts again and so every time there is a "new View('myfrontend')" ect. But is that a good thing? To have a new view object again and again and again.

Ain't it better to work with singletons here?


回答1:


Never ever. Simple as that.

When you display an invalid form again, it has to be resubmitted anyway. That will be an entirely new Request. The application will go through through the full bootstrap and dispatch. A singleton would not help here, because Singletons in PHP will also only live for the Request.

In addition, Singletons are much more difficult to test. I have yet to come across a UseCase where a Singleton can not be avoided when using Dependency Injection. Even Erich Gamma, one of the Singleton pattern's inventors, doubts this pattern nowadays:

"I'm in favor of dropping Singleton. Its use is almost always a design smell"

You are best off avoiding Singletons.




回答2:


If an object doesn't really need to be instantiated more than once, consider declaring a class with static methods instead.



来源:https://stackoverflow.com/questions/3387459/when-to-use-a-singleton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!