1

I've made this class to handle all of my sql-queries. But I'm unsure of how to use it properly.

The class looks something like this (this is a VERY simple version of it):

class sql {
    private $conn;
    private $data;

    function __construct() {
        //makes connection to DB and sets $conn and $data
    }
    public function select($variables, $table, $criterias) {
        //returns an array with all the info from DB
    }
    function __destruct() {
        //closes the sql-connection
    }
}

The question now is: Is this going to overload the DB, if I use it multiple times on every page-load? (refered to as Example #1)

$dbInfo = (new sql)->select($var,$tab,$cri);
$moreInfo = (new sql)->select($var2,$tab2,$cri2);
$evenMoreInfo = (new sql)->select($var3,$tab3,$cri3);

Would it be beneficial to make my sql class's methods static?

Or should I not create a new instance of a sql object every time I want to make a query (like the example below - refered to as Example #2)?

$sql = new sql();
$dbInfo = $sql->select($var,$tab,$cri);
$moreInfo = $sql->select($var2,$tab2,$cri2);
$evenMoreInfo = $sql->select($var3,$tab3,$cri3);

How and when is Example #1 the better choice over Example #2, and vice versa?

If I assume that Example #1 is going to take the most resources from the DB, when would you pick Example #1 over Example #2?

4

1 回答 1

0

您的示例 2 更常见,但是 SQL 对象通常是静态/单例。因此,每个服务器请求它都会连接到数据库一次。

您的基本 SQL 对象应处理连接到数据库,然后处理基本输入/输出,例如执行 SQL 字符串并返回结果。

然后,您可以在每个对象/表的基础上添加新对象,而不是与此 SQL 单例接口。这些类将根据它们的表、连接、字段名称/类型等来处理构建它们的自定义 SQL。

例如:

一个非常基本的“表”对象看起来像这样

class SomeTableObject
{
    m_TableName = 'SomeTable'; // Table to get Data from

    function GetSelectSQL()
    {
       return "SELECT * FROM ".$this->m_TableName;
    }

    function Select($where)
    {
        $sql = $this->GetSelectSQL().$where;
        return SqlSingleton::Execute($sql);
    }

    function GetByID($id)
    {
       $where = " WHERE FieldNameForID=$id";
       return $this->Select($where);
    }
}

如果这些对象扩展了具有基本 GetSelectSQL、TableName、Select 等函数的基类,它们会更好地工作。GetByID(和其他获取、更新、插入)因表而异。

于 2013-04-23T10:01:25.833 回答