<?php
// Require the singleton class
require_once 'Multiton.class.php';
/**
* Let's say that we have a web site that uses more than one database
* and we want only one instance of the DataBase class for each database
* connection.
* DataBases:
* - Forum
* - Blog
*/
// Working with various MySQL databases but only one driver:
$ForumDataBase = Multiton::GetInstance('ForumDataBase');
$BlogDataBase = Multiton::GetInstance('BlogDataBase');
// $BlogDataBase->Connect($host, $user, $pass, $database);
// $ForumDataBase->Connect($host, $user, $pass, $database);
// Better (using the Database name as $id):
// $ForumDataBase = Multiton::GetInstance($database, $host, $user, $pass);
// Of course in the class we have to call the constructor like: new self($host, $user, $pass);
// $BlogDataBase->Select('SELECT * FROM `archives`');
// $ForumDataBase->Select('SELECT * FROM `users`');
// If we have a lots of instances, something like users:
$users = Multiton::GetInstance("user_id_1")
->GetInstance("user_id_2")
->GetInstance("user_id_3");
// Note that in this case $users point to "user_id_3"
// To access the other ids use a foreach loop
foreach($users as $user)
{
// $user->DoSomething();
}
// Fatal error -> private constructor
$newInstance = new Multiton();
// Fatal error -> No clonning
$clone = clone $BlogDataBase;
// Fatal error -> No serialization
serialize($BlogDataBase);
|