<?php
/**
 * MiniMVC
 *
 * Convention-based micro-framework for PHP
 *
 * @package		miniMVC
 * @author 		Timothy J. Warren
 * @copyright	Copyright (c) 2011 - 2012
 * @link 		https://github.com/timw4mail/miniMVC
 * @license 	http://philsturgeon.co.uk/code/dbad-license 
 */

// --------------------------------------------------------------------------

/**
 * Base class for the framework
 *
 * @package miniMVC
 * @subpackage System
 */
class miniMVC extends MM {

	use Singleton;

	/**
	 * Constructor - Any classes loaded here become subclasses of miniMVC
	 *
	 * @param array $members
	 */
	public function __construct($members = [])
	{
		// Allow the class to be used like an array
		parent::__construct($members);
	}
	
	// --------------------------------------------------------------------------
	
	/**
	 * Method to load classes into the singleton
	 *
	 * @param string $name
	 * @return object
	 */
	public function load_class($name)
	{
		// In a subdirectory? No problem
		if (strpos("/", $name) !== FALSE)
		{
			$n = explode("/", $name);
			$name = $n[count($n) -1];
		}
		
		// Try system library first, then app library
		$path = MM_SYS_PATH . "libraries/{$name}.php";
		$name = "MM_{$name}";
		
		if ( ! is_file($path))
		{
			$path = MM_APP_PATH . "classes/{$name}.php";
			$name = str_replace('MM_', '', $name);
		}
		
		$class = "{$name}";
		
		// Load the class file if need be
		if ( ! class_exists($class, FALSE))
		{
			if (is_file($path))
			{
				require_once($path);
			}
		}
		
		// Create the object, and add it to the current miniMVC object
		if (class_exists($class, FALSE))
		{
			// Remove MM_ prefix from name
			$name = str_replace('MM_', '', $name);
		
			if ( ! isset($this->$name))
			{
				// Call a singleton, if the get_instance method exists
				if (method_exists($class, 'get_instance'))
				{
					return $this->$name =& $class::get_instance();
				}
			
				return $this->$name = new $class;
			}
		}
	}
	
	// --------------------------------------------------------------------------
	
	/**
	 * Convenience function to remove an object from the singleton
	 *
	 * @param string $name
	 */
	public function unload($name)
	{
		if (isset($this->$name))
		{
			unset($this->$name);
		}
	}
	
	// --------------------------------------------------------------------------
	
	/**
	 * Convenience function to load config files
	 *
	 * @param string $name
	 */
	public function load_config($name)
	{
		$path = MM_APP_PATH . "config/{$name}.php";
	
		if (is_file($path))
		{
			require_once($path);
		}
	}
}

// End of miniMVC.php