开发者

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) exam开发者_如何转开发ple why I should use that?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜