joomla是一个很优秀的CMS系统,个人觉得是很优秀的一个系统。在这个系统引入了很多的设计模式。其中最常见的就是单件模式了。

 在joomla中一个最明显的地方就是使用数据库。只要你需要数据库,那么你就可以使用下面的代码来获得数据库:

$db = JFactory::getDBO();

非常的方便,只要你需要就可以使用。不用担心说创建了很多个对象,内存没有释放。如果查看一下joomla的源码 :libraries\joomla\factory.php中会看到下面的部分:

	/**
	 * Get a database object.
	 *
	 * Returns the global {@link JDatabase} object, only creating it if it doesn't already exist.
	 *
	 * @return  JDatabase object
	 *
	 * @see     JDatabase
	 * @since   11.1
	 */
	public static function getDbo()
	{
		if (!self::$database)
		{
			//get the debug configuration setting
			$conf = self::getConfig();
			$debug = $conf->get('debug');

			self::$database = self::createDbo();
			self::$database->setDebug($debug);
		}

		return self::$database;
	}

 上面是getDbo()的实现,很明显,他是一个静态的方法,这个方法首先判断$database是否有值,如果有就直接返回,如果没有就创建。它能够保证整个程序中只有一个$database实例。我们看一下self::createDbo()的实现

/**
	 * Create an database object
	 *
	 * @return  JDatabase object
	 *
	 * @see     JDatabase
	 * @since   11.1
	 */
	protected static function createDbo()
	{
		jimport('joomla.database.table');

		$conf = self::getConfig();

		$host = $conf->get('host');
		$user = $conf->get('user');
		$password = $conf->get('password');
		$database = $conf->get('db');
		$prefix = $conf->get('dbprefix');
		$driver = $conf->get('dbtype');
		$debug = $conf->get('debug');

		$options = array('driver' => $driver, 'host' => $host, 'user' => $user, 'password' => $password, 'database' => $database, 'prefix' => $prefix);

		$db = JDatabase::getInstance($options);

		if ($db instanceof Exception)
		{
			if (!headers_sent())
			{
				header('HTTP/1.1 500 Internal Server Error');
			}
			jexit('Database Error: ' . (string) $db);
		}

		if ($db->getErrorNum() > 0)
		{
			die(sprintf('Database connection error (%d): %s', $db->getErrorNum(), $db->getErrorMsg()));
		}

		$db->setDebug($debug);

		return $db;
	}

 本来以为这是单件模式,但仔细想想,这个并不符合单件模式。

单件模式要完成的任务就是保证整个程序中只出现一个实例。可以做到延迟实例化。

实 现单件模式的一个简单的方法是:提供一个受保护的构造函数,这样外界就不能够通过构造函数来实例化对象了。然后提供一个静态的成员变量,这个静态的成员变 量用来保存类的实例。提供一个静态的getInstance方法,在这个方法中通过判断成员变量是否有值,来决定是否实例化。如果有值,就直接返回,否则 调用对象,进行实例化。

下面是一段简单的代码:

 

 



收藏
0个人 收藏

关注Joomla中国微信公众号,随时获得最新的Joomla新闻资讯!