This is the first time I am creating a website using OO, and I am struggling to find the right path. I donโt like classes where everything runs in the same class, so I separated the entity class and the database class. For example: http://w3cyberlearning.com/php/mysql_oop_product_class.php I believe that this class is not so logical. - why the product should contain a database instance - $ product-> get_products () is absolutely logical, I think.
Therefore, I create a separate class in accordance with 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 am stuck with some questions, I am dealing with him correctly.
Question 1
To, for example, remove a product, can I execute two different scripts that I have to 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 add the category as an object to the Product. Suppose you have an administrative page where you want to add a new product, and you have a list of options with category identifiers:
<input type="text" name="productname"> <select name="categories"> <option name="cat1" value="1"> <option name="cat2" value="2"> </select>
If I want to store this product in a database, what is the best way to do this? In the database, productstable only has the category ID disabled, as a foreign key to the category table.
$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 enter $ product-> categoryID and paste it into the database along with $ 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 save to get the identifier for the category from the object?
Both methods will work, but I'm a little stuck on how to do this.