简体   繁体   English

Yii中的组件(类)的目的是什么

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

I do not understand the Component piece used in the Yii FW. 我不了解Yii FW中使用的零部件
Is there a concrete (real life) example 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. Yii组件的基类是CComponent,它基本上是Yii中所有内容的基类。 Components can be loaded "on-the-fly" in code or on initation in config. 可以通过代码或在配置中初始化时“即时”加载组件。 You can read more about it at Yii Guide 您可以在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: 这里有一个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(); 现在,我可以使用此类检查应用程序使用的资源: $y = new Y; $y->stats(); $y = new Y; $y->stats(); Also, if i create a special CBehavior subclass: 另外,如果我创建一个特殊的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;
        }
}

And then apply this behavior to my Component: $y->attachBehavior('ybehavior', new YBehavior); 然后将此行为应用于我的组件: $y->attachBehavior('ybehavior', new YBehavior); Now i can use the method stats with my Y class: $y->stats() 现在我可以在我的Y类中使用stats方法: $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. 这是可能的,因为Yii中CComponent的每个子类都使您可以使用行为,事件,getter和setter等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM