How to create a new component

1 What is a component?

Yii applications are built upon components which are objects written to a specification.

A component is an instance of CComponent or its derived class. Using a component mainly involves accessing its properties and raising/handling its events. The base class CComponent specifies how to define properties and events.

2 Component Property

A component property is like an object’s public member variable. We can read its value or assign a value to it.

For example,


// get the textWidth property
$width=$component->textWidth;
// set the enableCaching property
$component->enableCaching=true;

To define a component property, we can simply declare a public member variable in the component class. A more flexible way, however, is by defining getter and setter methods like the following:


public function getTextWidth()
{
    return $this->_textWidth;
}

public function setTextWidth($value)
{
    $this->_textWidth=$value;
}

The above code defines a writable property named textWidth (the name is case-insensitive). When reading the property, getTextWidth() is invoked and its returned value becomes the property value; Similarly, when writing the property, setTextWidth() is invoked. If the setter method is not defined, the property would be read-only and writing it would throw an exception.

Using getter and setter methods to define a property has the benefit that additional logic (e.g. performing validation, raising events) can be executed when reading and writing the property.

3 Component Event

Component events are special properties that take methods (called event handlers) as their values. Attaching (assigning) a method to an event will cause the method to be invoked automatically at the places where the event is raised.

Therefore, the behavior of a component can be modified in a way that may not be foreseen during the development of the component.

A component event is defined by defining a method whose name starts with on. Like property names defined via getter/setter methods, event names are case-insensitive.

The following code defines an onClicked event:


public function onClicked($event)
{
    $this->raiseEvent('onClicked', $event);
}

where $event is an instance of CEvent or its child class representing the event parameter.

We can attach a method to this event as follows:


$component->onClicked=$callback;

where $callback refers to a valid PHP callback. It can be a global function or a class method. If the latter, the callback must be given as an array: array($object,‘methodName’).

The signature of an event handler must be as follows:


function methodName($event)
{
    ......
}

where $event is the parameter describing the event (it originates from the raiseEvent() call).

The $event parameter is an instance of CEvent or its derived class. At the minimum, it contains the information about who raises the event.

An event handler can also be an anonymous function which is supported by PHP 5.3 or above. For example,


$component->onClicked=function($event) {
    ......
}

If we call onClicked() now, the onClicked event will be raised (inside onClicked()), and the attached event handler will be invoked automatically.

An event can be attached with multiple handlers. When the event is raised, the handlers will be invoked in the order that they are attached to the event. If a handler decides to prevent the rest handlers from being invoked, it can set “$event→handled”:http://www.yiiframework.com/doc/api/1.1/CEvent#handled to be true.

4 Usage of components

In YII components represent database connection, session, JavaScript and CSS compressor, Gentics Content Connector API etc.

Any component can be initialised in any php class or file.

But for better performance components which are used extensible should be initialised in config files and used as properties of singleton object Yii::app.

By configuring the components property of the application instance, we can customize the class and property values of any application component used.

For example, we can configure the DbConnectionMan component, like this:


'components' => array(
   ...........................................................
        //Component manager of database connections
        'db' => array(
            //Db component class
            'class' => 'DbConnectionMan',
            //DB connection string
            'connectionString' => 'mysql:host=localhost;dbname=gportal',
            //whether to turn on prepare emulation. Defaults to false, meaning PDO will use the native prepare support if available.
            'emulatePrepare' => true,
            //the default prefix for table names. Defaults to null, meaning no table prefix.
            'tablePrefix' => 'gportal_',
            //DB username
            'username' => 'root',
            //DB Password
            'password' => 'root',
            'charset' => 'utf8',
            //whether the database connection should be automatically established the component is being initialized.
            'autoConnect' => false,
            //whether to enable profiling the SQL statements being executed. This should be mainly enabled and used during development
            //to find out the bottleneck of SQL executions.
            'enableProfiling' => true,
            //whether to log the values that are bound to a prepare SQL statement
            'enableParamLogging' => true,
            //number of seconds that table metadata can remain valid in cache. 86400, 0 - disabled
            'schemaCachingDuration' => 0,
            //Read write splitting function is swithable.You can specify this value to false to disable it.
            'enableSlave' => false,
            //slave connection config is same as CDbConnection
            'slaves' => array(

            ),
        ),
   ...........................................................

To access an application component, use Yii::app()→ComponentID, where ComponentID refers to the ID of the component (e.g. Yii::app()→db).

Example of accessing db component,


    $connection = Yii::app()->db;
    $command = $connection->createCommand();

An application component may be disabled by setting enabled to false in its configuration. Null is returned when we access a disabled component.

By default, application components are created on demand. This means an application component may not be created at all if it is not accessed during a user request. As a result, the overall performance may not be degraded even if an application is configured with many components. Some application components (e.g. CLogRouter) may need to be created regardless of whether they are accessed or not. To do so, list their IDs in the preload application property.

You can read here to get more information about basic YII component.

5 Gentics Portal.Node PHP components

Gentics Portal.Node PHP has a set of specific components for specific purposes: