Yii中组件(类)的用途是什么

Ita*_*vka 1 php design-patterns yii yii-components

我不明白Yii FW中使用的组件.
是否有一个具体的(现实生活)例子,为什么我应该使用它?

Joh*_*tan 5

框架由组件组成.Yii组件的基类是CComponent,它基本上是Yii中所有内容的基类.组件可以在代码中或在config中的初始化中"即时"加载.您可以在Yii Guide上阅读更多相关信息

现实生活中的例子.如果你想建造房屋,你需要一些类型的材料,所以那些砖或日志将是你的组件.你可以制作不同类型的它们,但基本上它们将支撑你的房子并提供它所需要的功能.

这里有一个Yii组件的例子:

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

现在我可以使用这个类来检查我的应用程序使用的资源:$y = new Y; $y->stats(); 另外,如果我创建一个特殊的CBehavior子类:

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;
        }
}
Run Code Online (Sandbox Code Playgroud)

然后将此行为应用于我的组件:$y->attachBehavior('ybehavior', new YBehavior); 现在我可以将方法统计信息与我的Y类一起使用: $y->stats()

这是可能的,因为Yii中CComponent的每个子类都为您提供了使用行为,事件,getter和setter等的可能性.