<?php

/**
 * 所在文件是Container.php
 */

/**
 * 提供全局的对象比如$db,$mc等，实现单例。
 *
 * @author Administrator
 */
class Container {
    /**
     * 
     * @var Container 自身对象实例
     */
    private static $instance;
    
    /**
     *
     * @var array services
     */
    private $objects = array();

    
    /**
     *  构造函数
     * @return \Container
     */
    private function __construct() {
        return $this;
    }
    
    /**
     * 返回自身的实例
     * @return \Container
     */
    public static function getInstance() {  
        if (!self::$instance) {  
            self::$instance = new self();  
        }  
        return self::$instance;  
    } 

    /**
     * 添加一个服务
     * @param type $name
     * @param type $object
     * @return null
     */
    public function set($name,$object) {
        if(array_key_exists($name, $this->objects)) {
            return null;
        }else {
            $this->objects[$name] = $object;
        }
    }

    /**
     * 获得一个服务
     * @param type $name
     * @return null
     */
    public function get($name) {
        if(array_key_exists($name, $this->objects)) {
            return $this->objects[$name];
        } else {
            return null;
        }
    }
    
    /**
     * 当调用getDb()等方法时调用该函数
     * @param type $name
     * @param type $arguments
     * @return null
     */
    public function __call($name, $arguments) {
        if(substr($name, 0, 3) =='get') {
            $sname = substr($name, 3);
            $sname{0} = strtolower($sname{0});
            return $this->get($sname);
        } else {
            return null;
        }
    }

	public function __destruct()
    {
        if(is_object($this->objects['db']))
        {
            $this->objects['db']->close();
        }

		if(is_object($this->objects['dbback']))
        {
            $this->objects['dbback']->close();
        }
    }
}

?>
