Reputation: 21
So I've got a class for the caching system, a class for database connections, an array of app settings, a class for handling different languages, etc. These classes are all needed in most other classes I create
Is there a better way to handle it than to do this:
function __construct($database,$cache,$appsettings,$language,...) {
in every class I have? Another problem with this approach is that I can't make functions static if they need a database connection. So for example, I have a users class that right now has a "getUsernameFromID()" function, which uses the database to get that username. If I use the above approach, I would have to actually create a user class, every time some piece of code needs a username from an ID.
Singleton classes would be a solution to this, but other answers on here say that they are a bad practice in PHP. Right now I'm using globals for these classes, which is obviously a bad solution as well. What should I do?
I hope that was clear enough, I'm doing my best.
Upvotes: 0
Views: 59
Reputation: 12721
You probably want to look into the Dependency Injection and Service Locator design patterns. Pimple is a popular dependency injection manager.
Singletons aren't necessarily a bad practice. Many times we just use them badly. For example, a class that manages it's own "single-ness" can be considered an anti-pattern. It creates a dependency on itself and enforces that globally (outside it's own scope). It's better that the single-ness be managed by the framework or other object that can enforce it within a scope.
Upvotes: 1