首页 > php教程 > php手册 > 正文

采用 PEAR 来缓冲 PHP 程序(二)

php中文网
发布: 2016-06-21 09:10:27
原创
1051人浏览过

程序

最后,我们来定制一个应用,综合的来解释 PEAR 缓冲机制的整体框架。


我们定义一个叫做 MySQL_Query_Cache 的类,缓冲 SELECT 的查询结果。

我们首先定义类的变量:



require_once ’Cache.php’;

class MySQL_Query_Cache extends Cache {
var $connection = null;
var $expires = 3600;

var $cursor = 0;
var $result = array();

function MySQL_Query_Cache($container = ’file’,
$container_options = array(’cache_dir’=> ’.’,
’filename_prefix’ => ’cache_’), $expires = 3600)
{
$this->Cache($container, $container_options);
$this->expires = $expires;
}

function _MySQL_Query_Cache() {
if (is_resource($this->connection)) {
mysql_close($this->connection);
}

$this->_Cache();
}
}
?>


在正式开始之前,我们需要一些辅助函数。

function connect($hostname, $username, $password, $database) {
$this->connection = mysql_connect($hostname, $username, $password) or trigger_error(’数据库连接失败!’, E_USER_ERROR);

mysql_select_db($database, $this->connection) or trigger_error(’数据库选择失败!’, E_USER_ERROR);
}

function fetch_row() {
if ($this->cursor result)) {
return $this->result[$this->cursor++];
} else {
return false;
}
}

function num_rows() {
return sizeof($this->result);
}
?>


下面我们来看怎样缓冲:

function query($query) {
if (stristr($query, ’SELECT’)) {
// 计算查询的缓冲标记
$cache_id = md5($query);

// 查询缓冲
$this->result = $this->get($cache_id, ’mysql_query_cache’);

if ($this->result == NULL) {
// 缓冲丢失
$this->cursor = 0;
$this->result = array();

if (is_resource($this->connection)) {
// 尽可能采用 mysql_unbuffered_query()

if (function_exists(’mysql_unbuffered_query’)) {$result = mysql_unbuffered_query($query, $this->connection);
} else {$result = mysql_query($query, $this->connection);
}

// 取出所有查询结果
while ($row = mysql_fetch_assoc($result)) {$this->result[] = $row;
}

// 释放 MySQL 结果资源
mysql_free_result($result);
// 把结果缓冲
$this->save($cache_id, $this->result, $this->expires, ’mysql_query_cache’);
}
}
} else {
// 没有查询结果,不需要缓冲
return mysql_query($query, $this->connection);
}
}
?>


例 3: 使用 MySQL 查询缓冲


$cache = new MySQL_Query_Cache();
$cache->connect(’hostname’, ’username’, ’password’, ’database’);
$cache->query(’select * from table’);

while ($row = $cache->fetch_row()) {
echo ’

’;
print_r($row);
echo ’

宣小二
宣小二

宣小二:媒体发稿平台,自媒体发稿平台,短视频矩阵发布平台,基于AI驱动的企业自助式投放平台。

宣小二 21
查看详情 宣小二
’;
}
?>



相关标签:
PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号