CodeIgniter自己帶了一套靜態化系統php
使用方法以下:ajax
$this->output->cache( 3 );//每三分鐘從新生成一次靜態頁面數據庫
不過這個在系統化的編輯中不方便管理 由此開發者能夠自定義一套本身的緩存管理系統緩存
好比加載相關的ctrl + act配置到memcache中以方便配置的查詢 及緩存的清理從新生成等框架
增長數據庫表以下fetch
CREATE TABLE `chewu_news` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`delsign` tinyint(3) unsigned NOT NULL,
`mid` bigint(20) unsigned NOT NULL,
`comment` varchar(128) DEFAULT NULL,
`modtime` datetime NOT NULL,
`addtime` datetime NOT NULL,
`controller' varchar(128) NOT NULL,
'action' varchar(128) NOT NULL,
'minutes' mediumint default 0;
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=138 DEFAULT CHARSET=utf8 COMMENT='緩存管理表;ui
添加ctrl action到數據庫中this
/**
* dev
* 加載ctrl action到數據庫中 只在開發時使用
*/
public function loadCtrlActIntoDb()
{
$this->_load_ctrls_into_db( dirname( dirname( __FILE__ ) ));
}url
//////////////////////////////////////////////////////////////////////////////////
//load cache info into database
private function _load_ctrls_into_db( $dir )
{
include_once APPPATH . 'utils/TimeUtils.php';
$list = scandir( $dir ); // 獲得該文件下的全部文件和文件夾
foreach( $list as $file)
{ //遍歷
$file_location = $dir . "/" . $file; //生成路徑debug
if( is_file( $file_location ) && (-1 != strstr( $file_location, '.php' ) || -1 != strstr( $file_location, '.PHP' )) )
{
//取class
$iBegin = strpos( $file_location, 'controllers' );
$iBegin += strlen( 'controllers' );
$iEnd = strrpos( $file_location, '/' );
$strModel = '';
$strModel = substr( $file_location, $iBegin + 1, strrpos( $file_location, '.php' ) - $iBegin - 1 );
if( $iBegin != $iEnd )
{ //model爲文件夾名+文件名
$strModel = str_replace( '/', '_', $strModel );
}
if( 0 === strpos( $strModel, 'learn' ) || 0 === strpos( $strModel, 'test' ) || 0 === strpos( $strModel, 'config' ) )
{
continue;
}
$strClsFile = file_get_contents( $file_location );
$iPos = strpos( $strClsFile, 'class' );
if( false == $iPos )
{ //非類文件
continue;
}
$strClsFile = substr( $strClsFile, $iPos );
$arrRes = preg_split( '/public[ ]+function[ ]+/', $strClsFile );
$strCls = $arrRes [0];
$strCls = preg_replace( '/[ ]+/', ' ', $strCls );
$arrCls = explode( ' ', $strCls );
$strCtrl = trim( $arrCls [1] );
$iSize = count( $arrRes );
for( $i = 1; $i < $iSize; ++ $i )
{ //
$strAction = trim( $arrRes [$i] );
$iEnd = strpos( $strAction, '(' );
$strFunc = substr( $strAction, 0, $iEnd );
if( '__construct' != $strFunc && '__destruct' != $strFunc && !isset( $this->objCtrls->$strCtrl->actions [$strFunc] ) )
{
//
$recCtrlAction = array (
'addtime' => TimeUtils::getFullTime(),
'modtime' => TimeUtils::getFullTime(),
'delsign' => MallEnum::DEL_SIGN_NO,
'mid' => 1,
'controller' => $strCtrl,
'action' => $strFunc,
'minutes' => 0 );
$this->db->insert( TableNames::CHEWU_CACHE_TIME_MGR, $recCtrlAction );
}
}
}
if( is_dir( $file_location ) && $file != "." && $file != ".." )
{ //判斷是否是文件夾
$this->_load_ctrls_into_db( $file_location ); //繼續遍歷
}
}
}
加載ctrl action信息到memcache
private function _loadCtrls( )
{
$this->objCtrls = new stdClass();
$query = $this->db->get_where( TableNames::CHEWU_CACHE_TIME_MGR, array (
'delsign' => MallEnum::DEL_SIGN_NO ) );
$arrRes = $query->result();
foreach( $arrRes as $row)
{
if( !isset( $this->objCtrls->{$row->controller} ) )
{
$this->objCtrls->{$row->controller} = new stdClass();
}
$this->objCtrls->{ $row->controller }->actions [$row->action] = $row;
}
}
/**
* 加載到內存
*/
public function loadStaticMgrInfoIntoMem( )
{
$this->_loadCtrls();
$this->memcacheutils->set( 'ctrlsInfo', $this->objCtrls, 0 );
$this->memcacheutils->set( 'bCtrlInfo', 1, 0 );
foreach( $this->objCtrls as $ctrl => $actions)
{
if( isset( $actions->actions ) )
{
foreach( $actions->actions as $actname => $act)
{
$this->memcacheutils->set( MallEnum::CTRL_ACTION . $act->controller . $act->action, $act->minutes, 0 );
}
}
}
echo 'ret=0';
}
以後可開發一管理端 對某些須要的action進行管理
這時使用靜態化的訪求以下
public function index( )
{
$this->output->cache( intval( $this->memcacheutils->get( MallEnum::CTRL_ACTION . __CLASS__ . __FUNCTION__ ) ));
$this->mallBiz->index();
}
爲了方便管理這裏要對CodeIgniter的框架進行一些修改以下(system/core/Output.php):
/**
* Write a Cache File
*
* @access public
* @param string
* @return void
*/
function _write_cache($output)
{
$CI =& get_instance();
$path = $CI->config->item('cache_path');
$cache_path = ($path == '') ? APPPATH.'cache/' : $path;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//以上爲方便管理cache所作的修改
$Rtr = $GLOBALS[ 'RTR' ];
$cache_path .= $Rtr->fetch_class() . $Rtr->fetch_method() . '/';
if( !is_dir( $cache_path ) )
{
mkdir( $cache_path );
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if ( ! is_dir($cache_path) OR ! is_really_writable($cache_path))
{
log_message('error', "Unable to write cache file: ".$cache_path);
return;
}
$uri = $CI->config->item('base_url').
$CI->config->item('index_page').
$CI->uri->uri_string();
$cache_path .= md5($uri);
if ( ! $fp = @fopen($cache_path, FOPEN_WRITE_CREATE_DESTRUCTIVE))
{
log_message('error', "Unable to write cache file: ".$cache_path);
return;
}
$expire = time() + ($this->cache_expiration * 60);
if (flock($fp, LOCK_EX))
{
fwrite($fp, $expire.'TS--->'.$output);
flock($fp, LOCK_UN);
}
else
{
log_message('error', "Unable to secure a file lock for file at: ".$cache_path);
return;
}
fclose($fp);
@chmod($cache_path, FILE_WRITE_MODE);
log_message('debug', "Cache file written: ".$cache_path);
}
/**
* Update/serve a cached file
*
* @access public
* @param object config class
* @param object uri class
* @return void
*/
function _display_cache(&$CFG, &$URI)
{
$cache_path = ($CFG->item('cache_path') == '') ? APPPATH.'cache/' : $CFG->item('cache_path');
// Build the file path. The file name is an MD5 hash of the full URI
$uri = $CFG->item('base_url').
$CFG->item('index_page').
$URI->uri_string;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//此爲方便管理cache而作的修改
$Rtr = $GLOBALS[ 'RTR' ];
$cache_path .= $Rtr->fetch_class() . $Rtr->fetch_method() . '/';
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$filepath = $cache_path . md5($uri);
if ( ! @file_exists($filepath))
{
return FALSE;
}
if ( ! $fp = @fopen($filepath, FOPEN_READ))
{
return FALSE;
}
flock($fp, LOCK_SH);
$cache = '';
if (filesize($filepath) > 0)
{
$cache = fread($fp, filesize($filepath));
}
flock($fp, LOCK_UN);
fclose($fp);
// Strip out the embedded timestamp
if ( ! preg_match("/(\d+TS--->)/", $cache, $match))
{
return FALSE;
}
// Has the file expired? If so we'll delete it.
if (time() >= trim(str_replace('TS--->', '', $match['1'])))
{
if (is_really_writable($cache_path))
{
@unlink($filepath);
log_message('debug', "Cache file has expired. File deleted");
return FALSE;
}
}
// Display the cache
$this->_display(str_replace($match['0'], '', $cache));
log_message('debug', "Cache file is current. Sending it to browser.");
return TRUE;
}
}
經以上修改後生成的cache再也不是之前的只有md5 hash後的文件名 而是每一個ctrlaction放在同一個文件夾裏這樣能夠方便cache的管理(好比刪除等)
緩存清理方法以下
//ajax方法
public function clearStaticCache()
{
$strCtrl = trim( $this->uri->segment( 4 ));
$strAct = trim( $this->uri->segment( 5 ));
if( $strCtrl === false || $strCtrl == '' ||
$strAct === false || $strAct == '' )
{
show_404();
}
$strPath = $this->config->item( 'cache_path' ) . $strCtrl .$strAct;
if( file_exists( $strPath ) )
{
$this->load->helper( 'file' );
delete_files( $strPath, true );
rmdir( $strPath );
}
echo 'ret=0';
}
通過以上CodeIgniter的可行宜用的靜態緩存系統已經創建完畢