来源:http://trac.seagullproject.org/wiki/Howto/FileOperations

Working With Files

搜索文件

Seagull允许访问PEAR ultility来管理目录列表。通过在SGL_Util目录中的PEAR文件主要可以实现:

  • 在一行代码中列出文件或目录
  • 过滤结果
  • 转换结果

后两个特性是通过使用回调函数实现的,下面是一个例子:

/***
 * Various utility methods.
 *
 * @package SGL
 * @author  Demian Turner <demian@phpkitchen.com>
 * @version $Revision: 1.12 $
 * @since   PHP 4.1
 */
class SGL_Util
{
    //  other methods left of for clarity
 
    function getAllNavDrivers()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
 
        require_once 'File/Util.php';
        $navDir = SGL_MOD_DIR . '/navigation/classes';
 
        //  match files with *Nav.php format
        $ret = SGL_Util::listDir($navDir, FILE_LIST_FILES, $sort = FILE_SORT_NONE, 
                create_function('$a', 'return preg_match("/.*Nav\.php/", $a);'];
 
        //  parse out filename w/o extension and .
        array_walk($ret, create_function('&$a', 'preg_match("/^.*Nav/", $a, $matches); $a =  $matches[0]; return true;'];
        return $ret;
    }
 
    /**
     * Wrapper for the File_Util::listDir method.
     * 
     * Instead of returning an array of objects, it returns an array of
     * strings (filenames).
     * 
     * The final argument, $cb, is a callback that either evaluates to true or
     * false and performs a filter operation, or it can also modify the 
     * directory/file names returned.  To achieve the latter effect use as 
     * follows:
     * 
     * 
     * function uc(&$filename) {
     *     $filename = strtoupper($filename);
     *     return true;
     * }
     * $entries = File_Util::listDir('.', FILE_LIST_ALL, FILE_SORT_NONE, 'uc');
     * foreach ($entries as $e) {
     *     echo $e->name, "\n";
     * }
     * 
     * 
     * @static
     * @access  public
     * @return  array
     * @param   string  $path
     * @param   int     $list
     * @param   int     $sort
     * @param   mixed   $cb
     */
    function listDir($path, $list = FILE_LIST_ALL, $sort = FILE_SORT_NONE, $cb = null)
    {
        $aFiles = File_Util::listDir($path, $list, $sort, $cb);
        $aRet = array();
        foreach ($aFiles as $oFile) {
            $aRet[$oFile->name] = $oFile->name;
        }
        return $aRet;
    }
}

== 使用PEAR的System::find搜索文件 ==在某个文件夹中搜索带有特定扩展名的文件:

    $dir = SGL_PATH . '/tmpl/basic';
    $aFiles = System::find("$dir -name *.php -name *.serial");
    if (!@System::rm($aFiles] {
        SGL::raiseError('There was a problem deleting the files', 
            SGL_ERROR_FILEUNWRITABLE);
    } else {
        SGL_Output::msgSet('Template cache successfullly deleted');
        SGL_HTTP::redirect('translationMgr.php');
    }

写入文件

file_put_contents()是PHP5独有的函数,当检测到使用的是PHP4版本时,Seagull会模仿出一个类似功能的函数。这是一个将输出写入到文件的方便的函数。

 
howto/fileoperations.txt · 最后更改: 2007/03/02 09:02 (外部编辑)
 
Except where otherwise noted, content on this wiki is licensed under the following license:GNU Free Documentation License 1.2