[POC] Singleton/Static classes refactoring to dependency injection #5946
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This is a POC of the refactoring to get rid of singletons and static classes. This is the step 1 described in #4917.
Piwik\Db
was a static class, i.e. all its methods were static.I added
Piwik\Db\Db
(do you like the name? wouldDatabase
be better?) and moved the code ofDb
into it. This new class is not static, and uses dependency injection.Piwik\Db
is now a static proxy toPiwik\Db\Db
. So for example callingDb::fetchAll(...)
will be forwarded toself::$db->fetchAll(...)
(Db\Db
).We can now inject the non-singleton (
Db\Db
) into whatever (in theory). But before doing that, we'll need to move the creation of that object into a container (right now it's created inDb\getInstance()
).We can now also unit tests
Db\Db
without hitting any database, because we can pass a mock instance of the DbAdapter. Yay.Piwik\Access
was a singleton.I added
Piwik\Authorization\Authorization
and nowPiwik\Access
just forwards to this new class.I think it was probably a mistake to do that because it's not necessary, I just got carried away and thought the new name was more explicit (I didn't get what "Access" meant at first, authorization is more standard). But whatever no big deal, we can revert that.
So a better solution would be probably to have
Access
extendAuthorization
(if we want to keep that name and namespace) and it would just add the singleton access for BC compatibility. That would avoid useless call forwarding.If we don't want to rename it, then we can just keep
Access
as it is and then when we have a container just have thegetInstance()
call the container instead of creating the object directly.