Best way to adapt a factory method to an interface - php

I'm trying to create the skeleton of a basic framework, but I've stumbled on a situation in which I find myself with some piece of the engine that is missing.
I have this class to manage MySQL connections:
class Mysql implements IConnection {
protected $user;
protected $pass;
protected $dbhost;
protected $dbname;
protected $dbh;
public function __construct($user, $pass, $dbhost, $dbname)
{
$this->user = $user;
$this->pass = $pass;
$this->dbhost = $dbhost;
$this->dbname = $dbname;
}
public function connect()
{
// implementation
}
public function prepare($query)
{
// implementation
}
}
Now I want to use a factory + singleton to manage a sole instance of this class:
class Database
{
private static $db;
private function __construct() {}
public function getInstance($DBType = 'mysql')
{
if (! isset(self::$db)) {
switch ($DBType) {
case 'mysql':
self::$db = new Mysql(); // <---- PROBLEM HERE!!
// more database types should follow
}
}
return self::$db;
}
}
Note that this way I should pass the factory method the connection parameters everytime I needed the database connection instance, which definitely wouldn't be convenient.
The only thing that comes to mind is to pass the db connection, previously created, to Mysql::__construct() and store it in a property, in order to use in within Mysql::prepare(), but it would break the interface: Mysql::connect() wouldn't make any sense, and I couldn't have the db connection wrapped in this class together with the query management.
What would you suggest me to do?
EDIT:
This is my own try, although I would need to change the interface, and I'm not sure if it would be a good approach:
- Changing the interface so that IConnection::connect() accepts the connection parameters instead of the constructor
class Mysql implements IConnection {
protected $dbh; // now I only need this property
public function __construct()
{
}
public function connect($user, $pass, $dbhost, $dbname)
{
// implementation
}
public function prepare($query)
{
// implementation
}
}
And the Singleton Factory:
class Database
{
private static $db;
private function __construct() {}
public function getInstance($DBType = 'mysql')
{
if (! isset(self::$db)) {
switch ($DBType) {
case 'mysql':
self::$db = new Mysql;
break;
case 'mssql':
self::$db = new Mssql;
break;
case 'postgresql':
self::$db = new Postgresql;
break;
// etc
}
}
return self::$db;
}
}
I think this way is clean enough. Some client code:
$db = Database::getInstance(Config::get('db_driver'));
$db->connect(Config::get('db_user'),
Config::get('db_pass'),
Config::get('db_host'),
Config::get('db_name'));
Suggestions and corrections are most welcome.

Related

static variable in singleton design pattern is always null

i had written a chat module and in this module for lowering pressure on database i used singleton design pattern for getting pdo Object.this is my driver class that uses singletone pattern:
class driver {
protected $_servername= "localhost";
protected $_username= "****";
protected $_password= "****";
protected $_dbname= "***";
private static $instance;
private $dbConn;
// The db connection is established in the private constructor.
public function __construct()
{
$this->dbConn = new PDO("mysql:host=$this->_servername;dbname=$this->_dbname", $this->_username, $this->_password);
// set the PDO error mode to exception
$this->dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public static function getInstance()
{
if(!self::$instance)
{
self::$instance = new driver();
}
return self::$instance;
}
public function getConnection()
{
return $this->dbConn;
}
public function __clone() {
throw new Exception("Can't clone a singleton");
}
}
in chat class in constructor i use this codde to get the instance:
$instance = driver::getInstance();
$conn = $instance->getConnection();
$this->_conn =$conn;
so if i put a code like
echo 123;die();
inside getinstance static method like this:
if(!self::$instance)
{
self::$instance = new driver();
echo 1111;die();
}
it always returns 1111. why static$instance variable not being filled or stay being filled with driver object?

PDO connect to db with classes

Im making a PDO system and got a problem/question. I gonna make multiple classes for my codes, for users, products etc. And I was wondering about the connection. I have this in one of my classes:
class Database
{
private $_db;
function __construct($db)
{
$this->_db = $db;
}
}
$db comes from a config file, where I also load all the classes in. The question is now:
Do I have to create the same function in all the classes or can i just have my "database" class that work for all my classes?
No, you don't have to (and shouldn't) create the same function over and over again for every class. That makes it very hard to maintain your application.
Try one of the following methods:
1. Dependency Injection
You can use dependency injection to do this. This is very situational and probably not what you're looking for, but I thought I'd put it here anyway.
Assume the following:
class Database
{
/**
* #var PDO
*/
private $db;
public function __construct(PDO $db)
{
$this->db = $db;
}
}
class User
{
/**
* #var Database
*/
private $db;
// Here we inject a Database object (as hinted by Database $db) into the current instance
public function __construct(Database $db)
{
$this->db = $db
}
}
try
{
$pdo = new PDO(...);
$db = new Database($pdo);
}
catch(PDOException $ex)
{
// Could not connect to database or some other error message
}
// Inject $db in the user class
$user = new User($db);
2. Singleton
You can make your Database class a singleton and then call it statically. This might be more what you need.
class Database
{
/**
* #var Database
*/
private static $instance;
/**
* #var PDO
*/
private $db;
protected function __construct(PDO $db)
{
$this->db = $db;
}
// You'd call this in your config
public static function initialize(PDO $db)
{
if(self::$instance == null)
{
// Create a new instance of this class
self::$instance = new self($db);
}
}
// Get the instance
public static function getInstance()
{
return self::$instance;
}
// Do something
public function doSomething()
{
// Do something
echo "Foo";
}
}
class User
{
public function doSomething()
{
// This would print "Foo"
Database::instance()->doSomething();
}
}
try
{
$db = new PDO(...);
}
catch(PDOException $ex)
{
// Could not connect to database or some other error message
}
Database::initialize($db);
$user = new User();
Hope this helps.

PHP __construct()

I have the following, however I'm unable to access the database functions outside of the initial db class?
Thanks!
database.php
class db
{
private $connection;
public function __construct()
{
$this->connection = new PDO();
}
}
admin.php
class admin
{
private $connection
public function __construct(db $connection)
{
$this->connection = $connection;
}
function myFunc()
{
// How do I access the connection here?
}
}
main.php
//include db.php
//include admin.php
$connection = new db();
$admin = new admin($connection);
// How do I access the DB here?
First of all, why are you encapsulating PDO just to class containing that one object? Cannot you use PDO directly?
One of the common practices would be to implement getter in db class, like:
class db {
...
public function getPDO(){
return $this->connection;
}
}
Another way is to re-implement every function (why would you do that?!), or use __call magic function...
Or just make $connection public ;)
Or you could extend PDO class (I'm not sure whether it'll work):
class DB extends PDO {
public function __construct ( $dsn, $username = null, $password = null, $driver_options = array()){
parent::__construct( $dsn, $username, $password, $driver_options);
... more of your stuff
}
public function myFunc(){
$this->...
}
}
ok, you really need to go and read up on object-oriented design, and access modifiers. I'll explain what you need to do here, but this is a band-aid solution, and you need to deeply understand how things are working here.
In your admin class, you defined the connection as a private attribute of the class. So in the myFunc function, you simply do $this->connection to access the connection that you created in the constructor.
In your main.php file, the object you are getting rom initializing a DB object is not the connection. It is the db object as a whole, so you can not pass the connection by itself to the admin class (it is defined as private, so nobody outside the class can view it). However, why do you need to pass it to the admin class? Managing the DB connection should be the responsibility of the DB class.
In other words, what are you trying to achieve by exposing the DB connection to the admin class?
Upate: based on the reply here is a suggested answer:
class Database {
private $connection;
public function __construct() {
$this->connection = new PDO();
}
}
class Admin {
private $db;
public function __construct() {
$this->db = new Database();
}
public function myFunc() {
$this->db->query('...');
}
}
In your main.php file:
$admin = new Admin();
$admin->myFunc();
Keep in mind, every admin object is going to create a new connection to the DB, so if you create many admin objects you might face some issues. You can get around this by declaring the DB to be a singleton.
How about this:Updated
<pre>
<?php
class DB {
private $host;
private $user;
private $pass;
private $dbase;
private $connection;
public function __construct($host,$user,$pass,$dbase)
{
$this->host = $host;
$this->user = $user;
$this->pass = $pass;
$this->dbase = $dbase;
$this->connection = new PDO("mysql:host=$this->host;dbname=$this->dbase", $this->user, $this->pass);
}
public function connect()
{
return $this->connection;
}
public function close()
{
unset($this->connection);
return true;
}
}
$dbh = new DB('localhost','root','','inventory');
$result = $dbh->connect()->query("SELECT * FROM products")->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
?>
</pre>
Updated with files separation
database.php
class db
{
private $connection;
public function __construct()
{
$this->connection = new PDO();
}
}
admin.php
class admin
{
private $connection
public function __construct(db $connection)
{
$this->connection = $connection;
}
function myFunc()
{
return $this->connection->prepare('SQL');
}
function getConnection()
{
return $this->connection;
}
}
main.php
require_once 'database.php';
require_once 'admin.php';
$connection = new db();
$admin = new admin($connection);
$admin->myFunc()->execute();

Singleton pattern in php

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?
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();
}
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.
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
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);
}
}

Calling a class inside another one in PHP

Hope you can help me with this one: i have two classes: Database and Users. The Database connects to the database using PDO (inside the constructor) and has functions to alter tables, insert data, etc. The Users class will handle login, as well add/remove users. However, the Users class needs to connect to the database. How can i do this?
There are several things you could do:
Globals
$db = new Database();
class Users
{
public function foo()
{
global $db;
$db->query();
}
}
Setting a static variable
$db = new Database();
class Model
{
static public $db;
}
Model::$db = $db;
class Users extends Model
{
public function foo()
{
self::$db->query();
}
}
Use a singleton
class Database
{
private static $instance;
private function __construct()
{
}
public static function instance()
{
return self::$instance ? self::$instance : self::$instance = new self();
}
}
class Users
{
public function foo()
{
Database::instance()->query();
// or $db = Database::instance(); $db->query();
}
}
The one thing you want to avoid is creating a new database connection per model or class.
Same way you normally would, but it might help to make the database a class property:
<?php
class Users
{
protected $_db;
public function __construct(Database $database = null)
{
if (!$database) {
$database = new Database;
}
$this->_db = $database;
}
public function addUser($username)
{
// Do stuff ...
$this->_db->insert($data);
}
}
Then you can use the User class like:
<?php
$users = new Users;
$users->addUser('joebob');
Simply add a reference to the database class instance into Users:
class Users {
var $database;
function __construct() {
$this->database = new Database();
}
};
Alternatively, if Database is a singleton, just reference it directly.
One way to do so would be to create ONE shared instance of the database class, then use it as a global variable wherever needed.
Start by creating the instance anywhere in your project, just make sure it is in global space (not inside another class or function).
$DB = new Database();
Then to access the shared database object, just use the $GLOBALS built-in array:
class User {
function __construct() {
$DB = &$GLOBALS['DB'];
// do something
$DB->callSomeMethod();
}
...
}
As pointed out by #Ryan, namespace collisions are possible using this strategy. The best middle path out would be to convert the Database class into a singleton. Then it would store its own instance (translation: ONE connection no matter what) which could be accessed via a Database::getInstance() method.
This is my Users class:
class Users {
private $data;
private $db;
public function __construct() {
$db = Database::getInstance('localhost', 'database', 'root', '123456');
}
public function __get($key) {
return $this->data[$key];
}
public function __set($key, $value) {
$this->data[$key] = $value;
}
public function test() {
foreach($this->db->query('table', '*', '', '', '', '', '0,5') as $value) {
$results .= $value['field1'] . "<br />";
}
return $results;
}
}

Categories