The project I am working on for about a year now was used to create a new mysqli connection to the database each time there was a Query to the database. In order to quickfix this problem at places where this strategy had some serious performance issues I created a global
$connection variable that deliveres a PDO instance.
However we also have some other data stored in
$SESSION which is heavily used on almost every SQL-Query. Therefore we call something like
$SESSION['xyz']->getLogin()->getUUID() in most of our methods that contain a SQL-Query.
So after about a year of delivering reusable code to the project, so that my team recognizes how easy and less unnerving implementing new features has become, i finally convinced them to take the next step and refactor our php code to some unified MVC-Code and even start using Interfaces (hurray!) and some additional design patterns. (So, finally I will be able to start using PHPUnit effectively)
So I decided to drop the singleton for our database connection and switch to dependency injection and also add an abstract base class that all our model classes will have to inherit from (there also is an abstract base class for all controllers). Since PHP only allows one constructor, I switched to static methods that return a new Instance of its class and also do some initial operations on the instance ( like
User:createByUUID( string $uuid ) and
User::createByEmail( string $email ) both loading user data from the database. )
Now, some data like the pdo and the UUID won't change during one request. So I'd like to inject these only once instead of injecting this data into every instance. My idea was to have a public static final method
addStaticDepenendcy( ... ) and also
getStaticDependency( ... ) to the abstract base class, that stores the Dependency in a static variable so Dependencies can be injected to all classes with a single command the moment they are created.
For all other dependencies that might come I will add some
getDependency() method to manage individual dependencies.
I also have some simple data (like the UUID), that is needed in (almost) all classes, so I would handle that the same way I handle dependencies even if they are just some integer or string.
Is this a 'good practice' to handle all dependencies? What problems could I run into with this strategy? Are there smarter ways to do this?