Yii框架自定义数据库操作组件示例(2)

<?php
namespace app\components\DbOper\realization;
use Yii;
use app\components\DbOper\DbOper;
/**
 * 自定义数据库操作组件实现类
 */
class DbRealization1 implements DbOper
{
  private $db = null;
  /**
   * interface @Override
   */
  public function fetchAll($sql='',$keyVal=array())
  {
    if($sql === '')
      return array();
    $result = $this->getQueryObj($sql,$keyVal)->queryAll();
    if($result)
      return $result;
    else
      return array();
  }
  /**
   * interface @Override
   */
  public function fetch($sql='',$keyVal=array())
  {
    if($sql === '')
      return array();
    $result = $this->getQueryObj($sql,$keyVal)->queryOne();
    if($result)
      return $result;
    else
      return array();
  }
  /**
   * interface @Override
   */
  public function insert($tableName='',$values=array())
  {
    if($tableName === '')
      return 0;
    $insert = $this->getYiiDbConnection()->createCommand();
    if(is_array($values[0]))
    {
      $keys = array_keys($values[0]);
      return $insert->batchInsert($tableName,$keys,$values)->execute();
    }
    return $insert->insert($tableName,$values)->execute();
  }
  /**
   * interface @Override
   */
  public function update($tableName='',$where = '',$update=array())
  {
    if($tableName === '')
      return 0;
    if($where === '')
      return 0;
    return $this->getYiiDbConnection()
        ->createCommand()
        ->update($tableName,$update,$where)
        ->execute();
  }
  /**
   * interface @Override
   */
  public function delete($tableName='',$where='')
  {
    if($tableName === '')
      return 0;
    return $this->getYiiDbConnection()
        ->createCommand()
        ->delete($tableName,$where)
        ->execute();
  }
  /**
   * 获得查询操作对象
   * @return 
   * Object 
   */
  private function getQueryObj($sql='',$keyVal=array())
  {
    $query = $this->getYiiDbConnection()->createCommand($sql);
    if(!empty($keyVal))
      $query->bindValues($keyVal);
    return $query;
  }
  /**
   * interface @Override
   */
  public function transcation($sqls = array())
  {
    if(empty($sqls))
      return false;
    $db = $this->getYiiDbConnection();
    $outerTransaction = $db->beginTransaction();
    $runClient = true;
    try
    {
      foreach($sqls as $sql)
      {
        $db->createCommand($sql)->execute();
      }
      $outerTransaction->commit();
    }catch(\Exception $e){
      $runClient = false;
      $outerTransaction->rollback();
    }
    return $runClient;
  }
  /**
   * interface @Override
   */
  public function getYiiDbConnection()
  {
    if($this->db === null)
    {
      $this->db = Yii::$app->db;
    }
    return $this->db;
  }
}

注意:我的自定义数据库操作类 依赖 Yii::$app->db 这个组件, 也就是框架自带的数据库连接组件

然后我们就可以通过 Yii::$app->dbOper 去操作数据库了。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/4053.html