普通网友 2010-08-04 15:59
浏览 30
已采纳

数据库访问抽象类

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!

  • 写回答

1条回答 默认 最新

  • dsajkdadsa14222 2010-08-04 16:06
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ESP8266连接阿里云出现问题
  • ¥15 被蓝屏搞吐了,有偿求帮解答,Ai回复直接拉黑
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并