zoukankan      html  css  js  c++  java
  • yii 自定义组件的调用

    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();

      }

    }

  • 相关阅读:
    jdk8:垃圾收集器
    Young GC和Full GC分别在什么情况下会发生?
    GC之Minor/Young/Major GC的区别
    Java的JJWT实现JWT
    什么是 JWT -- JSON WEB TOKEN
    Spring的两种动态代理:Jdk和Cglib 的区别和实现
    java对象结构 对象头 Markword
    偏向锁跟可重入性有什么区别
    C# 加密算法[汇总]
    Java语言:JAVA8 十大新特性详解(zz)
  • 原文地址:https://www.cnblogs.com/jami918/p/3483869.html
Copyright © 2011-2022 走看看