<?php
/**
* JThing Factory
*@author bibby
*$Id$

This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the
use of this software. It may be freely modified and redistributed, even in commercial applications.
** //*/
require_once('JThing.class.php');

class 
JFac
{
    public static 
$cache = array();
    public static 
$classes = array();
    public static 
$requested = array();
    
    function &
get($type,$id=false)
    {
        
$hash $type."_".$id;
        if(
self::$cache[$hash])
            return 
self::$cache[$hash];
        
        return 
self::cache( new JThing($type,$id) );
    }
    
    
/*** getObj
    converts a JThing json object into a php object
    @param    stdClass    JThing type thing
    @return    Object
    */
    
function getObj($clsobj)
    {
        
// bail if a bad argument
        
if(!is_object($clsobj))
            return 
false;
            
        
$hash self::hash($clsobj);
        
        
// if this object has been requested before, give it back.
        // this allows circular references primarily
        
if( is_objectself::$requested[$hash] ) )
            return 
self::$requested[$hash];
        
        
// flag that an object has been requested
        
self::$requested[$hash]=true;
        
        
// if we've cached the object already, send that.
        
if(is_a($clsobj,SPECIAL_CLASS) && self::$cache[$hash])
            return 
self::$cache[$hash];
        
        
// require the class file
        
$t $clsobj->{SPECIAL_CLASS};
        
self::requireFile($t);
        
        
// cache the new object
        
$obj self::cache( new $t($clsobj->type,$clsobj->id) );
        
        
// reference it in the "requested" cache
        
if( self::$requested[$hash] === true)
            
self::$requested[$hash] = $obj;
        
        return 
$obj
    }
    
    
/**
    a unique-ish id
    @param    object    usually the stdClass type
    @return    string
    */
    
function hash($obj)
    {
        return 
$obj->type."_".$obj->id;
    }
    
    
/**
    craete a reference
    @param    object    to cache
    @return same object
    */
    
function cache($obj)
    {
        
self::$cache[self::hash($obj)]=$obj;
        return 
$obj;
    }
    
    
## TODO
    
    /*** loadSession ***
    @access
    @param
    @return
    */
    
function loadSession()
    {
        
    }
    
    
/*** requireFile ***
    @access
    @param
    @return
    */
    
function requireFile($className)
    {
         if(
self::$classes[$className])
             return;
             
         require_once(
"$className.class.php");
         
self::$classes[$className]=true;
    }
}
?>