Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Singleton PDO

from http://www.php.net/manual/en/class.pdo.php

###### config.ini ######
db_driver=mysql
db_user=root
db_password=924892xp

[dsn]
host=localhost
port=3306
dbname=localhost

[db_options]
PDO::MYSQL_ATTR_INIT_COMMAND=set names utf8

[db_attributes]
ATTR_ERRMODE=ERRMODE_EXCEPTION
############

<?php class Database {
    private static $link = null ;

    private static function getLink ( ) {
        if ( self :: $link ) {
            return self :: $link ;
        }

        $ini = _BASE_DIR . "config.ini" ;
        $parse = parse_ini_file ( $ini , true ) ;

        $driver = $parse [ "db_driver" ] ;
        $dsn = "${driver}:" ;
        $user = $parse [ "db_user" ] ;
        $password = $parse [ "db_password" ] ;
        $options = $parse [ "db_options" ] ;
        $attributes = $parse [ "db_attributes" ] ;

        foreach ( $parse [ "dsn" ] as $k => $v ) {
            $dsn .= "${k}=${v};" ;
        }

        self :: $link = new PDO ( $dsn, $user, $password, $options ) ;

        foreach ( $attributes as $k => $v ) {
            self :: $link -> setAttribute ( constant ( "PDO::{$k}" )
                , constant ( "PDO::{$v}" ) ) ;
        }

        return self :: $link ;
    }

    public static function __callStatic ( $name, $args ) {
        $callback = array ( self :: getLink ( ), $name ) ;
        return call_user_func_array ( $callback , $args ) ;
    }
} ?>

<?php // examples
$stmt = Database :: prepare ( "SELECT 'something' ;" ) ;
$stmt -> execute ( ) ;
var_dump ( $stmt -> fetchAll ( ) ) ;
$stmt -> closeCursor ( ) ;
?>

My questions are:

What is singleton?

What does static mean/do?

What is public static function __callStatic ( used for?

And how can I make it, that PDO only connects to the database when needed? Such as a query or escaping? So if the class/object is unused then it doesn't connect.

like image 945
Johnny Avatar asked Sep 15 '10 05:09

Johnny


1 Answers

A singleton is a software design pattern that restricts the initiation of a class to one instance. http://en.wikipedia.org/wiki/Singleton_pattern

Static means that something belongs to the class and not a particular instance. In PHP, this also means that a static method needs to be called with :: not ->

_callStatic returns the PDO link if it has already been established. Otherwise, it first creates the link and then returns it.

The answer to your fourth question is precisely the singleton pattern. It ensures that the connection is only set up once, when needed.

like image 113
brian_d Avatar answered Sep 29 '22 17:09

brian_d