PHP Factory & Singleton

Posted by kris on June 12, 2007

A friend sent me an ICQ today asking an easy way to load classes on the fly, but keep a registry of them to save resources if he calls said object more than once per page load. Here is the quick example I gave him:

Code: php
  1.  
  2. class loader {
  3.     static $storage;
  4.  
  5.     public function factory($name) {
  6.         require_once ‘lib/’ . str_replace(’_', ‘/’, $name) . ‘.php’;
  7.         $instance = new $name;
  8.         return $instance;
  9.     }
  10.  
  11.    public function singleton($name) {
  12.        if (!isset(self::$storage[$name])) {
  13.            self::$storage[$name] = self::factory($name);
  14.        }
  15.        return self::$storage[$name]
  16.    }
  17. }
  18.  
  19. $foo = loader::singleton(’bar’);       // loads lib/foo.php
  20. $bar = loader::singleton(’foo_bar’); // loads lib/foo/bar.php
  21. ?>

I understand there is absolutely no error catching here, the point is how to store an object and call on demand. Simple, but figured if he needed some help, others might as well.

Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

Comments

Close
E-mail It