Search code examples
phpdesign-patternsyiiyii-components

what is the purpose of a component (class) in Yii


I do not understand the Component piece used in the Yii FW.
Is there a concrete (real life) example why I should use that?


Solution

  • Framework consists of components. The base class for Yii components is CComponent which is basically the base class of everything in Yii. Components can be loaded "on-the-fly" in code or on initation in config. You can read more about it at Yii Guide

    The real life example. If you want to build a house, you need some type of material for it, so those bricks or logs will be your Components. You can make different types of them, but basically they will sustain your house and give it needed features.

    Here you have an example of Yii Component:

    class Y extends CComponent
    {
        /**
        * Returns the images path on webserver
        * @return string
        */
        public static function getImagesPath()
        {
            return Yii::app()->getBasePath().DIRECTORY_SEPARATOR.'images';
        }
    }
    

    Now i can use this class to check resources used by my application: $y = new Y; $y->stats(); Also, if i create a special CBehavior subclass:

    class YBehavior extends CBehavior {
            /**
             * Shows the statistics of resources used by application
             * @param boolean $return defines if the result should be returned or send to output
             * @return string
             */
            public function stats($return = false)
            {
                $stats = '';
                $db_stats = Yii::app()->db->getStats();
        
                if (is_array($db_stats)) {
                    $stats = 'Requests completed: '.$db_stats[0].' (in '.round($db_stats[1], 5).' sec.)<br />';
                }
        
                $memory = round(Yii::getLogger()->memoryUsage/1024/1024, 3);
                $time = round(Yii::getLogger()->executionTime, 3);
        
                $stats .= 'Memory used: '.$memory.' Mb<br />';
                $stats .= 'Time elapsed: '.$time.' сек.';
        
                if ($return) {
                    return $stats;
                }
        
                echo $stats;
            }
    }
    

    And then apply this behavior to my Component: $y->attachBehavior('ybehavior', new YBehavior); Now i can use the method stats with my Y class: $y->stats()

    This is possible because every subclass of CComponent in Yii gives you a possibility to use behaviors, events, getters and setters and much more.