<分区>
我是第一次使用 OO 创建网站,我正在努力寻找正确的方法。 我不喜欢所有事情都在一个类中完成的类,所以我将实体类和数据库类分开了。 例如:http://w3cyberlearning.com/php/mysql_oop_product_class.php 我觉得这门课不太合逻辑。 - 为什么产品应该包含数据库实例 -$product->get_products() 我认为完全不符合逻辑。
所以我根据以下结构创建了一个单独的类:
Table: Products
Fields: productID,productName,categoryID
Table: ProductCategory
Fields: categoryID,category
Classes:
Product
-productID
-productName
-category (object)
DataProduct
-insertProduct($product)
insert query...
-deleteProduct($product)
delete query...
-getProduct($id)
select data from table ... (join between product and category to get all the fields)
$category = new Category($categoryID,$categoryname)
$product = new Product($productID,$productName);
$product->setCategory($category);
return $product;
ProductCategory
-categoryID
-category
DataProductCategory
...
但现在我遇到了一些问题,不知道我是否处理得当。
问题一
例如,删除一个产品,我可以执行两个不同的脚本,我应该使用哪个?
http://www.mywebsite.com/books/1/
$id = 1 (1 retrieved from the url)
$DataProduct = new DataProduct();
$DataProduct->deleteProduct($id);
OR
$product = new Product();
$product->setId($id);
$DataProduct = new DataProduct();
$DataProduct->deleteProduct($product);
问题2
当我从数据库中检索产品时,我创建了一个新的产品对象并将类别作为对象添加到产品中。 假设您有一个管理页面,您想要在其中添加新产品,并且您有一个带有 categorieID id 的选项列表:
<input type="text" name="productname">
<select name="categories">
<option name="cat1" value="1">
<option name="cat2" value="2">
</select>
如果我想将此产品保存到数据库中,最好的方法是什么? 在数据库中,producttable 仅保存 categoryID offcourse,作为 categorytable 的外键。
$product = new Product();
$product->setProductName("test");
$product->setCategoryID(1); (and add a variable categoryID in the products class)
$dataProduct = new DataProduct();
$dataProduct->insertProduct($product);
只需获取 $product->categoryID 并将其与 $product->productName 一起插入数据库
或者我应该这样做:
$product = new Product();
$product->setProductName("test");
$dataCategory = new DataCategory();
$dataProduct = new DataProduct();
$category = $dataCategory->getCategory(); (which retrieves the categoryID and name, creates the object and returns it)
$product->setCategory($category);
$dataProduct->insertProduct($product);
并通过保存从对象中检索类别的 ID?
这两种方法都可以,但我有点犹豫要走哪条路。