views:

33

answers:

3

I have an helper class with some static functions. all the functions in the class requires a 'heavy' initialization function to run once ( like it was a constructor.. ).

is there a good practice ?

the only thing i thought of is calling 'init' function , and breaking it's flow if it already run once (using static $initialized var). problem is i need to call it on EVERY of the classe's functions :(

please help

+1  A: 

Sounds like you'd be better served by a singleton rather than a bunch of static methods

class Singleton
{
  /**
   * 
   * @var Singleton
   */
  private $instance;

  private function __construct()
  {
    // Your "heavy" initialization stuff here
  }

  public static function getInstance()
  {
    if ( is_null( self::$instance ) )
    {
      self::$instance = new self();
    }
    return self::$instance;
  }

  public function someMethod1()
  {
    // whatever
  }

  public function someMethod2()
  {
    // whatever
  }
}

And then, in usage

// As opposed to this
Singleton::someMethod1();

// You'd do this
Singleton::getInstance()->someMethod1();
Peter Bailey
Thank you very much. I probably be doing this way
I want to -1 (but I won't) for private constructor and `getInstance()`... You're going to make it VERY hard to test effectively... At least make it protected so that you have options...
ircmaxell
@ircmaxell - you're just talking about issues with the singleton pattern itself, really. And code posted by anybody on SO shouldn't be considered authoritative - especially simple examples that are only meant to be illustrative. Everyone's scenarios and situations are different
Peter Bailey
Quite true. I won't argue that (and that's why I didn't downvote, the content is good). I just hate seeing private methods/members (it's a pet peeve)...
ircmaxell
+2  A: 
// file Foo.php
class Foo
{
  static function init() { /* ... */ }
}

Foo::init();

This way, the initialization happens when the class file is included. You can make sure this only happens when necessary (and only once) by using autoloading.

Victor Nicollet
Thank you , thats a good solution. but my framework includes all helpers. is there a way to make it inside included file ?
I don't understand your question. All the above happens in the included file.
Victor Nicollet
+1  A: 

Actually, I use a public static method __init__() on my static classes that require initialization (or at least need to execute some code). Then, in my autoloader, when it loads a class it checks is_callable($class, '__init__'). If it is, it calls that method. Quick, simple and effective...

ircmaxell
nice...87654321
bgould