NYCPHP Meetup

NYPHP.org

[nycphp-talk] Multitons and Late Static Binding

Daniel Convissor danielc at analysisandsolutions.com
Sat Jul 26 11:16:52 EDT 2008


Hi Paul:

Hadn't heard of "multitons" before despite my using them under the name 
"singletons."  So I checked out the Wikipedia entry about it, 
http://en.wikipedia.org/wiki/Multiton.  What's even more interesting, is 
the versions of this article prior to May of this year said this term is 
kind of made up:

   Multiton is a (disputed) term often used to describe a Singleton-like
   pattern that allows more than just one instance to be created. While
   there is no official Gang of Four design pattern called Multiton...

That aside, the code I was doing this in has its roots in PHP 4, so the 
hash/objects were being stored in $GLOBALS.  But seeing Wikipedia's 
example made me realize I could store the hash in the class itself.


> In the article I suggest that LSB could be used to do it better in PHP, 
> but I haven't figured out exactly how.  Any ideas?

Not sure how late static binding is really needed for this since the 
pattern works just fine in PHP 5.2:

class db {
    private $db_resource = null;
    private static $dbs = array();

    public function __construct($user, $db, $host, $port, $pass) {
        $this->db_resource = @new mysqli($host, $user, $pass, $db, $port);
        if (mysqli_connect_errno()) {
            // handle it...
        }
    }

    public static function multiton($user, $db, $host, $port, $pass) {
        $hash = self::get_auth_hash($user, $db, $host, $port, $pass);
        if (!isset(self::$dbs[$hash])) {
            self::$dbs[$hash] = new db($user, $db, $host, $port, $pass);
        }
        return self::$dbs[$hash];
    }
}


--Dan

-- 
 T H E   A N A L Y S I S   A N D   S O L U T I O N S   C O M P A N Y
            data intensive web and database programming
                http://www.AnalysisAndSolutions.com/
 4015 7th Ave #4, Brooklyn NY 11232  v: 718-854-0335 f: 718-854-0409



More information about the talk mailing list