S
S
serjioms2015-03-01 22:37:20
PHP
serjioms, 2015-03-01 22:37:20

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

2. conditionally index.php file
<?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(....);
    }
}

the second is to implement the Database class as singleton.
Tell me who has been writing in php for a long time. Is it true that when using the first option, a new connection will not constantly be established. And if implemented via singleton, how `kosher` to do it using PDO. Well, or is there some other reliable and simple option. Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
OnYourLips, 2015-03-01
@serjioms

Both options are disgusting.
Correctly establish a connection in one place, and then transfer it to where it is needed.

F
FanatPHP, 2015-03-01
@FanatPHP

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 question

Ask a Question

731 491 924 answers to any question