Note that there are some explanatory texts on larger screens.

plurals
  1. POIs there a use-case for singletons with database access in PHP?
    text
    copied!<p>I access my MySQL database via PDO. I'm setting up access to the database, and my first attempt was to use the following:</p> <p>The first thing I thought of is <code>global</code>:</p> <pre><code>$db = new PDO('mysql:host=127.0.0.1;dbname=toto', 'root', 'pwd'); function some_function() { global $db; $db-&gt;query('...'); } </code></pre> <p>This is considered a bad practice. After a little search, I ended up with the <a href="http://www.php.net/manual/en/language.oop5.patterns.php">Singleton pattern</a>, which</p> <blockquote> <p>"applies to situations in which there needs to be a single instance of a class." </p> </blockquote> <p>According to the example in the manual, we should do this:</p> <pre><code>class Database { private static $instance, $db; private function __construct(){} static function singleton() { if(!isset(self::$instance)) self::$instance = new __CLASS__; return self:$instance; } function get() { if(!isset(self::$db)) self::$db = new PDO('mysql:host=127.0.0.1;dbname=toto', 'user', 'pwd') return self::$db; } } function some_function() { $db = Database::singleton(); $db-&gt;get()-&gt;query('...'); } some_function(); </code></pre> <p>Why do I need that relatively large class when I can do this?</p> <pre><code>class Database { private static $db; private function __construct(){} static function get() { if(!isset(self::$rand)) self::$db = new PDO('mysql:host=127.0.0.1;dbname=toto', 'user', 'pwd'); return self::$db; } } function some_function() { Database::get()-&gt;query('...'); } some_function(); </code></pre> <p>This last one works perfectly and I don't need to worry about <code>$db</code> anymore. </p> <p>How can I create a smaller singleton class, or is there a use-case for singletons that I'm missing in PHP?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload