【问题标题】:Best way to include file in PHP?在 PHP 中包含文件的最佳方法?
【发布时间】:2011-07-20 23:29:26
【问题描述】:

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

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

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

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()
    {
    }
}
}

【问题讨论】:

  • 我也有过这个问题,结果发现PHP真的没有一个很好的包系统。不过,Netbeans 确实有帮助。

标签: php include-path


【解决方案1】:

我以前所有的 php 文件都是这样开始的:

include_once('init.php');

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

【讨论】:

  • 为了使其更易于维护,您可以将 init(或配置,我通常称之为)文件的路径定义为环境变量。无论应用程序的目录结构有多深,每个文件都可以只导入$_ENV['my_app_config'],而不必担心include_once('../../../init.php')之类的东西。
【解决方案2】:

这取决于您要完成的具体目标。

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

假设我们将使用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');

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

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

【讨论】:

    猜你喜欢
    • 2015-04-30
    • 2012-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多