drsdvwsvo78320812 2009-03-30 09:37
浏览 56
已采纳

如何管理数据层中的SQL语句

in a PHP project we already have separated business logic from database access. All database tasks are encapsulated in different database classes grouped by database and topic. Theses classes look very horrible, half the source are SQL strings, that get filled with params and so on. We thought of putting the SQL in "other" locations like resource files or something. What is considered best practise for this and do you know any supporting tools/libs for PHP?

Kind Regards

Stephan

  • 写回答

4条回答 默认 最新

  • dpwdldgn43486 2009-03-30 11:42
    关注

    You should use stored procedures wherever it is possible. That way you enhance performance, security and code maintenance. This should be your first approach.

    If you still want to separate the SP queries from the DAL, why not store them in a database? It may seem odd to store SQL queries in the database for abstraction, since a query is needed to extract other queries. This is actually a quite common approach, where you can select queries matching a certain criteria and possibly (if necessary) to build up the queries dynamically.

    Another approach may be to create Query-classes where queries are built up dynamically;

    class FruitQuery {
        ...
        public function addTypeCriteria($type) {
            $this->internalSQLCriterias[]  = "fruit=:type";
            $this->internalSQLParameters[] = array(':type', $type);
        }
        ...
        public function create() {
            $this->internalSQLQuery = "SELECT ... FROM Fruits";
    
            if (sizeof($this->internalSQLCriterias) > 0) {
                $this->internalSQLQuery .= " WHERE ";
                $moreThanOne = '';
    
                foreach ($this->internalSQLCriterias as $criteria) {
                    $this->internalSQLQuery .= $moreThanOne . $criteria;
                    $moreThanOne = " AND ";
                }
            }
        }
        ...
        public function execute() {
            /* Bind the parameters to the internalSQLQuery, execute and return results (if any) */
        }
    ...
    

    This class is absolutely not complete in any way, and you might want to rethink the structure of it - but you probably get the point I'm trying to make. :) Of course you have to filter the input to the Query-builder to avoid security breaches!

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

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥15 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备