Use PEAR to buffer PHP programs (ii)
Last Update:2017-02-28
Source: Internet
Author: User
At the end of the program, let's customize an application that synthesizes the overall framework of the PEAR buffering mechanism.
we define a class called Mysql_query_cache, which buffers the query results of a SELECT.
We first define the variables for the class:
<?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 ();
}
}
?>
before we start, we need some auxiliary functions.
function Connect ($hostname, $username, $password, $database) {
$this->connection = mysql_connect ($hostname, $username, $password) or trigger_error (' Database connection failed! ', e_user_error);
mysql_select_db ($database, $this->connection) or Trigger_error (' Database selection failed! ', 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);
}
?>
below we see how buffer:
<?php
function query ($query) {
if (stristr ($query, ' SELECT ')) {
//Compute the buffer tag of the query
$cache _id = MD5 ($query);
//Query buffering
$this->result = $this->get ($cache _id, ' Mysql_query_cache ');
if ($this->result = = NULL) {
//buffering loss
$this->cursor = 0;
$this->result = Array ();
if (Is_resource ($this->connection)) {
//Use Mysql_unbuffered_query ()
as far as possible
if (function_exists (' mysql_unbuffered_query ')) {$result = Mysql_unbuffered_query ($query, $this->connection);
} else {$result = mysql_query ($query, $this->connection);
}
//Remove all query results
while ($row = Mysql_fetch_assoc ($result)) {$this->result[] = $row;
}
//Release MySQL result resource
mysql_free_result ($result);
Buffer the results
$this->save ($cache _id, $this->result, $this->expires, ' Mysql_query_cache ');
}
}
} else {
//No query results, no buffering required
return mysql_query ($query, $this->connection);
}
}
?>
Example 3: Using the MySQL query buffer
<?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> ';
}
?>
< full finished >