PDO anonymous function inside Factory - php

In this question here on S.O, the accepted answer suggests to use both anonymous function and factory pattern for dealing with PDO connection. I believe the anonymous function is used in case a connection to a different database needs to be established, a different function will be defined for that. In that case, will it be alright to move the anonymous function to the factory class itself for just a single database?
This is what I had in mind
class StructureFactory
{
protected $provider = null;
protected $connection = null;
public function __construct( )
{
$this->provider = function() {
$instance = new PDO('mysql:......;charset=utf8', 'username', 'password');
$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$instance->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
return $instance;
};
}
public function create( $name )
{
if ( $this->connection === null )
{
$this->connection = call_user_func( $this->provider );
}
return new $name( $this->connection );
}
}
Also, even with this approach why not just passing the PDO parameters to the constructor achieve what the original answer was trying to achieve, i.e to establish different connections?
Something like:
class StructureFactory
{
protected $provider = null;
protected $connection = null;
public function __construct( $PDO_Params )
{
$this->provider = function() {
$instance = new PDO($PDO_Params["dsn"], $PDO_Params["username"], $PDO_Params["password"]);
$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$instance->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
return $instance;
};
}
public function create( $name)
{
if ( $this->connection === null )
{
$this->connection = call_user_func( $this->provider );
}
return new $name( $this->connection );
}
}

No. Because that way you loos any benefits from dependency injection.
The modification, that you could to is: inject an initialized PDO instance directly in the factory, instead of using this lazy-loading approach. Kinda like in this answer.
I would also recommend watching this lecture.

Related

Calling single db connection using static method

I tried to follow the structure factory in creating a single db connection as per below:
try {
$provider = function() {
$instance = new PDO("dsn", "username", "password");
return $instance;
};
} catch (PDOException $exception) {
error_log($exception->getMessage());
}
$factory = new StructureFactory($provider);
and StructureFactory as below:
class StructureFactory {
protected $provider = null;
protected $connection = null;
public function __construct(callable $provider) {
$this->provider = $provider;
}
public function create($class_name) {
if ($this->connection === null) {
$this->connection = call_user_func($this->provider);
}
return new $class_name($this->connection);
}
}
Then when I need to create a book instance, say "Book", I do this:
$factory->create("Book");
But if I don't need to create a book instance yet but just want to check if that book is existing, I'd like to call a static method on my "Book" class like:
Book::isBookExisting($bookname);
But inside this static method, how can I have the single database connection if I can only have it when I create the "Book" instance?
Or should I just use a Singleton for my db connection instead of doing this factory?
I am kinda at lost cause I'm not sure if I am doing it correctly. Please advise.
First
The way you've written the try catch block is mostly useless and certainly not doing as you expect.
try {
$provider = function() {
$instance = new PDO("dsn", "username", "password");
return $instance;
};
} catch (PDOException $exception) {
error_log($exception->getMessage());
}
Remember, $provider = function() { ... is an anonymous function. The code inside it only runs when the function is called. In other words, the code inside the try block, in your example, will never throw an exception. It will only ever throw an exception when is is called e.g. $provider().
Refactored
$provider = function() {
try {
$instance = new PDO("dsn", "username", "password");
} catch (PDOException $exception) {
error_log($exception->getMessage());
}
return $instance;
};
The database connection
There are too many ways to solve the database dependency issue, many of which are opinionated. There is no one solution.
You could:
Use a singleton
Use a argument dep. Book::isBookExisting($provider, $bookname);
Use a static dep. Book::setProvider($provider); Book::isBookExisting($bookname);
...
Further Reading:
Dependency Injection

how i can prevent multiple time connected to database

here is my code
pdo.php
class Connection {
public function __construct() {
$this->connect ($db);
}
private function connect($db) {
try {
if (! $db){
$this->db = new PDO ( 'mysql:host=localhost;dbname=Shopping;charset=utf8', 'xxxx', 'xxxxx' );
echo 'Connected';
return $this->db;
}
catch ( PDOException $conError ) {
echo 'failed to connect DB' . $conError->getMessage ();
}
}
}
product.php
class ProductInsert extends Connection { //here my function is called multiple times
function __construct() {
parent::__construct($db);
}
public function prdInsert(.....)
{ ........}
here my problem is database connection is opened multiple time. when ever i am calling the productInsert() then database connection is opened how i can prevent this
Do not extend your application class from database class.
This is your main problem.
They are too different classes having nothing in common.
So you have to just use your db object as a property.
Connection class is also useless at the moment, as it's just a leaky disguise for the PDO.
So, just create raw PDO object and then pass it in the constructor of product
class ProductInsert
{
function __construct(PDO $db)
{
$this->db = $db;
}
public function prdInsert(.....)
}
And for goodness sake, learn to indent your code.
class Connection {
public function __construct($db) {
return $this->connect($db);
}
private function connect($db) {
try {
if (! $db){
$db = new PDO ( 'mysql:host=localhost;dbname=Shopping;charset=utf8', 'xxxx', 'xxxxx' );
echo 'new connection';
}
return $db;
}
catch ( PDOException $conError ) {
echo 'failed to connect DB' . $conError->getMessage ();
}
}
}
here is the solution
pdo.php
class Connection {
// Declare instance
private static $instance = NULL;
// the constructor is set to private so so nobody can create a new instance using new
private function __construct() {
// maybe set the db name here later
}
// Return DB instance or create intitial connection #return object (PDO) #access public
public static function getInstance() {
if (! self::$instance) {
self::$instance = new PDO ( 'mysql:host=localhost;dbname=Shopping;charset=utf8', 'root', 'vss0ftech' );
self::$instance->setAttribute ( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
echo 'connected';
} else
echo 'connection is already existed';
return self::$instance;
}
// Like the constructor, we make __clone private so nobody can clone the instance
PRIVATE FUNCTION __CLONE() {
}
}
product.php
here we can call the method as like this
class ProductInsert {
public function prdInsert(.....) {
$result_By_Vendor_And_Title = Connection::getInstance ()->query ( "select * from........)
}
}

PHP Singleton Database Query

In PHP, I have following Singleton Database Class:
class Database
{
private static $instance;
private function __construct()
{
self::$instance = new mysqli('localhost', 'root', 'Matthias', 'financecontrol', '3307');
if (!self::$instance) {
throw new Exception('Could not connect to database in function __construct.');
}
}
public static function getInstance()
{
if (!self::$instance) {
self::$instance = new Database();
}
return self::$instance;
}
}
Whenever I try to perform a query on the database in another PHP file, for example to check whether a user already exists:
function userExists($username)
{
try {
$connection = Database::getInstance();
$result = $connection->query("select * from user where username='$username'");
if (!$result) {
throw new Exception("Connection to database failed in function userExists.");
}
if ($result->num_rows > 0) {
return true;
} else {
return false;
}
} catch (Exception $ex) {
$errorPager = new ErrorpageGenerator();
$errorPager->generateErrorPage($ex->getMessage());
return false;
}
}
I get an error message "PHP Fatal error: Call to undefined method Database::query() in User.php on line 44"
I've tried adding a query function in the Database class, but that did not seem to fix the problem. Any ideas? Thanks
You have to add this method of course. But you cannot assign Database() and the mySQLi object to m_pInstance
so do:
class Database
{
private static $conn;
// ...
public function __construct()
{
self::$conn = new mysqli('localhost', 'root', 'root', 'database', '3307');
//...
and then
public function query($sql)
{
return self::$conn->query($sql);
// or
return mysqli_query(self::$conn, $sql);
}
EDIT
Working code:
class Database
{
private static $instance = null;
private static $conn;
private function __construct()
{
self::$conn = new mysqli('localhost', 'root', 'root', 'database', '3307');
}
public static function getInstance()
{
if (self::$instance == null) {
self::$instance = new Database();
}
return self::$instance;
}
public function query($sql)
{
return self::$conn->query($sql);
}
}
You get this error, because Database::$m_pInstance is contains an instance of Database class and not instance of MySQLi. You have created a "conflict" between to parts of the code:
public static function getInstance()
{
if (!self::$m_pInstance) {
self::$m_pInstance = new Database(); // << PROBLEM
}
return self::$m_pInstance;
}
Which overrides what your constructor does:
private function __construct()
{
self::$m_pInstance = new mysqli( /* .. */ ); // PROBLEM
if (!self::$m_pInstance) {
throw new Exception('Could not .. blah');
}
else {
return self::$m_pInstance;
}
}
Even though the constructor assigns self::$m_pInstance the instance of MySQLi object, it gets overridden by self::$instance = new Database(); right after.
Also, in php __constuct() method should not return, ever.
That said, i think is should warn you that singleton is considered to be an anti-patterns, and should be avoided. Your code also has the unintended side-effect, forcing you to have only one database (not connection, the database) available per application.
You might benefit from watching few lectures:
Advanced OO Patterns (slides)
Global State and Singletons
Don't Look For Things!
Your code does not look right.
first, you assign $m_pInstance a new Database instance. But then, in the constructor, you assign it a new mysqli instance. I am unsure how php handles this case, but it seems that it treats it as Database object as indicated by your error message. The Database class however does not have a query method.
So the solution would be to save the mysqli object in a different field and add getters and setters for it or delegate the methods to it.

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);
}
}

Extending the MySQLi class

I want to be able to make classes which extend the MySQLi class to perform all its SQL queries.
$mysql = new mysqli('localhost', 'root', 'password', 'database') or die('error connecting to the database');
I dont know how to do this without globalising the $mysql object to use in my other methods or classes.
class Blog {
public function comment() {
global $mysql;
//rest here
}
}
Any help would be appreciated.
Thanks.
I was working on something similar. I'm happy about this singleton class that encapsulates the database login.
<?php
class db extends mysqli
{
protected static $instance;
protected static $options = array();
private function __construct() {
$o = self::$options;
// turn of error reporting
mysqli_report(MYSQLI_REPORT_OFF);
// connect to database
#parent::__construct(isset($o['host']) ? $o['host'] : 'localhost',
isset($o['user']) ? $o['user'] : 'root',
isset($o['pass']) ? $o['pass'] : '',
isset($o['dbname']) ? $o['dbname'] : 'world',
isset($o['port']) ? $o['port'] : 3306,
isset($o['sock']) ? $o['sock'] : false );
// check if a connection established
if( mysqli_connect_errno() ) {
throw new exception(mysqli_connect_error(), mysqli_connect_errno());
}
}
public static function getInstance() {
if( !self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
public static function setOptions( array $opt ) {
self::$options = array_merge(self::$options, $opt);
}
public function query($query) {
if( !$this->real_query($query) ) {
throw new exception( $this->error, $this->errno );
}
$result = new mysqli_result($this);
return $result;
}
public function prepare($query) {
$stmt = new mysqli_stmt($this, $query);
return $stmt;
}
}
To use you can have something like this:
<?php
require "db.class.php";
$sql = db::getInstance();
$result = $sql->query("select * from city");
/* Fetch the results of the query */
while( $row = $result->fetch_assoc() ){
printf("%s (%s)\n", $row['Name'], $row['Population']);
}
?>
My suggestion is to create a Singleton DataAccess class, instantiate that class in a global config file and call it in your Blog class like $query = DataAccess::query("SELECT * FROM blog WHERE id = ".$id).
Look into the Singleton pattern, it's a pretty easy to understand designpattern. Perfect for this situation.
Your DataAccess class can have several methods like query, fetchAssoc, numRows, checkUniqueValue, transactionStart, transactionCommit, transactionRollback etc etc. Those function could also be setup as an Interface which gets implemented by the DataAccess class. That way you can easily extend your DataAccess class for multiple database management systems.
The above pretty much describes my DataAccess model.
You can use PHP's extends keyword just for any other class:
class MyCustomSql extends mysqli {
public function __construct($host, $user, $password, $database) {
parent::__construct($host, $user, $password, $database);
}
public function someOtherMethod() {
}
}
$sql = new MyCustomSql('localhost', 'root', 'password', 'database') or die('Cannot connect!');
or better use object aggregation instead of inheritance:
class MySqlManipulator {
private $db;
public function __construct($host, $user, $password, $database) {
$this->db = new mysqli($host, $user, $password, $database);
}
public function someOtherMethod() {
return $this->db->query("SELECT * FROM blah_blah");
}
}
$mysqlmanipulator = new MySqlManipulator('localhost', 'root', 'password', 'database') or die('Cannot connect!');
My standard method is to make a singleton class that acts as the database accessor, and a base class that everything requiring such access inherits from.
So:
class Base {
protected $db;
function __construct(){
$this->db= MyDBSingleton::get_link();
//any other "global" vars you might want
}
}
class myClass extends Base {
function __construct($var) {
parent::__construct();// runs Base constructor
$this->init($var);
}
function init($id) {
$id=(int) $id;
$this->db->query("SELECT * FROM mytable WHERE id=$id");
//etc.
}
}
Have a look at PDO, which throw exceptions for you to catch if a query fails. It's widely used and tested so you shouldn't have a problem finding existing solutions whilst using it.
To inject it into your blog class:
class Blog {
private $_db;
public function __construct(PDO $db) {
$this->_db = $db
}
public function comment() {
return $this->_db->query(/*something*/);
}
}

Categories