I have a design question for working with databases in object-oriented PHP.
I have a table in my database called products
. Then I have 2 classes for this table in my PHP project. ProductsRepository.php
and Product.php
.
ProductsRepository.php
currently looks like this
class ProductsRepository
{
private $db;
public function __construct(DB $db)
{
$this->db = $db;
}
public function getById($id)
{
$data = $this->db->GetProductByID($id);
$product = new Product(
$data['id'],
$data['category'],
$data['title'],
$data['description'],
);
return $product;
}
public function getAll()
{
$products = array();
$data = $this->db->GetAllProducts();
foreach ($data as $productData){
$product = new Product(
$productData['id'],
$productData['category'],
$productData['title'],
$productData['description'],
);
$products[] = $product;
}
return $products;
}
}
My question is how I should build a "createProduct" method. First and foremost, which class should it be in? I want the method to return an instance of the new product. The main problem I have with this is how I should handle the id
of the new product since it will be given the next id
available by the database.
A few options I've thought of:
Have createProduct
in ProductsRepository
and let it take a product with id
set to -1 as argument
public function createProduct(Product $product)
{
$product['id'] = $this->db->insertANewProduct($product); //returns the id
}
Have createProduct
in Product
Should this be the constructor for the Product
class?
public function createProduct($db, $data)
{
$this->$data = $data; //includes all info of the new product except the id
$this->$data['id'] = $db->insertANewProduct($data); //returns the id
}