2012-11-18 34 views
1

我有一個負責處理所有配置的類 - 從文件讀取配置,並獲取在index.php(+從那裏設置它們)中設置的基本配置變量。因此,我決定在這裏使用多態 - 我做了Config類抽象,並用FILE和VARIABLE類擴展了這個。多態 - 確保一切正確

這是一個很好的做法行爲,如果這兩個職責的基類是100行長嗎?

不要在這裏冷落我 - 我只是不想在項目已經完成時發現它不是靈活的解決方案。

這是代碼(雖然沒有重構,測試和添加一些功能,但概念應該清楚)。

class Config { 

    private $file; 

    public static $configs = array(); 

    /** 
    * Initializes basic website configurations such as base URL, or the name 
    * of the index file. 
    * 
    * These values can be accessed through this class 
    */ 
    public static function init($configs = array()) 
    { 
     foreach($configs as $key => $value) 
     { 
      self::$configs[$key] = $value; 
     } 
    } 

    /** 
    * Returns the configuration variable which is set in the index file 
    * 
    * @param string $attribute 
    * @return multitype: 
    */ 
    public function __get($attribute) 
    { 
     return ($this->configs[$attribute]) ? $this->configs[$attribute] : -1; 
    } 

    /** 
    * Setting path to the config file. 
    * 
    * @param string $module 
    */ 
    private function __construct($module) 
    { 
     // Path to the config file 
     $path = APATH . 'config' . DIRECTORY_SEPARATOR . $module . '.php'; 

     // Set the config file to the attribute here 
     $this->file = include $path; 
    } 

    /** 
    * Return the object. 
    * 
    */ 
    public static function factory($module) 
    { 
     return new Config($module); 
    } 

    /** 
    * Loads configurations from the given file. 
    * 
    */ 
    public function load($property) 
    { 
     // Return requested value 
     return $array[$property]; 
    } 

} 
+1

請發一些代碼嗎? – mauris

+2

http://codereview.stackexchange.com可能是比較合適的網站。 –

+0

誰最喜歡的問題是?的xD – user1615069

回答

1

沒有什麼錯你在做什麼,但它使我不知道爲什麼想要做這種方式。

如果您試圖以特定的方式強制執行配置變量的處理,那麼可能會在靜態類中加載它們一次。如果你正在嘗試抽象化,那麼它是100行還是1K或者其他什麼都不重要。

它確實讓我想知道爲什麼你會在很多不同的文件中分散配置變量,這樣就需要封裝這樣的加載過程。通常配置信息在啓動時加載一次並保存。如果在應用程序啓動後某個文件/類在某個地方出現什麼情況,會不會加載配置或者只是忽略實現?

如果沒有其他的東西,你可能會想讓'init'保密,並從你的構造函數中調用它。否則,可以調用「工廠」,但忽略此步驟並假定不存在配置信息。另外 - 如果'configs'是靜態的,那麼'$ this-> configs'似乎有點粗略。