我想為我的php控制器實(shí)現(xiàn)一個真正的模式MVC。特別是,我想通過在PHP(用于業(yè)務(wù)組織的對象)中創(chuàng)建等效的Java“ bean”和使用這些業(yè)務(wù)對象的API來拆分模型和API。例如,我的基本對象是會員。問題是:我在哪里請求數(shù)據(jù)庫?我是否在__construct上要求所有成員的屬性,并且只使用getter訪問它們,或者在__construct中什么也不做,并且在每個getter函數(shù)中調(diào)用數(shù)據(jù)庫?人們告訴我,第一種解決方案更好,但是,如果我只想在控制器中提供特定信息,我將創(chuàng)建一個Member,其中包含在構(gòu)造時就計算出的所有信息(錯誤的內(nèi)存管理)。在第二種情況下,如果我想要幾個成員屬性,我將執(zhí)行幾個SQL請求,這將增加服務(wù)器執(zhí)行時間。第一種解決方案: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自定義請求非常適合不浪費(fèi)時間或內(nèi)存,因?yàn)樗鼈兪橇?xí)俗。那么,為什么今天這樣的請求被如此糟糕地看待呢?并且,如果Fb或Google這樣的大型組織使用數(shù)據(jù)庫進(jìn)行MVC,那么在拆分模型和控制器時如何不浪費(fèi)任何時間/內(nèi)存呢?
如何在不丟失SQL請求時間/服務(wù)器內(nèi)存的情況下用PHP / MySQL實(shí)現(xiàn)良好的MVC模式?
慕尼黑8549860
2021-03-31 13:15:36