如果我们有这样的代码:
class Game {
private $_id;
private $_name;
private $_url;
public function __construct($_id,$_name,$_url){
$this->_id = $_id;
$this->_name = $_name;
$this->_url = $_url;
}
}
我们想简单地连接到我们的数据库以通过 ID 获取游戏,我们将“getByID”函数放在哪里?
我们是将它作为“静态函数”放在“游戏类”中,还是作为“公共(public)函数”放在“数据库连接类”中,或者我们只是将方法放在主函数中的“通用函数”中index.php' 作为'函数'?
我目前在“游戏类”中选择了一个“静态函数”:
public static function getByID($id,$db){
$query = "SELECT * FROM game WHERE id = :id LIMIT 1";
$prepare = array(":id"=>$id);
$result = $db->Precute($query,$prepare);
foreach($result as $r) return new Game($r['id'],$r['name'],$r['url']);
return null;
}
(Precute 是数据库类中的自定义函数,用于准备和执行查询) 你会如何处理这个问题?
最佳答案
在适当的 OOP 中,返回特定类实例的 DAL 函数在该类中应该是静态的。作为一项基本规则,与一个特定对象相关的所有功能都应该是该特定对象的一部分,如果在实例上调用则作为实例方法,如果它创建或管理实例(“工厂模式”)则作为静态方法。
您的函数目前不是静态的,正确的用法是:
class Game
{
..other functions..
public static function getById($id)
{
..implementation, which can either access central storage or retrieve
the object itself if concurrent edits are not an issue..
}
}
然后在别处:
$myGame = Game::getById(684);
您可能想看看 Doctrine而不是重新发明轮子。即使你真的想做一个新的轮子,它的代码示例也都遵循正确的 OOP 原则。
关于php - OOP PHP 与 Mysql 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20935985/