2008-10-14

【程式】PHP : Singleton

之前在網路上看到一篇文章[Using globals in PHP ],裡面寫的方法還不錯,用起來的感覺就像Global一樣,一直都只會有一個Object。

// Get instance of DBConnection
$db =& DBConnection::getInstance();

// Set user property on object
$db->user = 'sa';

// Set second variable (which points to the same instance)
$second =& DBConnection::getInstance();

// Should print 'sa'
echo $second->user;

Class DBConnection {
  var $user;

  function &getInstance() {
    static $me;
    if (is_object($me) == true) {
      return $me;
    }
    $me = new DBConnection;
    return $me;
  }
  function connect() {
    // TODO
  }
  function query() {
    // TODO
  }
}

更進一步的用法,就是可以在Object宣告一個Array,寫一個Get和Set的Function,
然後利用Get和Set來存取你的資料。

Class Registry {
  var $_objects = array();

  function &getInstance() {
    static $me;
    if (is_object($me) == true) {
      return $me;
    }
    $me = new Registry;
    return $me;
  }
  function set($name, &$object) {
    $this->_objects[$name] = &$object;
  }
  function &get($name) {
    return $this->_object[$name];
  }
}
$db = new DBConnection;
$settings = new Settings_+XML;
$user = new User;

//Register Objects
$registry =& Registry::getInstance();
$registry->set ('db', $db);
$registry->set ('settings', $settings);
$registry->set ('user', $user);

function test() {
  $registry =& Registry::getInstance();
  $db =& $registry->get('db');
  $settings =& $registry->get('settings');
  $user =& $registry->get('user');
  // Do something with the objects
}



0 comments:

張貼留言