Jo Smo Jo Smo - 3 months ago 60
MySQL Question

Is it a good idea to put all database related methods into one class?

Would it be a better design to put all the database communication into one class or use it accross the whole program?


It's a good idea to follow Single responsibility principle (SRP), so you could have well defined roles/responsibilities for your classes. Don't have a class doing too many things.

Also consider Separation of concerns which simply put, is about having a clear separation between different parts of the application, such as templates, data and logic.

You can have a data/model layer that deals with the data of your application, without getting in the way of logic.

For example, have a DataMapper class for different entities in the system. The DataMapper could be responsible for interfacing with the database, pulling data, inserting and updating. This would be where the SQL lives, or the code to deal with some other storage mechanism if it didn't happen to be MySQL.

The benefit of this is in your logic code, you don't clutter it up with SQL statements all over the place, you simply call the DataMapper.

Quick example:

$userMapper = new UserMapper($db);
$users = $userMapper->getAll();

Note how the database object is passed to the mapper, this is Dependency Injection.