栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > PHP

Yii框架学习笔记之应用组件操作示例

PHP 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Yii框架学习笔记之应用组件操作示例

本文实例讲述了Yii框架学习笔记之应用组件操作。分享给大家供大家参考,具体如下:

所有的组件都应声明在config/web.php

//组件声明在该数组下
'components'=>array(
  //自定义组件1 - 函数形式
  'customComponent1' => function(){
    $custom = new appcomponentsCustomComponentrealizationCustomComponent1();
    $custom->setName('谭勇');
    $custom->setAge(22);
    return $custom;
  },
  //自定义组件2 - 数组形式
  'customComponent2' => array(
      'class' => 'appcomponentsCustomComponentrelazationCustomComponent2'
      'name'  => '谭勇',
      'age'  => 22
  ),
  //自定义组件 - 字符串形式
  'customComponent3' => 'appcomponentsCustomComponentrealizationCustomComponent3'
),

如果只是在components 中声明了该组件,那么只有在首次调用的时候才会实例化这个组件,之后调用都会复用之前的实例。 如果你在bootstrap 数组中声明了这个组件,那么该组件会随着应用主体的创建而实例(也就是默认会被实例,而不是首次调用才会实例这个组件)。

//默认加载customComponent1 和 customComponent2 组件
'bootstrap' => array(
  'customComponent1','customComponent2'
),

在应用目录下创建 components 目录

组件 CutomComponent

接口类 appcomponentsCustomComponentCustomComponent;



接口实现类 appcomponentsCustomComponentrealizationCustomComponent1

name = $name;
    }
    public function getName()
    {
      return $this->name;
    }
    public function setAge($age)
    {
      $this->age = $age;
    }
    public function getAge()
    {
      return $this->age;
    }
  }
?>

customComponent2,customComponent3 我们都让他们与customComponent1 具有相同的代码。 那么我们怎么去调用这些组件呢?

namespace appcontrollershome;
use Yii;
use yiiwebController;
class IndexController extends Controller
{
  public function actionIndex()
  {
    //组件customComponent1
    echo Yii::$app->customComponent1->getName();
    //组件customComponent2
    echo Yii::$app->customComponent2->getName();
    //组件customComponent3
    echo Yii::$app->customComponent3->getName();
  }
}

然后回过头看数组形式、函数形式、字符串形式的组件

//函数形式  -  这个很容易理解 实例化后设置属性值
function(){ 
    $custom = new appcomponentsCustomComponentrealizationCustomComponent1();
    $custom->setName('谭勇');
    $custom->setAge(22);
    return $custom;
  },
//数组形式 - 它会实例化这个组件 之后设置属性值 注意这里设置属性值的方法 和 函数不一样,它是 $custom->name = '谭勇' , $custom->age = 22
array(
      'class' => 'appcomponentsCustomComponentrelazationCustomComponent2'
      'name'  => '谭勇',
      'age'  => 22
  ),
//字符串形式 只知道会实例化这个组件,怎么注入属性值,这个不清楚支不支持

组件有什么作用?

如果你理解Java spring mvc 那么就不难理解组件的作用 可以作为服务层,数据访问层等等

更多关于Yii相关内容感兴趣的读者可查看本站专题:《Yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/38678.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号