PHP Classes

File: multiton.test.php

Recommend this page to a friend!
  Classes of Andrei Alexandru   Simple Singleton and Multiton Class   multiton.test.php   Download  
File: multiton.test.php
Role: Example script
Content type: text/plain
Description: Usage ot the multiton Class
Class: Simple Singleton and Multiton Class
Create and manage one or more singleton objects
Author: By
Last change: Instance access from a loop
Date: 13 years ago
Size: 1,479 bytes
 

Contents

Class file image Download
<?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);