zf增加.html的后缀,即可以实现静态化的插件
之前是.php后缀的页面,如何只需把后缀改成.html,像:http://www.gudalu.com/index.php,访问:http://www.gudalu.com/index.html 就会自成生成静态文件呢?
前段时间古大陆的cpu有点高,处理txt章节不给,决定搞成这种自动静态,zend framework很方便,三步搞定
1.创建一个ZendEx_Plugin_Html的插件,用来处理写html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <?Php /** * 静态化插件 * * @package tool */ class ZendEx_Plugin_Html extends Zend_Controller_Plugin_Abstract { protected $_filePath; public function setFilePath($filePath) { $this->_filePath = $filePath; } public function dispatchLoopShutdown() { $htmlContent = $this->_response->__toString(); $pathinfo = pathinfo($this->_filePath); !is_dir($pathinfo['dirname']) && mkdir($pathinfo['dirname'], 0777, true); file_put_contents($filePath, $htmlContent); } } |
1. 在入口把所有.html的请求全部转发到HtmlController中~
1 2 3 4 5 6 7 8 9 | $router = $front->getRouter(); $htmlRoute = new Zend_Controller_Router_Route_Regex( '[\d\w\/]+\.html', array( 'module' => 'default', 'controller' => 'html', 'action' => 'handle' ) ); |
2.HtmlController注册ZendEx_Plugin_Html插件,这里可以对uri进行处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | <?php /** * 静态化控制器 * * @author yuehei * @package ex */ class HtmlController extends Core_Controller_Action { public function handleAction() { $requestUri = $this->_request->getRequestUri(); $requestUri = parse_url($requestUri); $requestPath = $requestUri['path']; // --- 通过条件定位对应的参数来静态化数据 $module = 'default'; $controller = $action = ''; $params = array(); if (preg_match('/^\/index.html$/', $requestPath, $rs)) { $controller = 'index'; $action = 'index'; } // --- 文章页 if (preg_match('/^\/file\/([\d]+)\/index\.html$/', $requestPath, $rs)) { $id = $rs[1]; $controller = 'file'; $action = 'view'; $params = array('id' => $id); } if (empty($controller) || empty($action)) { //$this->_showError('无法解析地址'); $this->_closeView(); $this->_response->setHeader('Status', '404 Not Found', true); return; } $this->_forward($action, $controller, $module, $params); $this->_closeView(); $filePath = str_replace('_app', '_www', APP_PATH) . $requestPath; // --- 给更低的运行级别,在render之后运行 $helperHtml = new ZendEx_Plugin_Html(); $helperHtml->setFilePath($filePath); $helperHtml->setRequest($this->_request)->setResponse($this->_response); $this->getFrontController()->registerPlugin($helperHtml); } } |
没有评论▼