Answer the question
In order to leave comments, you need to log in
Php PDO database singleton. Which option to choose?
How to `kosherly` implement access to the database so that each time it is accessed, a new connection is not created? I see two options. First implement like this:
1. file Database.php
<?php
class Database extends PDO
{
function __construct()
{
parent::__construct('mysql:host=localhost;dbname=mydbname', username, password);
}
}
<?php
require_once Database.php;
class MyClas
{
function __construct()
{
$this->db = new Database();
}
function run()
{
$stmt = $this->db->prepare(....);
}
function callHook()
{
$stmt = $this->db->prepare(....);
}
}
Answer the question
In order to leave comments, you need to log in
Both options are disgusting.
Correctly establish a connection in one place, and then transfer it to where it is needed.
According to the first option:
1. Why is the Database class needed here?
2. Will you only have one class in the entire application? or more? And how many connections will there be after new myclass and new myclass2?
On the second.
Highbrows don't like singletons. Something he interferes with testing there. Plus religious intolerance. So only use a static singleton if your code is organized in classic procedural shit code.
If you have everything in the form of a kosher class hierarchy, then, as noted in another answer, pass the connection to the class, and do not create it again every time.
function __construct($db)
{
$this->db = $db;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question