OOP类和外部数据列表


OOP classes and external lists of data

在PHP编程OO时,我从来不知道如何将类映射到简单的数据列表。我将试着做一个我每天都会遇到的简单例子:

首先创建MySQL表:

/* create product table */
CREATE TABLE `product` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `description` text COLLATE utf8_unicode_ci,
 `price` decimal(10,0) NOT NULL,
 `brand` int(11) NOT NULL,
 `deliverytime` int(11) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
/* data list for all kind of brands */
CREATE TABLE `brand` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `brand` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
/* brand data*/
insert  into `brand`(`id`,`brand`) values (1,'nike'),(2,'adidas'),(3,'diesel'),  (4,'dkny'),(5,'lacoste');
/* data list for deliverytime */
CREATE TABLE `deliverytime` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `deliverytime` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
/* deliverytime data */
insert  into `deliverytime`(`id`,`deliverytime`) values (1,'1 day'),(2,'2 days'),(3,'3 days'),(4,'4 days'),(5,'5 days'),(6,'6 days'),(7,'1 week'),(8,'1 - 2 weeks'),(9,'2 - 3 weeks'),(10,'4 - 5 weeks');

然后创建产品类。

  class Product{
    private 
    $name,
    $description,
    $price,
    $brand
    $deliverytime;
    public function __construct(){
       // etc etc
    }
    public function save(){
       // save the product
    }
   }

现在最大的问题是:

我应该如何处理我的产品类中的$brand和$deliverytime ?我是否应该创建一个Brand和DeliveryTime对象(它们依次负责获取正确的Brand和/或DeliveryTime数据)?

那么保存Product对象呢?我该如何处理品牌和交货期数据?

处理这种情况的最佳实践或模式是什么?

很抱歉这个问题,但我不确定在哪里寻找(标签搜索):/

编辑:

好吧,假设我不想使用某种ORM框架(Doctrine, dORM, redbean等),因为它对我的小系统来说是一个巨大的过度消耗,而且我真的想知道如何自己创建映射以供学习…有什么建议吗?

这是我喜欢使用的样式

class ProductModel {
    public function find($id) {
         // fetch product with your database code using parameters to filter
         $product = new ProductEntity(
             // initialize with non foreighn values (eg. $row->id, $row->name)
             new ProductBrandEntity($row->brand_id, $row->brand_name); // available because you joined brand??
             new ProductDeliveryTime(/* initialize */)
         );
         return $product;
    }
}

我喜欢从数据库中调用对象实体,但你可以叫他们任何你想要的。这基本上是你在你的问题中建议的,但我更喜欢有一个模型(从MVC)来初始化实体,而不是实体初始化自己。您应该对orm和ActiveRecord做一些研究,因为这些工作基本上已经为您完成了!