yii 自定义组件的调用

时间:2022-02-11 23:05:25

1,main.php 里面导入

'import' => array(
            'application.components.*'
        ),

2,application/components/BaseComponent.php

<?php
/**
 * 基础组件
 */
class BaseComponent extends CComponent
{
    public function init()
    {
    }
}

3,application/components/TestComponent.php

<?php
class TestComponent extends BaseComponent {
    public $title = 'aaxx';
    private $_url = 'ccdd';
//这里的get方法和set方法写了之后就可以直接调用私有属性!如果不允许直接调用则去掉这两个方法
    public function setUrl($value='') {
        $this->_url = $value;
    }
    public function getUrl() {
        return $this->_url ;
        }
        
    public function test()
    {
        return 'test';
    }

}

4,application/components/Controller.php

class Controller extends CController
{

public function init()
    {
        header('Content-type:text/html;charset=utf-8');

  }

/**
     * __get()
     * @see CComponent::__get()
     */
    public function __get($name)
    {
         if(substr(strtolower($name), -4) == 'comp') {
             return $this->getComponent($name);
         } else if(isset($this->default_tpl_vars[$name])) {
             return $this->default_tpl_vars[$name];
         }
         return parent::__get($name);
    }
    /**
     * @desc 获取组件
     * @author lijianwei
     */
    public function getComponent($name)
    {
       $name = strtolower($name);
       $component_id = substr($name, 0, -4);
       $component_class_name = ucfirst($component_id). 'Component';
       
       if(Yii::app()->hasComponent($component_id)) {
           return Yii::app()->getComponent($component_id);
       } else {
           Yii::app()->setComponent($component_id, array('class' => $component_class_name));
           return Yii::app()->getComponent($component_id);
       }
    }

}

5,控制器调用application/Controllers/HomeController.php

class HomeController extends Controller
{

public function actionIndex()
    {

    $b = $this->testComp->url='ddd';//因为有set方法,给组件私有变量赋值不报错
        echo $b;
        echo $this->testComp->test();

  }

}