2011-03-23 155 views
5

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

我有很多文件,因为我尝试有良好的面向对象实践(一个类=一个文件)。

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

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

我也有这个问题,我已经到了PHP的结果,真的没有一个很好的包系统。 Netbeans虽然有帮助。 – 2011-03-23 02:10:03

回答

4

这取决于你想要完成什么。

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

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

  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'); 

当然,这个例子是最起码的,做一些有用的东西,但你可以看到它允许你做什么。

道歉,如果我犯了一些小错误,我正在打字,因为我走了。 :)

6

我用来启动与所有我的PHP文件:

include_once('init.php'); 

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

+3

为了使其更易于维护,您可以将init(或config,正如我通常所说的那样)文件的路径定义为环境变量。无论应用程序的目录结构有多深,每个文件都可以导入'$ _ENV ['my_app_config']',而不必担心像'include_once('../../../ init.php “)'。 – 2011-03-23 02:12:20

相关问题