php資料緩衝到檔案類設計

來源:互聯網
上載者:User

標籤:徹底刪除   md5   完成   緩衝   array   key   host   cal   反序   

// 自訂緩衝類class Cache_Filesystem {    // 緩衝寫儲存  function set ($key, $data, $ttl) {     //開啟檔案為讀/寫入模式     $h = fopen($this->get_filename($key), ‘a+‘);     if (!$h) throw new Exception("Could not write to cache");     flock($h, LOCK_EX); //寫鎖定,在完成之前檔案關閉不可再寫入          fseek($h, 0); // 讀到檔案頭     ftruncate($h, 0); //清空檔案內容     // 根據生存周期$ttl寫入到期時間     $data = serialize(array(time()+$ttl, $data));     if (fwrite($h, $data) === false) {        throw new Exception(‘Could not write to cache‘);     }     fclose($h);  }  // 讀取快取資料,如果未取出返回失敗資訊    function get ($key) {    $filename = $this->get_filename($key);    if ( !file_exists( $filename ) ) {       return false;    }    $h = fopen($filename, ‘r‘);    if (!$h) return false;    // 檔案讀取鎖定    flock($h, LOCK_SH);    $data = file_get_contents($filename);    fclose($h);    $data = @unserialize($data);    if ( !$data ) {        // 如果還原序列化失敗,則徹底刪除該檔案        unlink($filename);        return false;    }    if (time() > $data[0]) {       // 如果緩衝已經到期,則刪除檔案       unlink($filename);       return false;    }      }      // 清除緩衝  function clear ( $key ) {     $filename = $this->get_filename($key);     if (file_exists($filename)) {       return unlink($filename);     } else {     return false;     }  }  // 擷取快取檔案    private function get_filename ($key) {    return ‘./cache/‘ . md5($key);  }}

調用

require ‘./4.3-cache_class.php‘;// 建立新對象$cache = new Cache_Filesystem();function getUsers () {  global $cache;  // 自訂一個緩衝key唯一標識  $key = ‘getUsers:selectAll‘;  // 檢測資料是否緩衝  if ( !$data = $cache->get( $key ) ) {    // 如果沒有緩衝,則擷取新資料    $db_host = ‘localhost‘;    $db_user = ‘root‘;    $db_password = ‘root‘;    $database = ‘ecshop_test‘;    $conn = mysql_connect( $db_host, $db_user, $db_password);    mysql_select_db($database);    //執行sql查詢    $result = mysql_query("select * from ecs_users");    $data = array();    // 將擷取到的資料放入數組$data中    while ( $row = mysql_fetch_assoc($result)) {     $data[] = $row;    }    // 儲存該資料到緩衝中,生存周期為10分鐘    $cache->set($key, $data, 10);  }  return $data;}try {  $users = getUsers();  print_r($users);  $key = ‘getUsers:selectAll‘;  //$cache->clear($key);} catch (Exception $e) {  print $e->getMessage();}

  

php資料緩衝到檔案類設計

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.