A
A
Andy912017-02-05 19:38:47
PHP
Andy91, 2017-02-05 19:38:47

PHP. Singletone for pdo. How to implement?

Good afternoon! I’m just starting to learn php and I’m still weak in design patterns, I came across a bunch of different options on the net, but they are all kind of strange ....
And the questions arise:
1) Do I need to use this pattern for the database at all? And why is creating a lot of PDO objects scary?
2) As I understand it, when a child class inherits a PDO class, it is impossible to override the access identifier to protected for __construct?
I wrote the following class to implement singletone:

class DB  {

    static $db;
    static $instance;

    protected function __construct($dsn,$username,$password,$options) {
        self::$instance = new PDO($dsn,$username,$password,$options);
    }
    
    public static function getInstance($dsn,$username,$password,$options) {
        if(self::$instance instanceof PDO){
            return self::$instance;
        } else {
            if(self::$db instanceof self){
                exit('Ошибка работы БД!') ;
            } else {
                self::$db = new self($dsn, $username, $password, $options);
                return self::$instance;
            }
        }
    }
}

It seems to work correctly, but I would be happy with constructive criticism addressed to him with explanations!)))

Answer the question

In order to leave comments, you need to log in

5 answer(s)
F
FanatPHP, 2017-02-06
@Andy91

Ответ на этот вопрос очень простой.
- Если ты пишешь процедурный код, то в синглтоне нет никакого вреда, а только одна польза.
- Если же ты пишешь объектный код, то синглтон тебе просто не нужен, поскольку в объект при создании всегда можно передать инстанс класса для работы с БД и присвоить переменной класса.
по поводу реализации
1. Как уже сказали выше, какой-то странный метод getInstance(). Если каждый раз вызывать с парасетрами, то какой вообще смысл в синглтоне? Сделай хотя бы два метода, один коннект, а второй гетинстанс.
2. Не очень понятно почему две статические переменные, и какая за что отвечает. почему бы не оставить одну?
3. If we are going to make a singleton, then it is better to get rid of unnecessary writing and refer directly to methods for working with the database: `DB::insertId()` will be more convenient than `DB::getInstance()->insertId()`
4 Given the inconvenience of the PDO::execute() method, it will be useful to tweak the classics and add a method that will execute the request with parameters and return the statement. An example can be seen here: https://phpdelusions.net/pdo/pdo_wrapper

O
OnYourLips, 2017-02-05
@OnYourLips

1) Do I need to use this pattern for the DB at all?
No. Very often you need several connections to the DBMS.
In addition, a singleton is an anti-pattern that masks dependencies.
And why is creating a lot of PDO objects scary?
You don't need several of the same. Create a connection once, and then just pass it to other classes. For example, through the constructor.

M
McBernar, 2017-02-05
@McBernar

The next time you're told that a singleton is an antipattern or "masks dependencies" - ask that person to show you a real-life example of a singleton masking dependencies.

S
synapse_people, 2017-02-06
@synapse_people

What is the point of such a static method if it takes all constructor parameters?
Move the creation of the PDO object to a public method. To get something like this:
$db = DB::getInstance();
$db->connect(host,port,db.....);
Even better, if the DB will inherit (extends) PDO.
then make a DbAware interface with a setDb method - for all other classes that will use the database. And shove it all into some kind of dependency container.

N
Nikolai Konyukhov, 2017-02-06
@heahoh

Look here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question