Singleton in Yii

You are viewing revision #2 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#3) »

Singleton

Singleton is a desing pattern that is very useful when exactly one object is needed to coordinate actions across the system.

In Yii there are many implementation of this pattern, for example Yii::app()->db.

In this article we will learn how to create a singleton.

Creating the class

Let's imagine we need almost everywhere an instance of the class Region, and we want to avoid to do too much queries.

We can create a class which extends CApplicationCompoment, like that:

<?php 

class RegionSingleton extends CApplicationComponent
{
	private $_model=null;
	
	
	public function setModel($id)
	{
		$this->_model=Region::model()->findByPk($id);
	}
	
	public function getModel()
	{
		if (!$this->_model)
		{
			if (isset($_GET['region']))
				$this->_model=Region::model()->findByAttributes(array('url_name'=> $_GET['region']));
			else
				$this->_model=Region::model()->find();
		}
		return $this->_model;
	}
	
	public function getId()
	{
		return $this->model->id;
	}
	
	public function getName()
	{
		return $this->model->name;
	}
}

And include this class in config main:

'components'=>array(
		'region'=>array('class'=>'RegionSingleton'),
         ...
        )

Usage

Now, wherever in the application we can call

Yii::app()->region->model

for have the model, or also

Yii::app()->region->id 

for retrive the id.

We can also set the model by using

Yii::app()->region->setModel($id)
Conclusion

This approach can be very useful and resource-saving, but is better to avoid to as it introduces global state into an application, and that can lead to bad practices.

15 7
14 followers
Viewed: 74 591 times
Version: Unknown (update)
Category: How-tos
Written by: zaccaria
Last updated by: zaccaria
Created on: May 6, 2011
Last updated: 12 years ago
Update Article

Revisions

View all history

Related Articles