I
I
Ivan Petrov2016-09-23 20:31:04
PHP
Ivan Petrov, 2016-09-23 20:31:04

How to use singleton db correctly?

Tell me how to do it right.
I'm trying to make the simplest cms according to the mvc pattern.
I want to create a database object only once. The Db class is a singleton.
Is it possible to do so?
$db = Db::getInstance();
The Db object is created only once, then its static methods are used in the controllers, for example:
$data= Db::getOne(1);
the desired variable is immediately assigned the desired data through a static method, which is then displayed in the template.
The question is where to create the Db class object? In the front controller, in the main controller itself, from which the rest will be inherited, or somewhere else?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey delphinpro, 2016-09-23
@bitande

Db::getInstance()->getOne(1)

D
dev400, 2016-09-23
@dev400

correctly use dependency inversion and pass the ready object of the connection class to the desired model. Singleton is an antipattern, why is it even here?

F
firm, 2016-09-23
@firm

> The question is where to create the Db class object?
The implementation of the connection to the database has nothing to do with the controller.
The Db class is the system class of your framework.
The question of where to place it is your preference, in my opinion it would be logical to place it, for example, in the systems folder. It all depends on how you have designed the logical structure of your framework.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question