2

I am trying to write a web app in the MVC pattern and I wanted to know if it is good practice to have one class with all of the database calls that will be used by the application in this class.

Then just create an instance of this class when you need it?

Or is it better to mix database calls into any particular class (model or controller) that needs to access the database?

3 Answers 3

1

Hmm, this is a good question. It would be more of a personal opinion but what I typically do is create a single Database object to handle all db calls and then I create different db objects for what I need. For example, I would create a UserDB object and place the DB calls in it unique for user's. If you have user groups you could also create a UserGroupDB object and use that to call all the db queries you need. This allows your code to be easily read and can be used in multiple parts of your system while only keeping the DB logic in a single location. You don't want to create a single DB object with all your DB queries as this would be obvious overhead as most of the queries will not be required for all the pages within he system.

I hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

1

Normally, data access is handled by the model but there are instances where the model is not synonymous to data access layer.

for cleaner code, it might be wiser to create an abstract class that will handle your data access layer and concrete classes for each model that you have.

Comments

0

In my practice, the data access object, DAO for short, only is different in SQL. So, use one DB object to encapsulate the query, including select and modify(update, insert and delete), then different table or module has different DAO to build its specical SQL and use the DB object to do the query.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.