在PHP中包含文件的最佳方法?

Jea*_*erc 5 php include-path

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

我有很多文件,因为我尝试了很好的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()
    {
    }
}
}
Run Code Online (Sandbox Code Playgroud)

nan*_*ana 6

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

include_once('init.php');
Run Code Online (Sandbox Code Playgroud)

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

  • 为了使其更易于维护,您可以将init(或配置,我通常称之为)文件的路径定义为环境变量.无论应用程序的目录结构有多深,每个文件都可以导入`$ _ENV ['my_app_config']`而不必担心像`include_once('../../../ init.php)这样的东西")`. (3认同)

Jon*_*Jon 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');
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以像这样使用加载器:

// 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');
Run Code Online (Sandbox Code Playgroud)

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

如果我犯了任何小错误,我很抱歉,我正在边写边写。:)