如何使用PHP / MySQL实现良好的MVC模式而不会丢失SQL请求时间/服务器内存? (良好做法)

问题描述 投票:-2回答:1

我想为我的php控制器实现一个真正的模式MVC。特别是,我想通过在PHP(为业务组织制作的对象)和使用这些业务对象的API中创建等效的Java“bean”来拆分Model和API。

例如,我的基本对象是会员。问题是:我在哪里请求我的数据库?我是否在__construct上请求所有成员的特权,我只是用getter访问它们或者我在__construct中什么也不做,我在每个getter函数中调用数据库?人们告诉我第一个解决方案更好,但是,如果我只想在我的控制器中有一个特定的信息,我将创建一个成员,其中包含在构造中计算的所有信息(坏内存管理)。在第二种情况下,如果我想要几个成员的特性,我会做几个SQL请求,这将增加我的服务器执行时间。

第一次溶剂:

public function __construct($ID_membre,$sql)
{
    $this->ID_membre = $ID_membre;
    $res = mysql_get("select * from membres where ID_membre = $ID_membre",$sql);
    if(!$res)
        throw new Exceptions\MyDefaultException("no member for this Id");

    $this->firstName = $res['first_name'];
    $this->lastName = $res['last_name'];
    $this->mail = $res['mail'];
    $this->gender = $res['gender'];
    // ....

    $this->sql = $sql;
}
public function getLastName()
{
    return $this->lastName;
}
public function getMail()
{
    return $this->mail;
}
public function getGender()
{
    return $this->gender;
}
// .... 

第二解决方案

public function __construct($ID_membre,$sql)
{
    $this->ID_membre = $ID_membre;
    $res = mysql_get("select count(*) from membres where ID = $ID_membre",$sql);
    if($res == 0)
        throw new Exceptions\MyDefaultException("no member with this id");



    $this->sql = $sql;
}
public function getLastName()
{
    mysql_get("select name from members where ID = {$this->id}",$this->sql);
    return $this->lastName;
}
public function getMail()
{
    mysql_get("select mail from members where ID = {$this->id}",$this->sql);
    return $this->mail;
}
public function getGender()
{
    mysql_get("select gender from members where ID = {$this->id}",$this->sql);
    return $this->gender;
}

在这种情况下,控制器内的旧的SQL自定义请求是完美的,不会浪费时间或内存,因为它们是习俗。那么,为什么这样的要求如此糟糕呢?如果像Fb或Google这样的大型组织使用数据库进行MVC,他们如何在拆分模型和控制器时不浪费任何时间/内存?

php mysql database model-view-controller
1个回答
1
投票

这是一个经典问题,如果你想要许多成员的一个属性,它甚至会变得更糟。

标准答案是解决方案1更好。从数据库请求一行并不比从数据库请求一个值花费更长的时间,因此一次询问整行是有意义的。除非您的数据库行变得非常大。然而,这不应该出现在良好的数据库设计中。如果您的行变得如此之大以至于妨碍了效率,那么可能是时候拆分表了。

现在回到我在这个答案开头提到的问题。你还没有解决这个问题。我的建议是创建两个类:一个用解决方案1,一个处理一行,另一个用解决方案2处理多行。

因此,两种解决方案都有其自己的位置,只是解决方案2对于处理一行几乎总是低效的,而我甚至没有谈到它需要的额外编码量。

© www.soinside.com 2019 - 2024. All rights reserved.