Storing connection in a class variable - php

I am wondering how i can store my connection in a class variable and then keep reusing it ? Right now my code looks like this
This function sets up my Connection right now and is called everytime
function setDB()
{
$serviceAccount = ServiceAccount::fromJsonFile('firebase_credentials.json');
$firebase = (new Factory)
->withServiceAccount($serviceAccount)
->create();
$db = $firebase->getDatabase();
return $db;
}
This is one of my functions which needs the connection $db to get and update Data.
function Period($gameid, $action)
{
$db = setDB();
$reference = $db->getReference('games/'.$gameid.'/Clock/CurrentPeriode');
$value = $reference->getValue();
if ($action =='m')
{
$value = $value -1;
$db->getReference('games/'.$gameid.'/Clock/CurrentPeriode')
->set($value);
} else {
$value = $value +1;
$db->getReference('games/'.$gameid.'/Clock/CurrentPeriode')
->set($value);
}
}

The solution is using Singleton pattern:
class DbConn
{
private $db;
protected function __construct()
{
$serviceAccount = ServiceAccount::fromJsonFile('firebase_credentials.json');
$firebase = (new Factory)
->withServiceAccount($serviceAccount)
->create();
$this->db = $firebase->getDatabase();
}
public function getInstance()
{
static $instance;
if (!$instance) {
$instance = new self();
}
return $instance;
}
public function getDb()
{
return $this->db;
}
}
And usage will be looking like this:
function Period($gameid, $action)
{
$db = DbConn::getInstance()->getDb();
$reference = .....

You can make setDB() into a singletron class and thus archive what you want.

Everyone here is saying use the singleton pattern. I'm going to say no don't use it as an answer: Read here and here.
Instead I would use a different approach: dependency injection. Use that paradigm and instantiate your classes upon initial load and then you use that to abstract your db layer from your logic making it easier to query rather than having to access that part every time you want to query or make changes like what you're doing now.
After all said and done, your logic should look something like this in the end:
// in your top configuration that gets loaded with your framework
// probably in it's own config file
$Factory = new Factory();
$serviceAccount = ServiceAccount::fromJsonFile('firebase_credentials.json');
$DbContext = new DbContext($Factory, $serviceAccount);
// somewhere in your app
$GamesRepository = new GamesRepository($DbContext);
// your logic in some function or part of the app
$gameId = 1;
$value = $GamesRepository->getCurrentPeriode($gameId);
$action == 'm' ? $value++ : $value--;
$GamesRepository->setCurrentPeriode($value, $gameId);
Because your repository is handling all the db conn stuff using another class that has the db connection handled from initial load of the page, you can just continue to use some kind of model or repository to fetch the info you need. I can expand on this but I think you should just think about your architecture a little and make a stab at it with what you know already if you decide the singleton pattern is not the best use case or want to try a different approach given it's downsides.

Related

Singleton v Single Instance DB Connection in PHP

I'm moving onto teaching myself OOP in PHP.
I'm creating a couple of little web apps and have followed a lot of tutorials that either create the database (using PDO) via a Singleton, or via passing the global around. I've read that these are pretty much the same thing and are both to be avoided like the plague.
So I've watched the Google Tech Talks on clean code, and read almost every SO article on dependency injection and the like. I have a couple of questions.
The clean code videos suggest you shouldn't do 'work' in your constructors. Is this 'work' in reference to business logic. Ie. If my class's job is to create another object, is that an OK kind of 'work'?
For example, in trying to conform to single repsonibility classes I created three.
Class DB - which actually connects to the database.
Class DBFactory - which creates the DB object which connects to the database.
Class DBInstance - which returns a single instance of the DBFactory created PDO object.
Please note that I'm trying to create a single instance, without creating a Singleton pattern.
So I try and pass my dependencies for each class up the chain. I find myself in a position where I have to create all of the objects (from DB down) so I can inject the dependencies. For some reason I thought it would work the other way, I'd create the first object, which would create the second for me etc. I'm clearly missing something?
Hopefully this helps others as well - there seems to be a myriad of questions relating to this stuff and databases but very little good examples.
(I should mention this does work, I do get a list of hotel names out of the database!)
TestCode.php
include './classes/DB.php';
include './classes/DBFactory.php';
include './classes/DBInstance.php';
include './classes/Location.php';
$db = new DB;
$dbfactory = new DBFactory($db);
$dbinstance = new DBInstance($dbfactory);
$dbh = $dbinstance->getDbInstance();
//Example business logic
$location_names = Location::getLocationNames($dbh);
print_r($location_names);
Class DB.php:
class DB {
private $_dbhost = 'myhost';
private $_dbname = 'myname';
private $_dbuser = 'myuser';
private $_dbpass = 'mypass';
private $_error;
public function connect() {
try {
return new PDO("mysql:host=$this->_dbhost;dbname=$this->_dbname",
$this->_dbuser, $this->_dbpass);
}
catch (PDOException $e) {
$this->_error = 'Error! ' . $e->getMessage() . '<br />';
die();
}
}
public function getError() {
if (isset($this->_error)) {
return $this->_error;
}
}
}
Class DBFactory.php
class DBFactory {
private $_dbh;
public function __construct(DB $db) {
$this->_dbh = $db;
}
public function Create() {
return $this->_dbh->Connect();
}
}
Class DBInstance.php
class DBInstance {
private static $_dbinstance;
public function __construct(DBFactory $dbfactory) {
if (!isset(self::$_dbinstance)) {
self::$_dbinstance = $dbfactory->Create();
}
}
public function getDbInstance() {
return self::$_dbinstance;
}
}
Your code seems to do what you want it to.. but maybe we can use less object instantiation using inheritance and maybe we can avoid static properties in instanciated classes.
Also in regard to using a pattern of dependency injection that is able to handle multiple connections, but support using a single instance of it. exemple first, classes after
$params = array
('host'=>'localhost',
'db'=>'ice',
'user'=>'kopitar',
'pass'=>'topnet',
'charset'=>'utf8'); // passing the charset explicitely is great
$handle = new handle($params);
$db = $handle->getInstance();
we can either pass the $db to our functions
$location_names = Location::getLocationNames($db);
or the whole $handle. as long as $handle is not reconstructed, it will always return the same database connection.
$location_names = Location::getLocationNames($handle);
if I want to reconstruct I need the whole $handle
$handle->__construct(/* params but with another database infos */);
$db2 = $handle->getInstance();
As for the classes, I think we want the params to arrive from the instanciated class, so we can change them later.
class db {
function __construct($params) {
foreach ($params as $param => $value) {
$this->{$param} = $value; // assigns the connections infos
}
}
protected function connect() {
$dsn = 'mysql:host='.$this->host.';dbname='.$this->db.';charset='.$this->charset;
return new PDO($dsn,$this->user,$this->pass);
}
}
the factory creates a connection from params and passes it to something else, good factory
class factory extends db {
protected function create() {
return $this->connect();
}
}
now we want to have our object to keep it's connection as long as we do not rebuild it. so we give it to instance
class instance extends factory {
function instantiate() {
$this->instance = $this->create();
}
}
and last but not least, our handle which returns the instance. it could be in instance class.....................
but I feel like having four and find no real reason not to.
class handle extends instance {
function __construct($params) {
db::__construct($params);
$this->instantiate(); // when we construct a handle, we assign an instance to the instance property
}
function getInstance() {
return $this->instance;
}
}
KISS
Don't make things more complex than they are, of course this is just my opinion, but as I see it you are building a complex solution for a problem that someone else says might exist is some cases.
Php is not multi threaded so there goes one of the biggest arguments overboard. (in very rare-occasions it might be)
I'm using singletons for my database connections for about 15 years now and never ever had a problem with them, I do play around with different connections having one singleton handle several connection instances, but whatever... it works great and everyone that looks at the code.. understands it directly.
I'm not using globals because they can be overwritten and are kind of hard to predict (when it holds the correct object, and when/why they don't)
Use OOP to make your code cleaner, easier to work with and more flexible.
Don't use it to fix problems that aren't there and make your code more complex because others tell you to.
An very simple example of a db-connection singleton class handling several different connections.
class singleton{
private static $_instances=array();
public static function getInstance($connectionName){
if(!isset(self::$_instance[$connectionName]){
self::$_instance[$connectionName]=self::_getConnection($connectionName);
}
return self::$_instance[$connectionName];
}
}
just my 2 cents
Why do you have a factory if you have a singleton? This is needless.
This is a never-ending debate, but I'm advocate of do not use singletons for database connections.
As far as in most applications, you have only one data channel, you can consider your database connection unique, but this might not be always true.
In deed, the effort made to create a singleton database connection is even bigger than just create a regular one.
Also, your class DB is not configurable, therefore, you need to change it when your connection parameters change. And I think DB is a very bad name for this.
I'd rather call this Storage and do something like:
inteface Storage {
public function insert($container, array $data);
public function update($container, array $data, $where);
public function delete($container, $where);
public function getAll($container);
public function getOne($identifier);
}
final class PdoStorage implements Storage {
private $dbh;
private $dsn;
private $user;
private $pswd;
public function __construct($dsn, $user, $pswd) {
$this->dsn = $dsn;
$this->user = $user;
$this->pswd = $pswd;
}
// Lazy Initialization
private function connect() {
if ($this->dbh === null)
$this->dbh = new PDO($this->dsn, $this->user, $this->pswd);
}
public function insert($container, array $data) {
$this->connect();
// ... omitted for brevity
}
}
Now, when you need a database storage, you do:
$someObj = new SomeClass(new PdoStorage(...));
Now you might be wondering if you will need to create an PdoStorage for each single object that depends on it.
The answer is: no!
Now you can use a factory to simplify your life.
class SomeFactory {
private $defaultStorage;
public function __construct(Storage $storage) {
$this->defaultStorage = $storage;
}
public function create($type) {
// Somehow fetches the correct class to instantiate and put it into $class variable , for example... and then
return new $class($this->defaultStorage); // Or you'd better do this with reflection
}
}
$factory = new SomeFactory(new PdoStorage(...));
$factory->create('SomeClass');
This way, you can have just one database connector or more if you need.

Assistance with OOP, PDO Shopping Cart Class [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the best method for getting a database connection/object into a function in PHP?
Database and OOP Practices in PHP
I am trying to build an OOP shopping cart.
At present, it is half OOP, and half procedural... e.g.
function removeFromCart() {
require_once('/.../.../connectPDO.php');
$db = connectPDO();
$sql = 'DELETE FROM Quotes WHERE User = :user and ProductId = :pid';
$stmt = $db->prepare($sql);
$stmt->execute(array(':user' => $user, ':pid' => $pid));
}
My problem is that if I wish to add to cart, then in my function addToCart, I will need to require the db connection again.
This seems like a complete waste, considering every function will need to contain the following:
require_once('/.../.../connectPDO.php');
$db = connectPDO();
I am aware that this is completely in-efficient, and was wondering if anybody could help me write a skeleton OOP cart class which uses the above connection to connect to the DB?
Does this go in the constructor??? Will this stay alive when a user navigates from one page to another at the front end?
I am new to OOP and am completely lost.
Many thanks in advance.
Something like the following should get you started:
$pdo = new PDO('your dsn');
$cartData = new CartData($pdo);
$cart = new Cart($cartData);
class CartData
{
private $dbConnection;
public function __construct(PDO $dbConnection)
{
$this->dbConnection = $dbConnection;
}
public function removeItem($userId, $productId) {
$sql = 'DELETE FROM Quotes WHERE User = :user and ProductId = :pid';
$stmt = $this->dbConnection->prepare($sql);
$stmt->execute(array(':user' => $userId, ':pid' => $productId));
}
}
class Cart
{
private $cartData;
public function __construct(CartData $cartData)
{
$this->cartData = $cartData;
}
public function removeItem($userId, $productId) {
$this->cartData->removeItem($userId, $productId);
}
}
Note that I have removed the database calls from the actual Cart class, because that would only make it hard / impossible to swap to another database engine at some point. Or perhaps you might want to introduce a complete other way of storing your data (ahum unit testing). Also note that I have used dependency injection to give the classes the objects they need to be able to perform whatever it is they are responsible for.
I have used type hinting for the class objects which are being injected, however it would have been better to type hint against an interface, because that would make it easy to swap out the classes for other classes. And I strongly suggest you use interfaces (what I wrote above is simply an example to get the idea). This also make it pretty easy to created unit tests for your code.
At every page request, you make a new database connection. You can't share a connection between requests.
There are a couple of different design patterns (best practises) for handling this. For all of them, you need a DB abstraction layer (like PDO, Doctrine DBAL or something else).
Dependency Injection (recommend)
The most used design pattern to handle this is dependency injection:
class Foo
{
/**
* #var DatabaseAbstractionLayer
*/
private $dbal;
public function __construct(DatabaseAbstractionLayer $dbal)
{
$this->dbal = $dbal;
}
public function methodThatUsesTheDbal()
{
$this->dbal->query(...);
}
}
$db = new DatabaseAbstractionLayer();
$foo = new Foo($db); // constructor injection
$bar = new Bar();
$bar->setDbal($db); // setter injection
$baz = new Baz();
$baz->dbal = $db; // property injection (almost never used)
You can use a service container to handle this easily (example with pimple):
$container = new Pimple();
$container['db'] = $container->share(function ($c) {
return new DatabaseAbstractionLayer();
});
$container['foo'] = function ($c) {
return new Foo($c['db']);
};
$foo = $container['foo']->methodThatUsesDbal();
Singleton
class DatabaseAbstractionLayer
{
private static $_instance;
// ...
private function __construct()
{
// ...
}
// ...
public static function getInstance()
{
if (null === self::$_instance) {
self::$_instance = new static();
}
return self::$_instance;
}
}
class Foo
{
public function methodThatUsesDbal()
{
$db = DatabaseAbstractionLayer::getInstance();
// ...
}
}
Registery
Registery::set('db', new DatabaseAbstractionLayer());
class Foo
{
public function methodThatUsesRegistery()
{
Registery::get('db');
// ...
}
}

how to use more model in MVC

As i know in MVC, Model always connect to database, example:
class a extends Model {
...
}
class Model {
public function __construct() {
$db = new database;
$db->connect('localhost','root','','example');
}
}
But, in the case i have more Model always run to get config in database. So, when run website will be 2 Model are used.
This equivalent to 2 connect to database so its has effect to system when have many people visit my website (200 request = 400 connect to database)
About model
Actually model is not at class in the first place. Model is a layer, which contains multitude of objects. The two main groups of class instances in model layer are tasked with one of following responsibilities:
domain business logic and rules: implemented by domain objects (1) (2)
data access and persistence: usually implemented as datamappers (3)
In code it would looks something similar to this:
$user = $factory->buildObject('user');
$mapper = $factory->buildMapper('user');
$user->setId( 42 );
$mapper->fetch($user);
$now = time();
if ( $user->hasStatus( User::STATUS_LOCKED ) && !$user->isBanned( $now ) )
{
$user->setStatus( User::STATUS_AVAILABLE );
}
$mapper->commit($user);
As you might notice, at no point the business object actually interacts with database. Or is even aware of it. It might be that the information is stored in a plain text file, or via remote REST API, or in some noSQL thing. Domain object does not care about that. All the storage is handled by the mapper. The business logic that governs the making of invoice does not depend on location where the information about invoice comes from.
About connections
Since you are using OOP, you might take advantage of it. Consider this example:
class Test
{
protected $ob = null;
public function __construct( $ob )
{
$this->ob = $ob;
}
public function get()
{
var_dump( $this->ob->data );
}
public function set( $val )
{
$this->ob->data = $val;
}
}
$object = new stdClass;
$foo = new Test($object);
$bar = new Test($object);
$foo->set('lorem ipsum');
$bar->get();
To see executed: http://codepad.org/coCibwyk
You should notice, that both instances of Test class are sharing the same instance. In your code, you can do the same with instance of PDO.
And if you are using something similar to first code snipped , then :
class Factory
{
protected $connection = null;
public function __construct( $connection )
{
$this->connection = $connection;
}
public function buildMapper( $className )
{
$className = $className . 'Mapper';
$instance = new $className ;
$instance->useConnection( $this->connection );
return $instance;
}
// ... some other code
}
So, when you use $mapper = $factory->buildMapper('user'); , the method creates an object, which already has a connection.

I think I'm doing it wrong (PHP Class creation & signs and more)

Currently I have a class called user that I want to create with different variables, but I think I'm doing it wrong.
Currently I have a class "Unit" with these two functions
public function __construct($table, $id) {
require_once('database.php');
require_once('app.php');
require_once("postmark.php");
$this->table = $table;
$this->valid = true;
if(!$id) {
$this->valid = false;
}
$this->populate($id);
}
public function populate($id) {
$db = new DB();
$q = $db->where('id', $id)->get($this->table);
$resp = $q->fetchAll();
foreach ($resp as $row) {
foreach ($row as $key=>$value) {
if(!is_int($key))
$this->$key = html_entity_decode($value, ENT_QUOTES);
if(is_null($value)) {
$this->$key = null;
}
}
}
if(count($resp) <= 0) $this->valid = false;
$verdict = !$db->error;
$db = null;
unset($db);
return $verdict;
}
And then my "User" class extends it like so
public function __construct($id, $hash = null, $verify = null, $api = null) {
if($api)
$value = $this->apiToId($api);
else if($verify)
$value = $this->verifyToId($verify);
else if($hash)
$value = $this->hashToId($hash);
else
$value = $id;
parent::__construct("users", $value);
}
But I can't help but think this is poor in design. A few things I have seen in the past are the use of ampersands, possibly making it so I could do
$user = new User()->fromId($id);
Or
$user = new User()->withHash($hash);
Instead of passing it a long list of null params. That or I could improve the way inheritance works. While I like to think I know what I'm doing with PHP, I'd really like some help looking in the right direction. PHP's docs are so cumbersome, that I never no where to look, but always find cool useful tools. I'm wondering how I can improve this for more flexibility and structure.
Move includes to the very top of your php file. Anything that needs to be conditionally included is probably poorly designed.
Your unit class should be declared as abstract. This prevents anyone from instantiating a unit. You can only declare subclasses of it.
Any functions relating to your class should be declared as methods. Thus, the example given in an answer now-removed is a terrible choice. The function alloc really should be a static function defined in User. Code snippet at bottom.
Your init functions should be declared as static and return a new instance of the class. Defining an instance of the class to re-instantiate the class is just a bad idea.
Your database connection should use a Singleton pattern. Look it up if you need to.
Post your full code and comment on this answer if you'd like some help implementing all of this.
$user = User::initWithHash($hash);
//your create method:
/**
* Creates and returns a new instance of the class. Useful
* #return an instance of User.
*/
public static function create() {
return new User();
}

Database and OOP Practices in PHP

Its difficult to explain this situation but please see the example.
I have coded a website where the page loads, I initialize a database class. I sent this class as a function parameter to any functions that needs to access database.
I know this is bad approach but currently I have no clue how to do this any other way. Can you please help me.
Example
class sms {
function log_sms($message, $db) {
$sql = "INSERT INTO `smslog` SET
`mesasge` = '$message'
";
$db->query($sql);
if ($db->result)
return true;
return false;
}
}
then on the main page..
$db = new db(username,pass,localhost,dbname);
$sms = new sms;
$sms->log_sms($message, $db);
Is there any better approach than this ?
there are number of options how to resolve dependencies problem (object A requires object B):
constructor injection
class Sms {
function __construct($db) ....
}
$sms = new Sms (new MyDbClass);
setter injection
class Sms {
protected $db;
}
$sms = new Sms;
$sms->db = new MyDbClass;
'registry' pattern
class Registry {
static function get_db() {
return new MyDbClass;
}}
class Sms {
function doSomething() {
$db = Registry::get_db();
$db->....
}}
'service locator' pattern
class Loader {
function get_db() {
return new MyDbClass;
}}
class Sms {
function __construct($loader) {
$this->loader = $loader;
function doSomething() {
$db = $this->loader->get_db();
$db->....
}}
$sms = new Sms(new Loader);
automated container-based dependency injection, see for example http://www.sitepoint.com/blogs/2009/05/11/bucket-is-a-minimal-dependency-injection-container-for-php
interface DataSource {...}
class MyDb implements DataSource {...}
class Sms {
function __construct(DataSource $ds) ....
$di = new Dependecy_Container;
$di->register('DataSource', 'MyDb');
$sms = $di->get('Sms');
to name a few ;)
also the Fowler's article i gave you before is really worth reading
For starters you can make a protected $db variable in each of your classes that need to utilize the database. You could then pass $db in to the class constructor. Here's the updated code:
$db = new db(username,pass,localhost,dbname);
$sms = new sms($db);
$sms->log_sms($message);
class sms {
protected $db;
public function __construct($db) {
$this->db = $db;
}
public function log_sms($message) {
$sql = "INSERT INTO `smslog` SET
`mesasge` = '$message'
";
$this->db->query($sql);
if ($this->db->result)
return true;
return false;
}
}
This example is in PHP 5.
Singleton is also good practice in application design. They are very useful to avoid repeated queries or calculations during one call.
Passing Database object to every method or constructor is not a very good idea, use Singleton instead.
extend your database, or insert static method inside your db class. (I would also call for config within db constructor method)
class database extends db
{
public static function instance()
{
static $object;
if(!isset($object))
{
global $config;
$object = new db($config['username'],$config['pass'],$config['localhost'],['dbname']);
}
return $object;
}
}
make your method static
class sms {
public static function log($message) {
$sql = "INSERT INTO `smslog` SET `mesasge` = '$message'";
database::instance()->query($sql);
return (bool) database::instance()->result;
}
}
Next time you need to log sms just do static call like this
sms::log($message);
You could either have a static class that has two lists, one of available connections, the other of handed out connections, and just have a connection pool.
Or, if you are using something that has a quick connection time, such as MySQL, then just create the connection in your database class, do all the queries needed for that functionality, then close it. This is my preferred approach.

Categories