0

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?

akikos
  • 11
  • 4
  • 2
    See http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons for a discussion of this pattern – JAL Aug 02 '10 at 12:07
  • 1
    More and more people start calling singleton an anti-pattern nowadays, you should really try to avoid using it. – Mateusz Dymczyk Aug 02 '10 at 12:15

2 Answers2

11

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.

Community
  • 1
  • 1
Gordon
  • 296,205
  • 68
  • 508
  • 534
0

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

bcosca
  • 16,475
  • 5
  • 36
  • 50