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.
Related
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.
I'm trying to access an object outside of a class. I already have a class called Database which has a series of functions in it.
$database = new Database($host,$user,$pass,$name);
class User {
function view($username) {
$user = $database->findFirst('User','username',$username);
}
}
I cannot work out how to access the $database object and keep getting an error saying Undefined variable.
You could make use of dependnecy injection - constructor injection, e.g.
class User
{
/**
* #var Database
*/
protected $db;
public function __construct(Database $database)
{
$this->db = $database;
}
public function view($username)
{
$user = $this->db->findFirst('User', 'username', $username);
}
}
$database = new Database(/* ... */);
$user = new User($database);
Regarding the question in comment: Yes, this is possible. Let's think about some basic (abstract) class that could be used as a parent for all classes that should share the same basic logic (e.g. connecting to a DB, or at least injecting a DB connection).
Such abstract class could be:
class DBObject
{
/**
* #var Database
*/
protected $db;
public function __construct(Database $db)
{
$this->db = $db;
}
}
Then our User class can extend this abstract class in this way:
class User extends DBObject
{
public function view($username)
{
$user = $this->db->findFirst('User', 'username', $username);
}
}
Keep in mind that though the abstract class can implement __construct() function, it cannot be directly instantiated. Then somewhere in the code You can do the very same as in first example:
$database = new Database(/* ... */);
$user = new User($database);
$post = new Post($database);
$database should be a class member. Try this:
$database = new Database($host,$user,$pass,$name);
class User {
protected $db;
public function __construct($database) {
$this->db = $database;
}
public function view($username) {
$user = $db->findFirst('User','username',$username);
}
}
Simply define it as global variable within the function. Yet the proper way would be to make constructors or extend it with Database class.
$database = new Database($host,$user,$pass,$name);
class User {
function view($username) {
global $database;
$user = $database->findFirst('User','username',$username);
}
}
P.S. Here is another post where you can see the same situation with this solution.
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();
I need to use $GLOBALS['db'] in my classes ($db is defined in my index.php), but I don't want to use $GLOBALS['db'] when I have to call it.
I wrote this code at the beginning of my classes :
class ClassName
{
var $db;
public function __construct()
{
$this->db = $GLOBALS['db'];
}
public function test()
{
$val = $this->db->oneValue('SELECT first_name FROM users LIMIT 0, 1');
echo $val->first_name;
}
}
But I'm not enjoying this; I prefer to use directly $db in my code. Is there a solution to be able to call $GLOBALS['db'] by $db?
Simples, just inject in the constructor or a setter method: (I'm assuming $db is an object here, not an array of connection parameters etc)
class ClassName
{
protected $db;
public function __construct($db)
{
$this->setConnection($db);
//Any other constructor things you want to happen...
}
/*
* This is just here for convenience, this could be protected if you only want to set
* the db connection via the constructor
*/
public function setConnection($db)
{
$this->db = $db;
}
public function test()
{
$val = $this->db->oneValue('SELECT first_name FROM users LIMIT 0, 1');
echo $val->first_name;
}
}
As mentioned in some comments above, this is a form of dependency injection which will give you more ability to re-use code inside your project (A Good Thing TM).
I prefer using singleton pattern for databases.
this is the DB class i am using for my app.
class Database {
protected static $_dbh;
const HOST = 'localhost';
const DATABASE = 'dbname';
const USERNAME = 'username';
const PASSWORD = 'password';
private function __construct() { }
public static function getInstance() {
if(!isset($_dbh)) {
try {
#Connection String.
self::$_dbh = new PDO('mysql:host='.self::HOST.';dbname='.self::DATABASE,self::USERNAME,self::PASSWORD);
self::$_dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
#Print Errors.
echo $e->getMessage();
}
}
return self::$_dbh;
}
}
as i am using singleton pattern the connection will be re-used. you can now use the connection everywhere in your app by calling static connection method i.e
class ClassName
{
protected static $_dbh;
public function __construct() {
self::$_dbh = Database::getInstance();
}
public function test() {
$sth = self::$_dbh->query('SELECT first_name FROM users LIMIT 0, 1');
$row = $sth->fetchAll(PDO::FETCH_ASSOC);
echo $row['first_name'];
}
}
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);
}
}