Source Code:
(back to article)
<?php interface RepositoryInterface { public function getById($id); public function getAll(); public function save($data); } class Repository implements RepositoryInterface { protected $db; public function __construct($db) { $this->db = $db; } public function getById($id) { // mock implementation to return data return ['id' => $id, 'name' => 'Product ' . $id, 'price' => 100.0]; } public function getAll() { // mock implementation to return all data return [['id' => 1, 'name' => 'Product 1', 'price' => 100.0], ['id' => 2, 'name' => 'Product 2', 'price' => 200.0], ['id' => 3, 'name' => 'Product 3', 'price' => 300.0]]; } public function save($data) { // mock implementation to save data echo "Saving data: " . print_r($data, true) . "\n"; } } $repository = new Repository(null); $productId = 1; $product = $repository->getById($productId); echo "Product Information: "; echo "ID: " . $product['id'] . "\n"; echo "Name: " . $product['name'] . "\n"; echo "Price: " . $product['price'] . "\n"; $allProducts = $repository->getAll(); echo "All Products: \n"; foreach ($allProducts as $p) { echo "ID: " . $p['id'] . "\n"; echo "Name: " . $p['name'] . "\n"; echo "Price: " . $p['price'] . "\n"; } $newProduct = ['name' => 'Super Product', 'price' => 99.99]; $repository->save($newProduct); echo "New product saved successfully!\n"; ?>
Result:
Report an issue