How to write a simple application component

11 followers

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.

Total 4 comments

#8408 report it
ianaré at 2012/05/31 07:48pm
De Facto Singleton

Since there can be only one instance of an application component per CWebApplication, it acts like a singleton, even if not stored in a static property.

#3889 report it
_wk_ at 2011/05/17 07:21pm
Not Registry either

I don't believe this is the Registry pattern either. To my knowledge a Registry pattern is form of singleton that controls storage of values inside it. A value can be set but not unset. See the Zend_Registry component as a reference.

#3888 report it
_wk_ at 2011/05/17 07:17pm
Incorrect pattern

A singleton will have a protected or private constructor with a static method that will return a single instance of the object. This is limits to one object being created hence the name 'Singleton'.

#3769 report it
mitallast at 2011/05/06 07:33am
It is not singleton

It is not singleton. This pattern name is Registry, using for dependency injection in your application.

Leave a comment

Please to leave your comment.

Write new article