Difference between #3 and #2 of How to write a simple application component

changed
Title
Singleton in YiiHow to write a simple application
component
unchanged
Category
How-tos
changed
Tags
pattern singletonapplication component
changed
Content
SingletonApplication component
------------------

SingletonAn application component is a desing pattern
that is very useful when exactly one object is needed to coordinate actions
acrossconfortable way for share information among all component
of the system.application

In Yii there are many implementation of this pattern,application
components, 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,CApplicationComponent, like that:


~~~
[php]
<?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:

~~~
[php]
	'components'=>array(
		'region'=>array('class'=>'RegionSingleton'),
         ...
        )

~~~

### Usage

Now, wherever in the application we can call 

~~~
[php]
Yii::app()->region->model
~~~
 for have the model, or also  

~~~
[php]
Yii::app()->region->id 
~~~
for retrive the id.

We can also set the model by using 

~~~
[php]
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.because we do at most only a single query.


Write new article