Hari 29: Mini Proyek — Sistem Inventaris
90 min
Last updated 09 Apr 2026
Studi Kasus: Sistem Inventaris Sederhana
Kita akan membuat sistem inventaris menggunakan prinsip OOP yang telah dipelajari.
interface Storable {
public function getStok(): int;
public function tambahStok(int $jumlah): void;
public function kurangiStok(int $jumlah): void;
}
class Produk implements Storable {
private array $riwayat = [];
public function __construct(
public readonly string $kode,
public readonly string $nama,
public float $harga,
private int $stok,
) {}
public function getStok(): int { return $this->stok; }
public function tambahStok(int $jumlah): void {
if ($jumlah <= 0) throw new \InvalidArgumentException("Jumlah harus positif");
$this->stok += $jumlah;
$this->riwayat[] = "+$jumlah (stok: {$this->stok})";
}
public function kurangiStok(int $jumlah): void {
if ($jumlah > $this->stok) throw new \UnderflowException("Stok tidak cukup");
$this->stok -= $jumlah;
$this->riwayat[] = "-$jumlah (stok: {$this->stok})";
}
public function nilaiInventaris(): float {
return $this->harga * $this->stok;
}
}
class Inventaris {
private array $produk = [];
public function tambahProduk(Produk $p): void {
$this->produk[$p->kode] = $p;
}
public function cari(string $kode): ?Produk {
return $this->produk[$kode] ?? null;
}
public function totalNilai(): float {
return array_sum(array_map(fn($p) => $p->nilaiInventaris(), $this->produk));
}
public function laporan(): void {
foreach ($this->produk as $p) {
printf("%-10s %-15s Stok:%-5d Rp%s\n",
$p->kode, $p->nama, $p->getStok(),
number_format($p->nilaiInventaris(), 0, ",", ".")
);
}
echo "Total Nilai: Rp " . number_format($this->totalNilai(), 0, ",", ".") . "\n";
}
}
$inv = new Inventaris();
$inv->tambahProduk(new Produk("P001", "Laptop", 8500000, 10));
$inv->tambahProduk(new Produk("P002", "Mouse", 150000, 50));
$inv->tambahProduk(new Produk("P003", "Keyboard", 350000, 30));
$inv->cari("P001")->tambahStok(5);
$inv->cari("P002")->kurangiStok(10);
$inv->laporan();
💡
Notice: Laptop: (5+2)*8.5jt=59.5jt, Monitor: 3*2.5jt=7.5jt, Mouse: (20-5)*150rb=2.25jt → total 59.5+7.5+2.25+... tunggu hitung ulang: 7*8500000=59500000, 3*2500000=7500000, 15*150000=2250000 → 69.250.000... sebenarnya dengan tambah(2) dan kurang(5): Laptop 7*8500000=59500000, Monitor 3*2500000=7500000, Mouse 15*150000=2250000 total 69250000... let me recalculate. Actually: Laptop (5+2)=7, 7*8500000=59500000. Monitor 3, 3*2500000=7500000. Mouse (20-5)=15, 15*150000=2250000. Total = 69250000. So expected output should be 69,250,000. Let me fix this.
Assignment
Buat sistem sederhana: tambahkan 3 produk ke inventaris, lakukan satu tambahStok dan satu kurangiStok, lalu tampilkan total nilai inventaris format Rp.
Expected output:
Total: Rp 69,250,000
PHP
index.php
Solution
Output