因為有需要讀取 config ,剛好 Singleton Pattern 很適合這種使用情境,所以就寫了一個 PHP 版的 Config Tool 來用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<?php class Config { private static $instance; private static $config = array(); private function __construct() { // 使用 private 建構子避免在外面被意外地初始化 } private static function getInstance() { if (!isset(self::$instance)) { $class = __CLASS__; self::$instance = new $class(); require_once '/config/config.php'; // 使用絕對路徑效率會比較好 static::$config = $config; // $config 來自上面的 PHP 檔. // echo 'initial - '; } else { // echo 'singleton - '; } } public static function getValue($key) { self::getInstance(); if (isset(self::$config[$key])) { return self::$config[$key]; } else { return NULL; } } } |
然後需要有一個對應的 config 檔案,這邊為了方便直接寫成 PHP 的 map ,當然也可以寫成 ini/xml/yml 格式。:
1 2 3 4 5 6 7 8 |
<?php $config = array(); $config['test1'] = 'hello'; $config['test2'] = 'kitty'; $config['test3'] = 'foo'; $config['test4'] = 'bar'; |
執行方法 – 這樣的寫法可以避免每次都要重新讀取設定檔:
1 2 3 4 5 6 |
echo Config::getValue('test1') . PHP_EOL; echo Config::getValue('test2') . PHP_EOL; echo Config::getValue('test3') . PHP_EOL; echo Config::getValue('test4') . PHP_EOL; |
我還蠻好奇Singleton和純粹用static methods有什麼差別
我的看法是同樣的 class (裡面含有 static method) 還是可以 new 成不同的實體,
而 Singleton 是避免這種事情發生。或許還有其他好處吧,但就我來講,我想在很多的不同的地方拿到同樣一份的 config 。
雖然不太會 php
不過這個設計好方便啊 0.0