5

我目前正在开发一个 PHP Web 应用程序,我想知道在代码仍然可维护的情况下包含文件(include_once)的最佳方式是什么。可维护我的意思是,如果我想移动一个文件,很容易重构我的应用程序以使其正常工作。

我有很多文件,因为我尝试拥有良好的 OOP 实践(一个类 = 一个文件)。

这是我的应用程序的典型类结构:

namespace Controls
{
use Drawing\Color;

include_once '/../Control.php';

class GridView extends Control
{
    public $evenRowColor;

    public $oddRowColor;

    public function __construct()
    {
    }

    public function draw()
    {
    }

    protected function generateStyle()
    {
    }

    private function drawColumns()
    {
    }
}
}
4

2 回答 2

6

我曾经用以下方式启动我的所有 php 文件:

include_once('init.php');

然后在该文件中,我将 require_once 需要需要的所有其他文件,例如 functions.php 或 globals.php,我将在其中声明所有全局变量或常量。这样,您只需在一处编辑所有设置。

于 2011-03-23T02:09:15.733 回答
4

这取决于您要准确完成的任务。

如果你想在文件和它们所在的目录之间有一个可配置的映射,你需要制定一个路径抽象并实现一些加载器函数来处理它。我会做一个例子。

假设我们将使用一个符号Core.Controls.Control来引用Control.php将在(逻辑)目录中找到的(物理)文件Core.Controls。我们需要做一个两部分的实现:

  1. 指示我们的加载器Core.Controls映射到物理目录/controls
  2. Control.php在该目录中搜索。

所以这是一个开始:

class Loader {
    private static $dirMap = array();

    public static function Register($virtual, $physical) {
        self::$dirMap[$virtual] = $physical;
    }

    public static function Include($file) {
        $pos = strrpos($file, '.');
        if ($pos === false) {
            die('Error: expected at least one dot.');
        }

        $path = substr($file, 0, $pos);
        $file = substr($file, $pos + 1);

        if (!isset(self::$dirMap[$path])) {
            die('Unknown virtual directory: '.$path);
        }

        include (self::$dirMap[$path].'/'.$file.'.php');
    }
}

你会像这样使用加载器:

// This will probably be done on application startup.
// We need to use an absolute path here, but this is not hard to get with
// e.g. dirname(_FILE_) from your setup script or some such.
// Hardcoded for the example.
Loader::Register('Core.Controls', '/controls');

// And then at some other point:
Loader::Include('Core.Controls.Control');

当然,这个例子是做一些有用的事情的最低限度,但你可以看到它允许你做什么。

抱歉,如果我犯了任何小错误,我正在打字。:)

于 2011-03-23T02:11:36.513 回答