I have been creating a website using OO for the first time and I'm struggling to find the right way to go. I don't like classes where everything is done in one class so I separated the entity and database class. For example: http://w3cyberlearning.com/php/mysql_oop_product_class.php I find this class not so logical. -why should a product contain a database instance -$product->get_products() insn't logical at all I think.
So I create a separate class according to the following structure:
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
...
But now I'm stuck with some questions wether I'm handling it right.
Question 1
To for example, delete a product, I can execute two different scripts, which one should I use?
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);
Question 2
When I retrieve a product from the database, I create a new Product Object and I add the category as an object to the Product. Lets say you have an adminpage where you want to add a new product and you have an option list with categorieID ids:
<input type="text" name="productname">
<select name="categories">
<option name="cat1" value="1">
<option name="cat2" value="2">
</select>
If I want to save this product to the database, what is the best way to do this? In the database, the productstable only holds the categoryID offcourse, as an foreign key to the 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);
and just get the $product->categoryID and insert it into the database along with the $product->productName
or should I do:
$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);
and with saving retrieve the id for the category from the object?
Both ways will work, but I'm a little bit stuck on which is the way to go.