【问题标题】:How can I build a file/dir path map in PHP?如何在 PHP 中构建文件/目录路径映射?
【发布时间】:2016-08-15 20:27:02
【问题描述】:

我是一名前端开发人员,我决定扩展我的知识来学习 PHP。我还在学习完成事情的语法/方法,所以请多多包涵。

当我开始处理我的第一个 PHP 项目时,我意识到我需要创建一个路径图,只是为了保持清洁和干燥。

这就是我的 php 文件结构现在的样子:

这很容易使用类似 JSON 的数据结构来表示,但我发现尝试使用 PHP 数据类型来实现这一点很尴尬(我仍在学习语法/做事方式)。

我读了一点,我决定使用一些关联数组, 我想出了这个解决方案,它有效,但我想检查一个更简单的解决方案是否可行。 (我的目标是学习PHP的最佳实践)

见:

$paths = array(
    'dirs' => array(
        'base' => '/php/'
    )
);

$paths['dirs']['common'] = $paths['dirs']['base'] . 'common/';
$paths['dirs']['home'] = $paths['dirs']['base'] . 'home/';

$paths['files'] = array(
    'home' => $paths['dirs']['home'] . 'home.php',
    'header' => $paths['dirs']['common'] . 'header.php',
    'scripts' => $paths['dirs']['common'] . 'scripts.php',
    'footer' => $paths['dirs']['common'] . 'footer.php',
    'core' => $paths['dirs']['base'] . 'core.php',
    'business-variables' => $paths['dirs']['base'] . 'business-variables.php'
);

我在这里做坏事吗?

有更好/更简单/标准的方法吗?

【问题讨论】:

    标签: php path hashmap associative-array


    【解决方案1】:

    如果您需要处理文件 - 最好和最简单的方法是使用 DirectoryIterator。在这种情况下,每个文件都是对象,您可以使用他的方法。这里是一个小例子:

    // or '/php/' in your case
    $path = '/';
    foreach (new DirectoryIterator($path) as $file) {
        if ($file->isDot()) continue;
    
        if ($file->isDir()) {
            print $file->getFilename() . '<br/>';
        }
    }
    

    【讨论】:

      【解决方案2】:

      如果您不能只使用DirectoryIterator 读取文件夹结构...

      为了便于阅读,我会这样做:

      class FileStructure {
          const BASE = '/php/';
          const COMMON = 'common/%s';
          const HOME = 'home/%s';
      
          public function Paths(){
             return array(
                 'home' => $this->Home('home.php'),
                 'header' => $this->Common('header.php')
             );
          }
      
          private function Common($file = null){
             return sprintf(static::BASE.static::COMMON, $file);
          }
      
          private function Home($file = null){
             return sprintf(static::BASE.static::HOME, $file);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-25
        • 2016-04-14
        • 2016-07-08
        • 2015-11-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多