Ćwiczyczę sobie programowanie obiektowe, staram się trzymać zasad SOLID, ale najlepiej będzie jeśli ktoś z zewnątrz oceni to co napisałem. Moje pytanie jest - czy jest to po prostu dobry kod? Czy jest on dobrze zaprojektowany(czy jest elastyczny)? Czy jest zgodny z zasadami SOLID? I najważniejsze - co można w nim poprawić?
interface ProductRepositoryInterface{ /** * Find all products * * @return array */ public function findAll(); /** * Find specific product by id * * @param int id * * @return array */ public function findById($id); /** * Save single product * * @param array item * * @return bool */ public function save($item); } class JsonProductReposiotry implements ProductRepositoryInterface { /** * Path to json file, witch contains data */ private $file = 'database.json'; /** * Set file property */ function __construct($file = 'database.json') { $this->file = $file; } /** * Find all products * * @return array */ public function findAll() { } /** * Find specific product by id * * @param int id * * @return array */ public function findById($id) { foreach ($items as $item) { if ($item['id'] == $id) return $item; } } /** * Save single product * * @param array item * * @return bool */ public function save($item) { $this->items[] = $item; //append new product $result = file_put_contents($this->file, json_encode($this->items)); //save to file return ($result) ? true : false; } } class Product { /** * Products properties that can be set */ private $fillable = ['id', 'name', 'price']; /** * Automatic sets properties */ public function __set($property, $value) { $this->$property = $value; } } } class ProductsManager { /** * Sotres all producst obiented from respository */ private $products = []; /** * Set ProductsManager dependencies * * @param ProductRepositoryInterface */ function __construct(ProductRepositoryInterface $repository) { $this->repository = $repository; } /** * Add single Product instacne to products property */ public function addProduct(Product $item) { $this->products[] = $item; } /** * Get all products from respository * * @return array */ public function findAll() { return $this->repository->findAll(); } /** * Save all products * * @return all products */ public function saveAll() { foreach ($this->products as $product) { $this->repository->save([ 'id' => $product->id, 'name'=> $product->name, 'price' => $product->price ]); } return $this->findAll(); } }
Poniżej proste zastosowanie tych klas
$manager = new ProductsManager(new JsonProductReposiotry('database.json')); $dress = new Product(); $dress->id = '791'; $dress->name = 'dress'; $dress->price = '150'; $socks = new Product(); $socks->id = '21'; $socks->name = 'socks'; $socks->price = '15'; $manager->addProduct($dress); $manager->addProduct($socks); $manager->saveAll();