Database access abstraction classes
Currently, I have a database access class named DB
, which uses PDO
. I Then have a handful of sub-classes for accessing each table:
Users
Images
Galleries
Text
Videos
This was nice when I first started my project, but now I'm not sure if it's that great, as I have a method for each database query that I use within each of these classes. For example:
Images::insertNew($filename)
Images::getTotalInGallery($galleryId)
Images::getAllInGallery($galleryId, $fetchStyle)
Images::updateDescription($imageId, $description)
Images::updateGallery($imageId, $galleryId, $orderNum)
Images::getSingle($imageId)
Images::getFilename($imageId)
Images::getImageIdByFilename($filename)
Galleries::getNameById($galleryId)
Galleries::getAll()
Galleries::getMaxImages($galleryId)
Galleries::checkIfExists($galleryId)
Galleries::createNew($galleryName)
Galleries::getById($galleryId)
Galleries::delete($galleryId)
Well, you get the idea. I have been adding these methods as the need for them arises, and in development, I start by just using the DB
class:
//Execute a query
DB::query($query);
//Get a single row
$row = DB::getSingleRow($query);
//Get multiple rows
$rows = DB::getMultipleRows($query);
So, I test queries with my DB class, then when they are working, I wrap them in a method of the class that is related to it (Image class for images table, Galleries class for galleries table, etc.).
I feel like this will keep growing and growing as I add new features later on (which may be OK, but I'm not certain). Can anybody critique my 开发者_运维问答method and/or provide alternative solutions?
Thanks!
No, this actually sounds pretty good. You seem to have a solid abstraction layer between business logic and data access (This is called Data Mapper pattern).
The only problem with this getting big is, that you might end up with methods that overlap. You should also try to maintain a standard naming convenction across both classes.
In Images the method is Images::insertNew and in Galleries it is Galleries:createNew.
Do you actually have models? Because what it looks like is that you have a lot of queries to assemble single values, but not whole objects.
精彩评论