PHP Database class with singleton pattern [closed]

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



PHP Database class with singleton pattern [closed]



Is it a good practice to create query function inside Database class (which must be created with singletone pattern). Or better create another class with database interface, or something like that, and get database instance in constructor? (Sorry for my English :)


<?php
class Database

private static $_pdo = null;

private static function getDatabase()
if (self::$_pdo === null)
self::$_pdo = new PDO("mysql:host=localhost;dbname=contact_manager", 'root', '');


return self::$_pdo;


public static function query($query, $parameters)
Database::_toArray($parameters);
$query = self::getDatabase()->prepare($query);
$query->execute($parameters);
$result = $query->fetchAll(PDO::FETCH_ASSOC);

return $result;


private static function _toArray(&$parameters)
if (!is_array($parameters))
$parameters = array($parameters);



private function __construct()
private function __clone()
private function __wakeup()

?>



Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.




1 Answer
1



This is very wide theme is it good practice or not. As for me there're can be some points of view.



If you don't plan extend your project with another databases which queries should be called via same interface - this solution is OK



If we look at this from SOLID's point of view this is bad decision. According to SOLID you have to separate DB connection from queries. This is because of D-principle (dependency inversion) + S-principle (single responsibility). Also you have to define your own DatabaseInterface which you will use for injection your connection into Repositories - classes which encapsulate your DB queries.


DatabaseInterface


Repositories



However, this decision also depends on size of your project and your goal. If you just want to make everything right instead of inventing your own brand new bicycle, just take some framework like Symfony or Laravel and forget about this low-level stuff.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard