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

changed
Title
How to write a simple application componentSingleton in
Yii
unchanged
Category
How-tos
changed
Tags
application componentpattern singleton
changed
Content
Application componentSingleton
------------------

An application componentSingleton is a confortable
way for share information among all component ofdesing pattern that
is very useful when exactly one object is needed to coordinate actions
across the applicationsystem.

In Yii there are many application components,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
CApplicationComponent,CApplicationCompoment, 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, because we do at most
only a single query.but is better to avoid to as it introduces global
state into an application, and that can lead to bad practices.


Write new article