How to write a simple application component

You are viewing revision #3 of this wiki article.
This is the latest version of this article.
You may want to see the changes made in this revision.

« previous (#2)

Application component

An application component is a confortable way for share information among all component of the application

In Yii there are many application components, for example Yii::app()->db.

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, 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, because we do at most only a single query.

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

Revisions

View all history

Related Articles