'我有一个关于处理类属性的最佳方法的问题。
为了便于解释,假设我有一个名为 company 的类。“公司”具有单一属性,例如“名称”、“地址”等。除了这些单一属性之外,“公司”还具有多个员工、多个办公室和多个咖啡机。(不好的例子,但我能想到的最好的例子)。
初始化一个类时,我可以在构造方法中运行 SQL 查询来检索姓名、地址等。但是,由于“Employees”、“Offices”和“Coffee Machines”都存储在不同的数据库表中,并返回多个结果,要立即设置这些属性,我需要再运行三个 SQL 查询。
这是最好的方法,还是创建三个方法“getEmployees”、“getOffices”和“getCoffeeMachines”并在需要时运行查询的最佳实践?
不确定这是否清楚。这里有两个例子。是否最好这样做,从而在初始化时调用四个 SQL 查询,以便所有信息立即可用:
Class Company
{
private $name;
private $address;
private $employees;
private $offices;
private $coffeeMachines;
public function __construct()
{
$this->employees = array();
$this->offices = array();
$this->coffeeMachines = array();
... SQL to get name and address ...
$this->name = $rs['name'];
$this->address = $rs['address'];
... SQL to get employees ...
while ($rs = mysql_fetch_array)
{
$this->employees[$rs['id']] = $rs['name'];
}
... SQL to get offices ...
while ($rs = mysql_fetch_array)
{
$this->offices[$rs['id']] = $rs['office'];
}
... SQL to get coffee machines ...
while ($rs = mysql_fetch_array)
{
$this->coffeeMachines[$rs['id']] = $rs['coffeeMachine'];
}
}
}
或者最好这样做,只在初始化时运行一个 SQL 查询,并在需要时运行未来的查询
Class Company
{
private $name;
private $address;
private $employees;
private $offices;
private $coffeeMachines;
public function __construct()
{
... SQL to get name and address ...
$this->name = $rs['name'];
$this->address = $rs['address'];
}
public function getEmployees()
{
... SQL to get employees ...
while ($rs = mysql_fetch_array)
{
$this->employees[$rs['id']] = $rs['name'];
}
}
public function getOffices()
{
... SQL to get offices ...
while ($rs = mysql_fetch_array)
{
$this->offices[$rs['id']] = $rs['office'];
}
}
public function getCoffeeMachines()
{
... SQL to get coffee machines ...
while ($rs = mysql_fetch_array)
{
$this->coffeeMachines[$rs['id']] = $rs['coffeeMachine'];
}
}
}
对于它的价值,我怀疑后者,但可以使用其他意见。
谢谢