Login   Register  
PHP Classes
elePHPant
Icontem

File: multiton.class.php

Recommend this page to a friend!
Stumble It! Stumble It! Bookmark in del.icio.us Bookmark in del.icio.us
  Classes of Andrei Alexandru  >  Simple Singleton and Multiton Class  >  multiton.class.php  >  Download  
File: multiton.class.php
Role: Class source
Content type: text/plain
Description: Multiton Implementation Class
Class: Simple Singleton and Multiton Class
Create and manage one or more singleton objects
Author: By
Last change: Bug fix:
function UnsetInstance($id) allways triggers an error.
Date: 2 years ago
Size: 2,022 bytes
 

Contents

Class file image Download
<?php
/**
 * Multiton class implementing Iterator interface thanks to Tom Schaefer
 */

class Multiton implements Iterator
{
    
/**
     * The list of instances of this class
     * @var object
     */
    
private static $instances = array();

    
/**
     * Returns only one instance of this class per id
     * @param string $id
     * @return object
     */
    
public static function GetInstance($id)
    {
        if (!empty(
$id))
        {
            if (!isset(
self::$instances[$id]) || !self::$instances[$id] instanceof self)
                
self::$instances[$id] = new self();

            return 
self::$instances[$id];
        }
        
trigger_error("Empty ID!"E_USER_ERROR);
    }

    
/**
     * Removes the instance.
     * @param string $id
     */
    
public function UnsetInstance($id)
    {
        if (!empty(
$id))
        {
            if (isset(
self::$instances[$id]) && self::$instances[$id] instanceof self)
                unset(
self::$instances[$id]);
            return 
true;
        }
        
trigger_error("Empty ID!"E_USER_ERROR);
    }

    
/**
     * Private constructor
     */
    
private function  __construct()
    {

    }

    
/**
     * No serialization allowed
     */
    
public function __sleep()
    {
        
trigger_error("No serialization allowed!"E_USER_ERROR);
    }

    
/**
     * No cloning allowed
     */
    
public function __clone()
    {
        
trigger_error("No cloning allowed!"E_USER_ERROR);
    }


    
/**
     * Implementing Iterator
     */
    
public function current()
    {
        return 
current(self::$instances);
    }

    public function 
key()
    {
        return 
key(self::$instances);
    }

    public function 
next()
    {
        return 
next(self::$instances);
    }

    public function 
rewind()
    {
        
reset(self::$instances);
    }

    public function 
valid()
    {
        return 
current(self::$instances) !== false;
    }
}