Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can we avoid including $db with every function that queries the $db? #15

Closed
bbertucc opened this issue Apr 13, 2022 · 2 comments
Closed
Labels
question Further information is requested

Comments

@bbertucc
Copy link
Collaborator

I didn't plan on making every $db call a function, but it happened.

Now I have to require models/db.php and $db every time I want to query the db.

I know that creates lots of redundancy.

Curious if there is a simpler solution?

@bbertucc bbertucc added the question Further information is requested label Apr 13, 2022
@ebertucc
Copy link
Collaborator

Yes: singletons and/or factories.

Creating a singleton class to wrap the database connection lets you initialize the connection once without having to then pass the connection around. This blog post has a pretty good breakdown of how this works.

Dependency injection is another option if you want to avoid singletons for testing/maintainability purposes, but imo it's 1) overkill if you don't want to support multiple DB engines at the same time (the singleton class still abstracts the DB logic from the rest of the app, so you can update in one place if desired later on), and 2) mostly proposed by people who hate on singletons due to cargo cult.

Relevant reddit discussion here.

ebertucc added a commit to ebertucc/equalify that referenced this issue Apr 20, 2022
@ebertucc
Copy link
Collaborator

Submitted a PR with one way this could look. Lemme know what you think.

bbertucc pushed a commit that referenced this issue Apr 21, 2022
Refactor to use static db connection as per #15
bbertucc added a commit that referenced this issue Mar 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants