0

I'm looking for a class pattern that helps me to obtain a global instance of Smarty and use the same during all application life. I tried to use a singleton o factory singleton pattern like this:

final class Personal_Smarty
{
    static private $instance;

    private function __construct() {}

    static public function instance()
    {
        if( !isset( self::$_instance ) )
        {
                $smarty = new Smarty();

                self::$instance = $smarty;
        };
        return self::$instance;
    }

}

but I think it's not what I need because I need to create a Smarty instance only for once during all application life (so I don't want to be forced to create a Smarty instance for every request).

Is there a good way to do that? I'm not sure it's a good practice to do so and whether I will have problems with that. What do you think? The reason for my question is that I think that creating the smarty instance for every php script I use could be onerous (overhead), but maybe it's only my thought.

Frank
  • 2,083
  • 8
  • 34
  • 52
  • 1
    What do you mean by every script? Are you trying to keep this instance over multiple requests? – andy Sep 24 '14 at 15:31
  • What you're looking for is called Singleton. But it's a really bad idea to use them, so don't. – GordonM Sep 24 '14 at 15:31
  • @GordonM why would a singleton be a really bad idea? – andy Sep 24 '14 at 15:32
  • @andy http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons – GordonM Sep 24 '14 at 15:35
  • @andy yes, that's what I meant. – Frank Sep 24 '14 at 15:37
  • 1
    Revised comment: You can't do this in PHP. The whole language is built around the idea of a Shared Nothing Architecture. Resources that exist for a particular instance exist for that instance only. Not even the singleton antipattern can get around that. – GordonM Sep 24 '14 at 15:41

1 Answers1

1

The only way to share data across different requests is to store it in a session. However, data in a session also needs to be stored and loaded in between which is why storing a class instance in a session is not a good idea.

Basically, your assumption that creating a smarty instance is a performance issue is just not correct.

andy
  • 2,002
  • 1
  • 12
  • 21