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

小洋人n

小洋人n

2016-01-29 13:40

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

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


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

我们首先定义类的变量:

<?php
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();
}
}
?

(本文来源于图老师网站,更多请访问https://m.tulaoshi.com/php/)

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

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 < sizeof($this-result)) {
return $this-result[$this-cursor ];
} else {
return false;
}
}

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

(本文来源于图老师网站,更多请访问https://m.tulaoshi.com/php/)

下面我们来看怎样缓冲:

<?php
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 查询缓冲

<?php require_once 'MySQL_Query_Cache.php';

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

while ($row = $cache-fetch_row()) {
echo '<p';
print_r($row);
echo '</p';
}
?

展开更多 50%)
分享

猜你喜欢

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

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

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

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

s8lol主宰符文怎么配

英雄联盟 网络游戏
s8lol主宰符文怎么配

用Pear加速PHP程序开发

PHP
用Pear加速PHP程序开发

10个网络规划PEAR类 来简化PHP编码

PHP
10个网络规划PEAR类 来简化PHP编码

lol偷钱流符文搭配推荐

英雄联盟 网络游戏
lol偷钱流符文搭配推荐

用PEAR来写你的下一个php程序

Web开发
用PEAR来写你的下一个php程序

《PHP程序设计》 第二章 安装PHP

PHP
《PHP程序设计》 第二章 安装PHP

lolAD刺客新符文搭配推荐

英雄联盟
lolAD刺客新符文搭配推荐

Flash组件之旅(2):组件样式(2)

Flash组件之旅(2):组件样式(2)

《魔法禁书目录》试玩发布 主人公的3D格斗

《魔法禁书目录》试玩发布 主人公的3D格斗
下拉加载更多内容 ↓