採用 PEAR 來緩衝 PHP 程式(二)

來源:互聯網
上載者:User
程式 最後,我們來定製一個應用,綜合的來解釋 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();
}
}
?>


在正式開始之前,我們需要一些輔助函數。

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


下面我們來看怎樣緩衝:

<?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>’;
}
?>
<全文完>


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.