douxinghuai3150 2010-05-19 19:09 采纳率: 0%
浏览 54
已采纳

数据访问层,最佳实践

I'm looking for input on the best way to refactor the data access layer (DAL) in my PHP based web app. I follow an MVC pattern: PHP/HTML/CSS/etc. views on the front end, PHP controllers/services in the middle, and a PHP DAL sitting on top of a relational database in the model. Pretty standard stuff. Things are working fine, but my DAL is getting large (codesmell?) and becoming a bit unwieldy.

My DAL contains almost all of the logic to interface with my database and is full of functions that look like this:

function getUser($user_id) {
   $statement = "select id, name from users where user_id=:user_id";
   PDO builds statement and fetchs results as an array
   return $array_of_results_generated_by_PDO_fetch_method;
}

Notes:

  • The logic in my controller only interacts with the model using functions like the above in the DAL
  • I am not using a framework (I'm of the opinion that PHP is a templating language and there's no need to inject complexity via a framework)
  • I generally use PHP as a procedural language and tend to shy away from its OOP approach (I enjoy OOP development but prefer to keep that complexity out of PHP)

What approaches have you taken when your DAL has reached this point? Do I have a fundamental design problem? Do I simply need to chop my DAL into a number of smaller files (logically divide it)? Thanks.

  • 写回答

2条回答 默认 最新

  • doushi6932 2010-05-19 19:28
    关注

    In terms of your architecture, each table in your DB should (generally) have its own model (PHP class), if you're not doing this, then I'd say you have a code smell.

    If you have each table as a model, then I wouldn't worry about the amount of code in each class. It's good to have "fat models" and "skinny controllers".

    If you wanted to thin out some code, you could use a lightweight data object wrapper, something like PEAR's DB_DataObject. A few examples of what a DB_DataObject model might look like:

    
    $user = new User;
    $user->get($user_id);
    
    
    $user = new User;
    $user->name = 'foo';
    $user->find();
    while($user->fetch()) {
    ...
    }
    

    The benefit of using something like DB_DataObject is you abstract away a lot of the low level PDO stuff and your class implementation will focus more on your business logic.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器