Symfony2自帶文件緩存(cache)功能用法

    前言:    

    如果你使用Symfony2框架做項目,那麼可能你需要緩存一些數據;說到緩存,方法卻是很多,從數據庫到文件到內存,再分N種緩存技術,比如php自帶的file_put_contents(文件緩存),以及最常見的memcached、APC、redis(內存緩存)等等。

    選擇哪一種緩存:

    確實任何一種緩存技術都可能將你的程序提高許多速度,然而選擇哪一種緩存得根據你項目的實際情況來看。對於點擊量大的建議使用memcached、APC、redis等工具來緩存,因爲他們的結構分明,讀取更快;對於變化不大,經常從一臺服務器取另一臺服務器的內容時(比如讀取API數據),選擇簡單的文件緩存也能比擬工具的速度。

    Symfony2 file cache:

    無需任何配置,只需要在你需要操作的controller文件上方引用Filesystem和IOException即可

    

  use Symfony\Component\Filesystem\Filesystem;
  use Symfony\Component\Filesystem\Exception\IOException;


DefultControll.php

  <?php
  namespace Ce\WebBundle\Controller;
  use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  use Symfony\Component\Filesystem\Filesystem;
  use Symfony\Component\Filesystem\Exception\IOException;
  
  /**
    * @接口緩存文件方法(在實際項目中可以吧它寫到model裏)
    * @$pertime = 0 爲無限生命
    */
  private function cacheFile($filename, $date, $pertime = 0 )
  {
          if(empty($filename) || empty($date)){
    	      return false;
          }
          //在緩存目錄中創建自己的文件
	  $fs = new Filesystem(); 
       
	  try {
	       $fs->mkdir(dirname($filename));
	  } catch (IOException $e) {
	       return false;
	  }

	  //整合數據
	  $time = time();
	  $cache = array();
	  $cache['contents'] = $date;
	  $cache['pertime']   = $pertime === 0 ? 0 : $time + $pertime;
	  $cache['mtime']    = $time;
	  $res = serialize($cache);
	  //寫下你的文件
	  $result = false;
    	  $f = @fopen($filename, 'w');
          if ($f) {
              @flock($f, LOCK_EX);
              fseek($f, 0);
              ftruncate($f, 0);
              $tmp = @fwrite($f, $res);
              if (!($tmp === false)) {
                   $result = true;
              }
              @fclose($f);
          }
	      @chmod($filename,0777);

    	  return $result;
   }
   
   /**
     * @清除緩存文件
     */
    private function clearFile($filename)
    {
    	if(!file_exists($filename)){
    		return false;
    	}else{
    		//刪除緩存文件
    		return unlink($filename);
    	}
    }
   
   /**
     * @調用緩存的方法
     * @Route("/file")
     * @Template()
     */
    public function fileAction()
    {
       
    	$name = 'multiDepot';
        //這裏傳入需要緩存的數據
    	$date = ['id'=>1,'name'=>'小軍'];
    	//設置的緩存時間
	$pertime = 10;
	$newTime = time();
	//設置緩存路徑
    	$filename = $this->container->getParameter('kernel.cache_dir') . ''.$name.'.txt';
    	//如果存在緩存文件,取緩存文件內容
    	if(file_exists($filename)){
    		//閱讀你的文件的內容
		$res = unserialize(file_get_contents($filename));
		//如果文件已經過期,重新緩存文件
		if($res['mtime'] - $newTime < $pertime){
			$this->clearFile($filename);
			$this->cacheFile($filename, $date, $pertime);
		}
		//這裏需要判斷當前數據是否有更新,有更新則從接口取數據,重新種緩存
		//if(true){
		//	clearFile($filename);
		//	$this->cacheFile( $filename, $date, $pertime );
		//}
    	}else{
    		//不存在則緩存文件
	    	$this->cacheFile($filename, $date);
    	}

    OK,非常簡單就實現了Symfony2的文件緩存,緩存的文件在 D:\wamp\www\abc\branches\dev\app\ cache\dev 文件夾下。

    這裏需要注意的是interfere文件夾需要自己手動創建,在服務器上的話還需要設置權限爲可寫、可讀。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章