当前位置: 首页 > 编程文章 >

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

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

作者:许知时间:2025-03-28 16:16:20浏览:159

Yaf作为纯天然的MVC框架,原生并未提供DB类库。本文分享了在重构项目过程中封装的基于PDO的MySQL数据库操作代码。通过单例模式管理连接,支持配置化初始化,并提供了查询、插入等基础方法,旨在为使用Yaf进行PHP开发的人员提供参考。

本文目录收起

Yaf框架下MySQL数据库操作封装概述

以下实例展示了在Yaf框架中对MySQL数据库操作的封装实现,供开发者参考与借鉴。

Yaf环境下DB简单操作封装

背景介绍

鉴于Yaf具备纯天然的MVC架构特性,笔者曾在贝锐工作期间与主管利用该框架完成了向日葵网站端的重构工作。随后,Yaf也被推广至其他项目中应用。然而,由于Yaf本身未内置数据库类库,因此这里分享近期封装的相关代码。

核心代码实现

基于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 '
'; echo 'Connection failed:' . $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;
  }
}

执行结果展示

期望上述内容能对各位PHP程序开发人员有所助益。

上一篇
Windows 7下PHP开发环境安装配置图文方法

本文介绍在Windows 7 Ultimate系统下搭建包含IIS 6.1、MySQL 5.0.67及PHP 5.2.13的开发环境。通过启用IIS的CGI功能并配置FastCGI,成功实现PHP运行,并通过输出hello world验证环境可用性。同时对比了EditPlus与Zend Studio等开发工具的使用体验。

下一篇
React框架入门:组件、JSX与生命周期详解

本文介绍Facebook开发的React框架,通过虚拟DOM实现高效渲染。文章详细解析了组件的创建、JSX语法的使用、属性与状态的管理,以及组件从挂载到卸载的生命周期函数,帮助开发者快速掌握React核心概念。

相关文章

更多
PHP PDO 处理 SQLSTATE 23000:区分重复键与必填值缺失

在 PHP 使用 PDO MySQL 进行批量导入时,SQLSTATE 23000 既可能由唯一键重复(如 MySQL 1062)引起,也可能因必填字段为 NULL(如 MySQL 1048)触发。仅依赖 SQLSTATE 无法区分具体业务原因,需结合驱动错误码 errorInfo 中的第二位进行判断。通过记录详细错误信息并验证最终数据状态,可避免将缺失必填值的错误误判为重复数据而静默跳过。

2026.01.26 992
PHP使用PDO从MySQL读取大量数据:关闭缓冲查询与生成器优化

本文介绍在PHP 5.6环境下,利用PDO连接MySQL 5.6处理大规模数据集时的内存优化方案。核心在于设置PDO::MYSQL_ATTR_USE_BUFFERED_QUERY为false以禁用结果集缓冲,配合yield生成器逐行迭代数据,从而将内存占用控制在极低水平(如0.34MB),成功处理超过25万行数据而避免内存溢出。

2026.01.01 977
PHP PDO 基础教程:连接、查询与预处理语句详解

本文介绍 PHP 中用于访问数据库的 PDO 扩展。相比已弃用的 mysql_ 系列函数,PDO 支持多种数据库驱动并提供面向对象接口。文章涵盖建立连接、执行简单查询、使用位置参数和命名参数的预处理语句以防止 SQL 注入,以及配置不同的数据获取模式。

2025.09.18 977
PHP执行非缓冲查询的三种API实现方式

本文介绍在PHP中执行非缓冲查询的三种主要API方法,分别基于mysqli、pdo_mysql和mysql扩展。非缓冲查询允许逐行获取结果集,适用于处理大型数据集以减少内存占用。每种方法的具体实现细节及适用场景将在下文详细阐述。

2025.07.18 902
PHP基于PDO的多数据库操作类

分享一个支持MySQL、SQL Server及Oracle的PHP PDO数据库操作类。该类在实际工作中用于统一不同数据库的操作,基于已有代码进行改进后提供,旨在帮助PHP开发者简化多数据库环境下的编程工作。

2025.02.05 862
PHP PDO结果集获取方法详解:fetch、fetchAll与fetchColumn

本文详细介绍PHP中PDO扩展获取数据库结果集的三种核心方法:fetch()、fetchAll()和fetchColumn()。通过具体代码示例,解析各方法的语法参数、返回类型及适用场景,帮助开发者高效处理MySQL数据查询结果。

2026.09.13 837

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
PDO 参数绑定代码生成
PDO 参数绑定代码生成

检查 SQL 命名或问号占位符与 JSON 参数是否匹配,生成使用原生预处理及 bindValue 的 PHP PDO 代码。

键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。