2011-03-23 114 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

相關問題