不同类

时间:2016-01-11 06:06:04

标签: php mysql redundancy

我正在创建一个使用8个类的PHP Web应用程序(更多内容)。我意识到所有这些类都具有访问数据库的相同功能:get_single,get_list,插入,更新和删除。

对于每个课程,解决了哪个数据库表以及选择了哪些字段。

例如:

function get_single($conn) {

    $sql = $conn->prepare('SELECT id_person, join_date, img_profile, img_header, firstname, familyname, nationality, mail, password, birthday FROM person WHERE id_person = ?');
    $sql->bind_param('i', $this->id);


    $sql->execute();
    $sql->bind_result($this->id, $this->join_date, $this->profile_img, $this->header_img, $this->firstname, $this->familyname, $this->nationality, $this->mail, $this->password, $this->birthday);

    $sql->fetch();

    return $this;
}

我问自己是否可以或应该为所有类编写单个函数,如下所示:

function get_single($id, $conn, $query) {

    $sql = $conn->prepare($query);
    $sql->bind_param('i', $id);


    $sql->execute();
    $sql->bind_result(/* ??? */);

    $sql->fetch();

    return /* ??? */ ;
}

...然后拨打

$foo = new Foo(array('id' => $bar));
$foo = get_single($foo->id, $conn, $qry_single_foo);

这样我可以

  • 集中存储所有SQL查询
  • 减少代码总量
  • 提高可读性......也许?

或者我应该有这些类继承的父类吗?

还是使用设计模式?也许是装饰者? (对不起,我的知识很不存在)

现在我意识到可能更容易做到不同,我有点不知所措。

想法?

由于

1 个答案:

答案 0 :(得分:0)

您可以使用Web MVC框架或ORM库。

请检查一些可以与您的应用程序集成的ORM库。

<强> ORM