Yaf框架封装的MySQL数据库操作示例


Posted in PHP onMarch 06, 2019

本文实例讲述了Yaf框架封装的MySQL数据库操作。分享给大家供大家参考,具体如下:

Yaf封装DB简单操作

介绍

因为Yaf是一个纯天然的MVC阔架,本人还在贝锐的时候就和主管一起用Yaf框架去重构了向日葵的网站端,到后面,Yaf也逐渐应用到了其他项目上,但是Yaf是没有带DB类库的,所以本人也共享下最近封装的代码!

代码

使用PDO封装MySQL操作

class Db_Mysql
{
  private $_options = array();
  private $db;
  private $statement;
  private $_fetchMode = 2;
  /**
   * 构造函数
   *
   * @param string $host
   * @param string $username
   * @param string $password
   * @param string $dbname
   * @param string $charset
   */
  private function __construct($host, $username, $password, $dbname, $charset)
  {
    //初始化数据连接
    try {
      $dns = 'mysql:dbname=' . $dbname . ';host=' . $host;
      $this->db = new PDO($dns, $username, $password, array(PDO::ATTR_PERSISTENT => true, PDO::ATTR_AUTOCOMMIT => 1));
      $this->db->query('SET NAMES ' . $charset);
    } catch (PDOException $e) {
      echo header("Content-type: text/html; charset=utf-8");
      echo '<pre />';
      echo '<b>Connection failed:</b>' . $e->getMessage();
      die;
    }
  }
  /**
   * 调用初始化MYSQL连接
   *
   * @param string $config
   * @return Aomp_Db_Mysql
   */
  static public function getInstance($config = '')
  {
    $host = $config->host;
    $username = $config->username;
    $password = $config->password;
    $dbname = $config->dbname;
    $charset = $config->charset;
    $db = new self($host, $username, $password, $dbname, $charset);
    return $db;
  }
  /**
   * 获取多条数据
   *
   * @param string $sql
   * @param array $bind
   * @param string $fetchMode
   * @return multitype:
   */
  public function fetchAll($sql, $bind = array(), $fetchMode = null)
  {
    if($fetchMode === NULL){
      $fetchMode = $this->_fetchMode;
    }
    $stmt = $this->query($sql, $bind);
    $res = $stmt->fetchAll($fetchMode);
    return $res;
  }
  /**
   * 获取单条数据
   *
   * @param string $sql
   * @param array $bind
   * @param string $fetchMode
   * @return mixed
   */
  public function fetchRow($sql, array $bind = array(), $fetchMode = null)
  {
    if ($fetchMode === null) {
      $fetchMode = $this->_fetchMode;
    }
    $stmt = $this->query($sql, $bind);
    $result = $stmt->fetch($fetchMode);
    return $result;
  }
  /**
   * 获取统计或者ID
   *
   * @param string $sql
   * @param array $bind
   * @return string
   */
  public function fetchOne($sql, array $bind = array())
  {
    $stmt = $this->query($sql, $bind);
    $res = $stmt->fetchColumn(0);
    return $res;
  }
  /**
   * 增加
   *
   * @param string $table
   * @param array $bind
   * @return number
   */
  public function insert($table, array $bind)
  {
    $cols = array();
    $vals = array();
    foreach ($bind as $k => $v) {
      $cols[] = '`' . $k . '`';
      $vals[] = ':' . $k;
      unset($bind[$k]);
      $bind[':' . $k] = $v;
    }
    $sql = 'INSERT INTO '
      . $table
      . ' (' . implode(',', $cols) . ') '
      . 'VALUES (' . implode(',', $vals) . ')';
    $stmt = $this->query($sql, $bind);
    $res = $stmt->rowCount();
    return $res;
  }
  /**
   * 删除
   *
   * @param string $table
   * @param string $where
   * @return boolean
   */
  public function delete($table, $where = '')
  {
    $where = $this->_whereExpr($where);
    $sql = 'DELETE FROM '
      . $table
      . ($where ? ' WHERE ' .$where : '');
    $stmt = $this->query($sql);
    $res = $stmt->rowCount();
    return $res;
  }
  /**
   * 修改
   *
   * @param string $table
   * @param array $bind
   * @param string $where
   * @return boolean
   */
  public function update($table, array $bind, $where = '')
  {
    $set = array();
    foreach ($bind as $k => $v) {
      $bind[':' . $k] = $v;
      $v = ':' . $k;
      $set[] = $k . ' = ' . $v;
      unset($bind[$k]);
    }
    $where = $this->_whereExpr($where);
    $sql = 'UPDATE '
      . $table
      . ' SET ' . implode(',', $set)
      . (($where) ? ' WHERE ' . $where : '');
    $stmt = $this->query($sql, $bind);
    $res = $stmt->rowCount();
    return $res;
  }
  /**
   * 获取新增ID
   *
   * @param string $tableName
   * @param string $primaryKey
   * @return string
   */
  public function lastInsertId()
  {
    return (string) $this->db->lastInsertId();
  }
  public function query($sql, $bind = array())
  {
    if(!is_array($bind)){
      $bind = array($bind);
    }
    $stmt = $this->prepare($sql);
    $stmt->execute($bind);
    $stmt->setFetchMode($this->_fetchMode);
    return $stmt;
  }
  public function prepare($sql = '')
  {
    if(empty($sql)){
      return false;
    }
    $this->statement = $this->db->prepare($sql);
    return $this->statement;
  }
  public function execute($param = '')
  {
    if(is_array($param)){
      try {
        return $this->statement->execute($param);
      } catch (Exception $e) {
        return $e->getMessage();
      }
    }else {
      try {
        return $this->statement->execute();
      } catch (Exception $e) {
        return $e->getMessage();
      }
    }
  }
  /**
   *
   * @param string $where
   * @return null|string
   */
  protected function _whereExpr($where)
  {
    if(empty($where)){
      return $where;
    }
    if(!is_array($where)){
      $where = array($where);
    }
    $where = implode(' AND ', $where);
    return $where;
  }
  /**
   * 关闭数据库操作
   */
  public function close()
  {
    $this->_db = null;
  }
}

配置

db.type = 'mysql'
db.host = '127.0.0.1'
db.username = 'root'
db.password = '123456'
db.dbname = 'test'
db.charset = 'UTF8'

调用方法

class TestController extends Yaf_Controller_Abstract
{
  public function indexAction()
  {
    $config = Yaf_Application::app()->getConfig()->db;
    $db = Db_Mysql::getInstance($config);
    $row = $db->fetchOne('select count(*) from `user`');
    print_r($row);die;
  }
}

结果

Yaf框架封装的MySQL数据库操作示例

希望本文所述对大家PHP程序设计有所帮助。

PHP 相关文章推荐
php 购物车实例(申精)
May 11 PHP
需要发散思维学习PHP
Jun 29 PHP
linux iconv方法的使用
Oct 01 PHP
使用Apache的htaccess防止图片被盗链的解决方法
Apr 27 PHP
IIS+fastcgi下PHP运行超时问题的解决办法详解
Jun 20 PHP
php页面缓存方法小结
Jan 10 PHP
php mongodb操作类 带几个简单的例子
Aug 25 PHP
分享PHP-pcntl 实现多进程代码
Sep 30 PHP
ThinkPHP框架分布式数据库连接方法详解
Mar 14 PHP
php中文乱码问题的终极解决方案汇总
Aug 01 PHP
PHP对象的浅复制与深复制的实例详解
Oct 26 PHP
php实现生成带二维码图片并强制下载功能
Feb 24 PHP
PHP实现的敏感词过滤方法示例
Mar 06 #PHP
详解PHP 二维数组排序保持键名不变
Mar 06 #PHP
PHP获取ttf格式文件字体名的方法示例
Mar 06 #PHP
php ajax confirm 删除实例详解
Mar 06 #PHP
详解PHP多个进程配合redis的有序集合实现大文件去重
Mar 06 #PHP
一次因composer错误使用引发的问题与解决
Mar 06 #PHP
利用PHP如何统计Nginx日志的User Agent数据
Mar 06 #PHP
You might like
php检测useragent版本示例
2014/03/24 PHP
PHP正则验证Email的方法
2015/06/15 PHP
thinkphp5.1框架容器与依赖注入实例分析
2019/07/23 PHP
javascript 学习之旅 (2)
2009/02/05 Javascript
Jquery getJSON方法详细分析
2013/12/26 Javascript
在Google 地图上实现做的标记相连接
2015/01/05 Javascript
Javascript实现的SHA-256加密算法完整实例
2016/02/02 Javascript
js 自带的sort() 方法全面了解
2016/08/16 Javascript
基于JavaScript实现鼠标箭头移动图片跟着移动
2016/08/30 Javascript
jquery使用EasyUI Tree异步加载JSON数据(生成树)
2017/02/11 Javascript
微信小程序实战之自定义模态弹窗(8)
2017/04/18 Javascript
vue实现全选、反选功能
2020/11/17 Javascript
Python实现读取邮箱中的邮件功能示例【含文本及附件】
2017/08/05 Python
Python 3实战爬虫之爬取京东图书的图片详解
2017/10/09 Python
Python脚本完成post接口测试的实例
2018/12/17 Python
Python3.5实现的三级菜单功能示例
2019/03/25 Python
Python PyCharm如何进行断点调试
2019/07/05 Python
弄懂这56个Python使用技巧(轻松掌握Python高效开发)
2019/09/18 Python
tensorflow 实现打印pb模型的所有节点
2020/01/23 Python
Window10上Tensorflow的安装(CPU和GPU版本)
2020/12/15 Python
css3实现波纹特效、H5实现动态波浪效果
2018/01/31 HTML / CSS
We Fashion荷兰:一家国际时装公司
2018/04/18 全球购物
SISLEY希思黎官方旗舰店:享誉全球的奢华植物美容品牌
2018/04/25 全球购物
Brother加拿大官网:打印机、贴标机、缝纫机
2019/10/09 全球购物
小学教育毕业生自荐信
2013/11/18 职场文书
餐饮加盟计划书
2014/01/10 职场文书
经贸日语专业个人求职信范文
2014/04/29 职场文书
"9.18"国耻日演讲稿范文
2014/09/14 职场文书
党的群众路线教育实践活动对照检查材料范文
2014/09/24 职场文书
2015年社区文体活动总结
2015/03/25 职场文书
毕业论文答辩稿范文
2015/06/23 职场文书
2015国庆节宣传语
2015/07/14 职场文书
开业庆典嘉宾致辞
2015/08/01 职场文书
Vue+Element UI实现概要小弹窗的全过程
2021/05/30 Vue.js
如何用Python搭建gRPC服务
2021/06/30 Python
Java 泛型详解(超详细的java泛型方法解析)
2021/07/02 Java/Android