When to use a singleton?
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?
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.
If an object doesn't really need to be instantiated more than once, consider declaring a class with static methods instead.
精彩评论