Singleton pattern in php

2020-02-06 03:44发布

问题:

class SingleTon
{
    private static $instance;

    private function __construct()
    {
    }

    public function getInstance() {
        if($instance === null) {
            $instance = new SingleTon();
        }
        return $instance;
    }
}

The above code depicts Singleton pattern from this article. http://www.hiteshagrawal.com/php/singleton-class-in-php-5

I did not understand one thing. I load this class in my project, but how would I ever create an object of Singleton initially. Will I call like this Singelton :: getInstance()

Can anyone show me an Singleton class where database connection is established?

回答1:

An example of how you would implement a Singleton pattern for a database class can be seen below:

class Database implements Singleton {
    private static $instance;
    private $pdo;

    private function __construct() {
        $this->pdo = new PDO(
            "mysql:host=localhost;dbname=database",
            "user",
            "password"
        );
    }

    public static function getInstance() {
        if(self::$instance === null) {
            self::$instance = new Database();
        }
        return self::$instance->pdo;
    }
}

You would make use of the class in the following manner:

$db = Database::getInstance();
// $db is now an instance of PDO
$db->prepare("SELECT ...");

// ...

$db = Database::getInstance();
// $db is the same instance as before

And for reference, the Singleton interface would look like:

interface Singleton {
    public static function getInstance();
}


回答2:

Yes, you have to call using

SingleTon::getInstance();

The first time it will test the private var $instance which is null and so the script will run $instance = new SingleTon();.

For a database class it's the same thing. This is an extract of a class which I use in Zend Framework:

class Application_Model_Database
{
   /**
    *
    * @var Zend_Db_Adapter_Abstract
    */
   private static $Db = NULL;

   /**
    *
    * @return Zend_Db_Adapter_Abstract
    */
   public static function getDb()
   {
      if (self::$Db === NULL)
         self::$Db = Zend_Db_Table::getDefaultAdapter();
      return self::$Db;
   }
}

Note: The pattern is Singleton, not SingleTon.



回答3:

A few corrections to your code. You need to ensure that the getInstance method is 'static', meaning it's a class method not an instance method. You also need to reference the attribute through the 'self' keyword.

Though it's typically not done, you should also override the "__clone()" method, which short circuits cloning of instance.

<?
class Singleton
{
    private static $_instance;

    private function __construct() { }
    private final function __clone() { }

    public static function getInstance() {
        if(self::$_instance === null) {
            self::$_instance = new Singleton();
        }
        return self::$_instance;
    }
}
?>

$mySingleton = Singleton::getInstance();

One thing to not is that if you plan on doing unit testing, using the singleton pattern will cause you some difficulties. See http://sebastian-bergmann.de/archives/882-Testing-Code-That-Uses-Singletons.html



回答4:

class Database{
    private static $link=NULL;
    private static $getInitial=NULL;

    public static function getInitial() {
         if (self::$getInitial == null)
         self::$getInitial = new Database();
         return self::$getInitial;
    }
    public function __construct($server = 'localhost', $username = 'root', $password ='tabsquare123', $database = 'cloud_storage') {

         self::$link = mysql_connect($server, $username, $password);
         mysql_select_db($database,self::$link);
         mysql_query("SET CHARACTER SET utf8", self::$link); 
         mysql_query("SET NAMES 'utf8'", self::$link); 
         return self::$link;
    }

    function __destruct(){
          mysql_close(self::$link);
    }
}


标签: php singleton