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 相关文章推荐
Zend公司全球首推PHP认证
Oct 09 PHP
PHP 高手之路(三)
Oct 09 PHP
几种显示数据的方法的比较
Oct 09 PHP
PHP新手上路(十三)
Oct 09 PHP
用php获取远程图片并把它保存到本地的代码
Apr 07 PHP
ie6 动态缩略图不显示的原因
Jun 21 PHP
360通用php防护代码(使用操作详解)
Jun 18 PHP
PHP中使用register_shutdown_function函数截获fatal error示例
Apr 21 PHP
YII2.0之Activeform表单组件用法实例
Jan 09 PHP
php集成动态口令认证
Jul 21 PHP
PHP基于MySQLI函数封装的数据库连接工具类【定义与用法】
Aug 11 PHP
Laravel 中创建 Zip 压缩文件并提供下载的实现方法
Apr 02 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
隐藏X-Space个人空间下方版权方法隐藏X-Space个人空间标题隐藏X-Space个人空间管理版权方法
2007/02/22 PHP
php minixml详解
2008/07/19 PHP
php使用strtotime和date函数判断日期是否有效代码分享
2013/12/25 PHP
Linux系统递归生成目录中文件的md5的方法
2015/06/29 PHP
谈谈从phpinfo中能获取哪些值得注意的信息
2017/03/28 PHP
利用PHP获取访客IP、地区位置、浏览器及来源页面等信息
2017/06/27 PHP
Laravel模型间关系设置分表的方法示例
2018/04/21 PHP
PHP+redis实现的购物车单例类示例
2019/02/02 PHP
javascript 短路法代码精简
2009/08/20 Javascript
jQuery中与toggleClass等价的程序段 以及未来学习的方向
2010/03/18 Javascript
关于可运行代码无法正常执行的使用说明
2010/05/13 Javascript
Javascript获取窗口(容器)的大小及位置参数列举及简要说明
2012/12/09 Javascript
深入理解JavaScript中为什么string可以拥有方法
2016/05/24 Javascript
Vue.js实现网格列表布局转换方法
2017/08/25 Javascript
vue.js使用v-if实现显示与隐藏功能示例
2018/07/06 Javascript
解决element-ui中下拉菜单子选项click事件不触发的问题
2018/08/22 Javascript
vue中使用gojs/jointjs的示例代码
2018/08/24 Javascript
微信小程序中的店铺评分组件及vue中用svg实现的评分显示组件
2018/11/16 Javascript
M2实现Nodejs项目自动部署的方法步骤
2019/05/05 NodeJs
Node.js 中如何收集和解析命令行参数
2021/01/08 Javascript
[04:03]辉夜杯主赛事 12月25日RECAP精彩回顾
2015/12/26 DOTA
[42:23]完美世界DOTA2联赛PWL S3 Forest vs Rebirth 第二场 12.10
2020/12/13 DOTA
python正则表达式面试题解答
2020/04/28 Python
Windows下将Python文件打包成.EXE可执行文件的方法
2018/08/03 Python
python中dict字典的查询键值对 遍历 排序 创建 访问 更新 删除基础操作方法
2018/09/13 Python
使用pytorch完成kaggle猫狗图像识别方式
2020/01/10 Python
MAC平台基于Python Appium环境搭建过程图解
2020/08/13 Python
python编程的核心知识点总结
2021/02/08 Python
几个常见的软件测试问题
2016/09/07 面试题
电气工程及其自动化自我评价四篇
2013/09/24 职场文书
大学生自我评价怎样写好
2013/10/23 职场文书
高二生物教学反思
2014/01/27 职场文书
体育之星事迹材料
2014/05/11 职场文书
汽车运用工程专业求职信
2014/06/18 职场文书
住房租房协议书
2014/08/20 职场文书
2015年法律事务部工作总结
2015/07/27 职场文书