欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Yii框架模擬組件調(diào)用注入示例

 更新時(shí)間:2019年11月11日 11:13:38   作者:傾聽(tīng)歲月  
這篇文章主要介紹了Yii框架模擬組件調(diào)用注入,結(jié)合實(shí)例形式分析了Yii框架存儲(chǔ)服務(wù)功能組件與調(diào)用相關(guān)操作技巧,需要的朋友可以參考下

本文實(shí)例講述了Yii框架模擬組件調(diào)用注入。分享給大家供大家參考,具體如下:

yii 中組件只有在被調(diào)用的時(shí)候才會(huì)被實(shí)例化,且在當(dāng)前請(qǐng)求中之后調(diào)用該組件只會(huì)使用上一次實(shí)例化的實(shí)例,不會(huì)重新生成該實(shí)例。

'components'  => array(
  '組件調(diào)用名'  =>  '組件調(diào)用命名空間',
  '組件調(diào)用名'  => array(
      'class' => '組件調(diào)用命名空間'
  );
  '組件調(diào)用名'  => function(){
    return new '組件調(diào)用命名空間';
  }
)

一個(gè)類似的小組件,可以實(shí)現(xiàn)上述功能。方便我們存儲(chǔ)服務(wù)功能組件。

<?php
namespace app\components\Services;
/**
 * 自定義服務(wù)層調(diào)用組件
 * 支持 的實(shí)例模式只有yii模式的string 和 array 模式
 * 例子
 * services => array(
 *   'customService' => array(
*        'class' => 'app\components\Custom\Custom',
*        'name' => '我是勇哥'
*      ),
 * )
 */
class Services
{
  private $dataObj = array();
  private $classes = array();
  public function __set($name,$value)
  {
    $this->classes[$name] = $value;
  }
  public function __get($name)
  {
    if(!isset($this->dataObj[$name]) || $this->dataObj[$name] == null)
    {
      $classInfo = $this->classes[$name];
      $this->dataObj[$name] = is_array($classInfo) ? (new $classInfo['class']) : (new $classInfo);
      if(is_array($classInfo))
        foreach($classInfo as $a=>$b)
          if($a != 'class')
            $this->dataObj[$name]->$a = $b;
    }
    return $this->dataObj[$name];
  }
}

web.php

'components'=>array(
  'services' => array(
    'class'  =>  'app\components\Services\Services',
    //自定義服務(wù) custom1
    'custom1Service' => array(
      'class' => 'app\services\Custom1\Custom1',
      //需要注入的屬性值
      'name'  => '我是勇哥',
      'age'  => 22
    ),
    //自定義服務(wù) custom2
    'custom2Service' => array(
      'class' => 'app\services\Custom2\Custom2',
      //需要注入的屬性值
      'name'  => '我是勇哥',
      'age'  => 22
    ),
  )
)

控制層調(diào)用

<?php
namespace app\controllers\home;
use Yii;
use yii\web\Controller;
class IndexController extends Controller
{
  public function actionIndex()
  {
    echo Yii::$app->services->custom1Service->name;
  }
}

更多關(guān)于Yii相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Yii框架入門(mén)及常用技巧總結(jié)》、《php優(yōu)秀開(kāi)發(fā)框架總結(jié)》、《smarty模板入門(mén)基礎(chǔ)教程》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門(mén)教程》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫(kù)操作入門(mén)教程》及《php常見(jiàn)數(shù)據(jù)庫(kù)操作技巧匯總

希望本文所述對(duì)大家基于Yii框架的PHP程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論