这是我使用的代码,它展示了类以及使用案例。我已经快速地添加了注释,其中一些可能需要更改以匹配您的路径或者define()
PUBLICPATH
class View_Helper_Minify extends Zend_View_Helper_Abstract
{
public function minify($files, $ext, $folderName)
{
$folder = PUBLICPATH . $folderName . "/";
$update_needed = false;
$cacheFileExt = "." . $ext;
$filesExploded = explode(',', $files);
$cacheFilePath = $folder . md5($files) . $cacheFileExt;
$cacheFileName = preg_replace("#[^a-zA-Z0-9\.]#", "", end(explode("/", $cacheFilePath)));
$cacheFileDate = is_file($cacheFilePath) ? filemtime($cacheFilePath) : 0;
$fileList = array();
foreach($filesExploded as $f)
{
$f = $folder . $f . '.' . $ext;
if(is_file($f))
{
if(filemtime($f) > $cacheFileDate)
$update_needed = true;
$fileList[] = $f;
}
}
if(filemtime($folder) > $cacheFileDate)
$update_needed = true;
if($update_needed)
$this->optmiseFiles($fileList, $cacheFilePath, $ext);
if(is_file($cacheFilePath))
return "/" . $folderName . "/" . $cacheFileName;
throw new Exception("No minified file cached");
}
private function optimise($code, $ext)
{
if($ext == "js")
return $code;
while(($i = strpos($code, '/*')) !== false)
{
$i2 = strpos($code, '*/',$i);
if($i2 === false)
break;
$code = substr($code, 0, $i).substr($code, $i2 + 2);
}
$code = str_replace('/*','',$code);
$code = str_replace("\n",' ',$code);
$code = str_replace("\r",' ',$code);
$code = str_replace("\t",' ',$code);
$code = @ereg_replace('[ ]+',' ',$code);
$code = str_replace(': ',':', $code);
$code = str_replace('; ',';', $code);
$code = str_replace(', ',',', $code);
$code = str_replace(' :',':', $code);
$code = str_replace(' ;',';', $code);
$code = str_replace(' ,',',', $code);
return $code;
}
private function optmiseFiles($fileList, $cacheFilePath, $ext)
{
$code = '';
if(is_array($fileList))
{
foreach($fileList as $f)
$code .= is_file($f) ? $this->optimise(implode('', file($f)), $ext) : '';
}
else
$code = is_file($fileList) ? $this->optimise(implode('', file($fileList)), $ext) : '';
$f = @fopen($cacheFilePath, 'w');
if(is_resource($f))
{
fwrite($f, $code);
fclose($f);
}
}
}
在视图中,您可以像这样使用助手:
$files = array("jquery-ui-1.8.7.custom",
"jquery.pnotify.default",
"jquery.pnotify.default.icons",
"tipTip",
"prettyPhoto",
"custom");
$cssString = $this->minify(implode("," , $files), "css", "css");
echo $this->headLink()
->appendStylesheet($this->baseUrl($cssString));
以下是JavaScript版本的实现
$files = array("jquery-1.4.4.min",
"jquery.pnotify.min",
"jquery.tipTip.minified",
"jquery.countdown.min",
"jquery.prettyPhoto",
"jquery.typewatch",
"default.functions");
$jsString = $this->minify(implode("," , $files), "js", "scripts");
echo $this->headScript()->appendFile($this->baseUrl($jsString));