Answer the question
In order to leave comments, you need to log in
Designing Database Classes in PHP
I am reworking an existing project, it has a lot of classes for working with the database, but they are designed, it seems to me, just awful.
class db
- a class for working with the database (connection, processing requests / results, monitoring the connection with the database)
class db_ext extends db
- a class containing many different functions that are not included in other classes.
class db_module_N extends db_ext
- model classes containing various functions associated with various system modules
I think that inheriting from a class ( db
) that is designed to work with the database is a bad practice. Accordingly, if we stop inheriting from it, then we need to separately create an instance of this class and pass it as a parameter to all classes that plan to work with the database.
Example:
$db_link = new db();
$db_module_N = new db_module_N($db_link);
$db_ext = new db_ext($db_link);
db
singleton, because sometimes it is necessary to create several connections to the database. class db_module_N1 extends db_module_N
function __construct($db)
{
parent::__construct($db);
}
Answer the question
In order to leave comments, you need to log in
Well, there are only 2 options here: either inheritance or composition (in one form or another). In order not to write with your hands constantly creating an embedded object and passing it to the constructor, you can look in the direction of dependency injection. There are, as I understand it, ready-made libraries for this matter, among which you need to look for something simpler. In general, here you need to google.
As for the fact that in the child's constructor you need to constantly call the parent's constructor, it's not very clear. If the child constructor does nothing else at all, then maybe it makes sense not to define it at all, in which case the parent constructor will be called automatically?
The model should not be connected in any way with the logic of working with the base. As an option - Models - separate classes that are tied to repositories - in fact, record managers. Each repository depends on a db class that is passed to its constructor.
As mentioned above, in order to simplify your life, you can use the DI implementation to manage dependencies. For example Pimple or, if a little more complicated, PHP-DI or some other.
In general, why not replace all this stuff with a ready-made ORM?
I do not want to make the db class a singleton, because sometimes it is necessary to create several connections to the database.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question