我在设计我正在构建的一个小php应用程序的OOP时遇到了一些困难。我在数据库中有餐馆的信息,分为一个restaurant表和一个locations表。这两个表都有一些公共列,如phone、website和logo url。显然,locations与restaurants之间的关系是多对一的.
所以问题是:我想创建一个Restaurant类,它包含所有与全球餐馆信息相关的信息,如名称、电话、网站、徽标等。然后,我想创建一个Location类,其中包含特定位置的信息,如地址、电话、网站、徽标等。
我遇到的问题是,我希望能够实例化这两种对象类型,但也希望Location类返回到父数据中,如果它本身不存在的话。通常,您可以编写这样的东西(缩写):
class Restaurant {
protected $phone;
function __construct($restaurant_id) {
// Perform db call here and set class attributes
}
public function getPhone() {
return $this->phone;
}
}
class Location extends Restaurant {
function __construct($location_id) {
// Perform db call here and set class attributes
// $restaurant_id would be loaded from the DB above
parent::__construct($restaurant_id)
}
}
$location = new Location(123);
echo $location->getPhone();
$restaurant = new Restaurant(456);
echo $restaurant->getPhone();但正如我所说的,我希望getPhone()方法首先检查$this->phone,如果它不存在,则返回到父服务器。这样的事会不会是正确的方法?
class Restaurant {
private $phone;
function __construct($restaurant_id) {
// Perform db call here and set class attributes
}
public getPhone() {
return $this->phone;
}
}
class Location extends Restaurant {
private $phone;
function __construct($location_id) {
// Perform db call here and set class attributes
// $restaurant_id would be loaded from the DB above
parent::__construct($restaurant_id)
}
public function getPhone() {
if(!empty($this->phone)) {
return $this->phone;
}
return parent::getPhone();
}
}
$location = new Location(123);
echo $location->getPhone();我觉得上面的代码真的很麻烦,而且可能有更好的方法来实现这一点。由于这两个类都有共同的属性,所以Location类最好不要扩展Restaurant,而是为“父”对象保留一个Restaurant类型的变量?然后在Location::getPhone()方法中,它执行类似的if(empty())检查吗?
发布于 2012-06-14 02:59:52
Location不应该扩展Restaurant,因为它本身并不是一家餐厅;它是该餐厅的许多位置之一。
class Location {
private $restaurant;
private $phone;
public function getPhone() {
return $this->phone ?: $restaurant->getPhone();
}
}现在,在这两个类之间有这么多相同的字段,您可能希望定义一个它们各自扩展的公共基类,例如包含网站、电话和徽标的CompanyInfoHolder。在这种情况下,Location将完全覆盖上面的getPhone。
https://stackoverflow.com/questions/11026063
复制相似问题