View Single Post
Old 12-30-2009, 01:46 PM   #16 (permalink)
vonnero
The Visitor
 
Join Date: Dec 2009
Posts: 1
Thanks: 0
vonnero is on a distinguished road
Default

Quote:
Originally Posted by cachepl0x View Post
Great tutorial. It actually looks a lot like the way I did my singleton pattern.. lol

Here it is:

PHP Code:
class Config
{
    const 
host "localhost";
    const 
user "root";
    const 
pass "pass";
    const 
name "name";
}

final class 
Singleton extends Config
{
    protected static 
$connection;
    protected static 
$database null;
    
    protected function 
Singleton () { }
    protected function 
__clone   () { }
    
    static function 
Prepare()
    {
        
self::$connection = new mysqli
        
(
            
parent::host,
            
parent::user,
            
parent::pass,
            
parent::name
        
);
        
        if (
mysqli_connect_errno())
        {
            
printf
            
(
                
"Connection Error: %s\n "mysqli_connect_error()
            );
        } else { echo 
"Databse resource found."; }
    }
    
    public static function 
Instance()
    {        
        if (!isset(
            
self::$database)) {
            
self::$database self::Prepare();
        }
        return 
self::$database;
    }
}

$instance Singleton::Instance(); 
great tut.... how about this? removing the extra method prepare() and moving the code into the __cunstruct

class Config
{
const DB_HOST = "localhost";


const DB_USERNAME = "uuu";



const DB_PASSWORD = "pppp";



const DB_NAME = "bbbb";
}






final class Database extends Config
{

protected static $dbConnection;
protected static $database = NULL;

protected function __construct () {

self::$dbConnection = new mysqli
(
parent::DB_HOST,
parent::DB_USERNAME,
parent::DB_PASSWORD,
parent::DB_NAME
);

if (mysqli_connect_errno())
{

throw new Exception('Unable to connect to database');
}

}

protected function __clone () { }


public static function getInstance()
{


if (!isset(
self::$database)) {
self::$database = new Database();
}
return self::$database;
}
}
vonnero is offline  
Reply With Quote