我第一次使用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
...
Run Code Online (Sandbox Code Playgroud)
但现在我遇到了一些问题,我正在处理它.
举例来说,删除一个产品,我可以执行两个不同的脚本,我应该使用哪一个?
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);
Run Code Online (Sandbox Code Playgroud)
当我从数据库中检索产品时,我创建了一个新的产品对象,并将该类别作为对象添加到产品中.假设您有一个管理页面,您想要添加新产品,并且您有一个包含类别ID的选项列表:
<input type="text" name="productname">
<select name="categories">
<option name="cat1" value="1">
<option name="cat2" value="2">
</select>
Run Code Online (Sandbox Code Playgroud)
如果我想将此产品保存到数据库,那么最好的方法是什么?在数据库中,productstable只保存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);
Run Code Online (Sandbox Code Playgroud)
然后获取$ 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);
Run Code Online (Sandbox Code Playgroud)
并保存从对象中检索类别的ID?
这两种方式都可行,但我有点卡在哪个方向.
问题1
我建议使用该DataProduct方法。尽管它与 更相关Product,但您已经在使用 来执行DataProduct类似的操作,例如插入和更新。我想说你也需要坚持删除同一个对象。
问题2
尽管我的感觉是你应该坚持第一种方法,因为它更整洁,但第二种方法是 OOP 正确的。您只为类设置属性,因此如果您在类中获取对象,Product则会很混乱。相反,您想要设置整个对象。CategoryIDProduct
OOP 是一个困难的理论问题,但你做得很好。我知道很难判断你自己的 OOP,因为你经常从编程的角度来看待它,而不是 OOP 的角度,这使得它变得比现在更难。