ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
PHP ရဲ့ အခြေခံအပိုင်းတွေ အားလုံးကို သင်တွေ့ပြီးပါပြီ: variable၊ array၊ function၊ form၊ session၊ class၊ exception နဲ့ database။ အပိုင်းတွေကို သိတာက မီးဖိုချောင်သုံး ကိရိယာအစုံ ပိုင်ဆိုင်တာနဲ့ တူပါတယ်။ ဒါပေမယ့် ဟင်းတစ်ခွက် ချက်ကြည့်မှ အဲဒါတွေ ဘယ်လို အတူအလုပ်လုပ်လဲ သင်ယူရပါတယ်။
နောက်ဆက်လုပ်သင့်တာက tutorial တစ်ခု ထပ်လိုက်တာ မဟုတ်ဘဲ project သေးသေးလေးတစ်ခု ဆောက်တာပါ။ အဲဒီမှာ data က input ကနေ ဝင်လာပြီး စစ်ဆေးမှုတွေကို ဖြတ်၊ storage ထဲ ရောက်၊ report အဖြစ် ပြန်ထွက်လာပါတယ်။
Problem → Why → Solution
ပြဿနာ: ဖိုင်အလွတ်ရှေ့မှာ ခက်ခဲနေတာ
Course ပြီးတဲ့နောက် အကျပ်အတည်းတစ်ခုက tutorial ကူးခုန်တာပါ။ Example တိုင်းကို လိုက်လုပ်နိုင်ပေမယ့် ဖိုင်အလွတ်ကို မြင်ရင် ဘာကနေစရမလဲ မသိတော့ပါဘူး။ ဗဟုသုတက သီးခြားသေတ္တာတွေထဲမှာ ရှိနေလို့ပါ၊ array အတွက် lesson တစ်ခု၊ form အတွက် တစ်ခု၊ PDO အတွက် တစ်ခု။ တကယ့် feature တစ်ခုကတော့ အဲဒါအားလုံးကို နေရာတစ်ခုတည်းမှာ အစီအစဉ်မှန်မှန် လိုပါတယ်။
ပေါင်းစပ်ဖို့ လေ့ကျင့်မထားရင် code က ရှည်လျားတဲ့ script တစ်ခုဖြစ်သွားပြီး validation၊ SQL နဲ့ print ထုတ်တာတွေ ရောနေပါတယ်။ ဥပမာ အောက်က loop ကို ကြည့်ပါ။ ဖြေရှင်းနည်းက တာဝန်တစ်ခုစီ ဘယ်နေရာမှာ နေမလဲ ကိုယ်တိုင်ဆုံးဖြတ်ရတဲ့ project သေးသေးလေးတစ်ခု လုပ်ကြည့်တာပါ။
<?php
// Parsing, checking, SQL and printing all tangled in one loop.
foreach ($rows as $row) {
if ($row['amount'] > 0) {
$pdo->query("INSERT INTO expenses VALUES
(NULL, '{$row['title']}', {$row['amount']})");
echo 'Saved ' . $row['title'] . '<br>';
}
}ဘာကြောင့် သင်ခန်းစာတွေက မလုံလောက်တာလဲ
Lesson တစ်ခုစီက tool တစ်ခုကို သီးသန့် ပြပါတယ်။ ဒါပေမယ့် tool တွေကြား ဆက်ကြောင်း (seam) တွေကို မပြပါဘူး: input က typed object ဖြစ်လာတဲ့နေရာ၊ error တစ်ခုကို ဖမ်းတဲ့နေရာ၊ SQL ကို ဝှက်ထားတဲ့နေရာ။ အဲဒီ seam တွေကို ရွေးချယ်တာက project ရဲ့ အဓိကအလုပ်ပါ။
Core concept: layer တစ်ခုကို အလုပ်တစ်ခု
သေးငယ်တဲ့ PHP program တစ်ခုကို pipeline အဖြစ် မြင်ပါ။ Raw data က တစ်ဘက်ကဝင်ပြီး အလွှာတစ်ခုချင်းစီက အလုပ်တစ်ခုကိုပဲ လုပ်ကာ report က တစ်ဘက်ကနေ ထွက်ပါတယ်။ ဒီ lesson ရဲ့ capstone မှာ အလွှာငါးခု ရှိပါတယ်။
၁။ Raw input ကို typed object ဖြစ်အောင်
CSV row ဒါမှမဟုတ် form က လာတဲ့ array ကို ယုံလို့မရပါဘူး။ Expense::fromRow() က array ကို စစ်ပြီး မှန်ရင် Expense object ဆောက်ပါတယ်၊ မှားရင် exception ပစ်ပါတယ်။ ဒီအလွှာကို ဖြတ်ပြီးတဲ့ object တိုင်းက စည်းမျဉ်းကို ကိုက်ညီပြီးသားပါ။
၂။ Type နဲ့ enum တွေနဲ့ domain ကို model လုပ်
declare(strict_types=1)၊ int amountCents၊ readonly property နဲ့ enum Category တို့ကြောင့် မမှန်တဲ့ တန်ဖိုးတွေက ဆောက်လို့တောင် မရပါဘူး။ "gifts" လို မသိတဲ့ category က Category::tryFrom() မှာ null ပြန်ပြီး ပယ်ချခံရပါတယ်။
၃။ Exception တွေက စည်းမျဉ်းချိုးတာကို သယ်ပါတယ်
ValidationException ကို loop ထဲက row တစ်ခုစီမှာ ဖမ်းပါတယ်။ Row တစ်ခု မှားလို့ import တစ်ခုလုံး မရပ်ပါဘူး၊ ကောင်းတဲ့ row တွေ ဆက်သွားပြီး မှားတဲ့ row တွေကို အကြောင်းရင်းနဲ့ စာရင်းလုပ်ထားပါတယ်။
၄။ Repository က SQL ကို ဝှက်ထားပါတယ်
ExpenseRepository က PDO prepared statement တွေကို ထုပ်ထားလို့ ကျန် code က SQL မသိဘဲ add() နဲ့ all() ကိုပဲ သုံးပါတယ်။ Table မှာ CHECK (amount_cents > 0) ရှိတာက ဒုတိယကာကွယ်ရေးပါ။
၅။ Array function တွေက report ဆောက်ပါတယ်
array_map၊ array_sum၊ max၊ array_search၊ arsort တို့က object list ကို total နဲ့ ranking အဖြစ် ပြောင်းပါတယ်။ တွက်ချက်မှုတွေကို array ပေါ်မှာ လုပ်တဲ့ ရိုးရိုး function တွေအဖြစ် ထားရင် test လုပ်ရ လွယ်ပါတယ်။
| Course topic | Capstone ထဲမှာ ပေါ်တဲ့နေရာ |
|---|---|
| Type declaration နဲ့ strict types | declare(strict_types=1)၊ int $amountCents၊ readonly |
| Class နဲ့ object | Expense နဲ့ ExpenseRepository |
| Exception | Row တစ်ခုစီမှာ ValidationException ကို ဖမ်းတာ |
| Array | array_map၊ array_sum၊ arsort၊ max |
| PDO နဲ့ prepared statement | Repository ရဲ့ add() နဲ့ all() |
| Validation နဲ့ constraint | filter_var၊ Category::tryFrom၊ CHECK |
Tutorial example နဲ့ project ကို ခွဲခြားတာက ဆုံးဖြတ်ချက်တွေပါ: validation က ဘယ်မှာနေမလဲ၊ ဘယ် error တွေကို ဖမ်းမလဲ၊ ပိုက်ဆံကို ဘယ် type နဲ့ ထားမလဲ။ ဒီဆုံးဖြတ်ချက်တွေကို ကိုယ်တိုင်လုပ်ဖူးမှ code ရဲ့ ဖွဲ့စည်းပုံကို နားလည်လာပါတယ်။
- Raw row တွေက ရိုးရိုး array အဖြစ် ဝင်
- fromRow() က valid object ဒါမှမဟုတ် exception
- Repository က သိမ်းပြီး ပြန်ဖတ်
- Array function တွေက report ဆောက်
Layer တစ်ခုစီက ကိုယ့်အလုပ်ကိုပဲ လုပ်ပါတယ်။ Report မှားနေရင် ဘယ် layer ကို ဖွင့်ကြည့်ရမလဲ ချက်ချင်း သိပါတယ်။
အခြေခံ ပုံစံ
<?php
foreach ($rawRows as $line => $raw) {
try {
$repository->add(Entity::fromRow($raw));
} catch (ValidationException $problem) {
$rejected[] = "row $line: " . $problem->getMessage();
}
}
$items = $repository->all();
$total = array_sum(array_map(fn (Entity $e) => $e->value, $items));Row တစ်ခုစီကို try ထဲမှာ valid object ဖြစ်အောင် ဆောက်ပြီး သိမ်းပါတယ်။ ValidationException က ဒီ row ကိုပဲ ကျော်စေပြီး အကြောင်းရင်းကို စာရင်းထဲ ထည့်ပါတယ်။ အားလုံးပြီးမှ ပြန်ဖတ်ပြီး array function တွေနဲ့ တွက်ပါတယ်။
Capstone: အသုံးစရိတ် import နဲ့ report
ဒီ file တစ်ခုတည်းမှာ course ရဲ့ အဓိကအပိုင်းတွေ အားလုံး ပါပါတယ်။ ကြိုရေးထားတဲ့ raw row ရှစ်ကြောင်း (အချို့က မှားနေတယ်) ကို Expense အဖြစ် ပြောင်းပြီး in-memory SQLite database ထဲ သိမ်းကာ category အလိုက် စုစုပေါင်းနဲ့ အကြီးဆုံး အသုံးစရိတ်ကို ရိုက်ထုတ်ပါတယ်။ ပိုက်ဆံကို float မဟုတ်ဘဲ cent (integer) နဲ့ သိမ်းထားတာကို သတိပြုပါ။ PDO ကို SQLite နဲ့ သုံးထားလို့ MySQL server မလိုပါဘူး၊ Course ရဲ့ MySQL lesson တွေက SQL ပုံစံ တူတူကိုပဲ ရေးပါတယ်။
<?php
declare(strict_types=1);
final class ValidationException extends InvalidArgumentException
{
}
enum Category: string
{
case Food = 'food';
case Transport = 'transport';
case Fun = 'fun';
public static function fromInput(string $text): self
{
return self::tryFrom(strtolower(trim($text)))
?? throw new ValidationException("Unknown category '$text'");
}
}
final class Expense
{
public function __construct(
public readonly string $title,
public readonly int $amountCents,
public readonly Category $category,
) {
if ($title === '') {
throw new ValidationException('Title is required');
}
if ($amountCents <= 0) {
throw new ValidationException('Amount must be positive');
}
}
/** Build an Expense from raw, untrusted input such as a CSV row or a form. */
public static function fromRow(array $row): self
{
$amount = filter_var($row['amount'] ?? '', FILTER_VALIDATE_FLOAT);
if ($amount === false) {
throw new ValidationException('Amount is not a number');
}
return new self(
trim((string) ($row['title'] ?? '')),
(int) round($amount * 100),
Category::fromInput((string) ($row['category'] ?? '')),
);
}
}
final class ExpenseRepository
{
public function __construct(private PDO $pdo)
{
$this->pdo->exec('CREATE TABLE expenses (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
amount_cents INTEGER NOT NULL CHECK (amount_cents > 0),
category TEXT NOT NULL
)');
}
public function add(Expense $expense): void
{
$stmt = $this->pdo->prepare(
'INSERT INTO expenses (title, amount_cents, category)
VALUES (:title, :amount, :category)'
);
$stmt->execute([
'title' => $expense->title,
'amount' => $expense->amountCents,
'category' => $expense->category->value,
]);
}
/** @return Expense[] */
public function all(): array
{
$sql = 'SELECT title, amount_cents, category FROM expenses ORDER BY id';
$toExpense = fn (array $r): Expense => new Expense(
$r['title'],
(int) $r['amount_cents'],
Category::from($r['category'])
);
return array_map($toExpense, $this->pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC));
}
}
function money(int $cents): string
{
return number_format($cents / 100, 2);
}
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$repo = new ExpenseRepository($pdo);
$rawRows = [
['title' => 'Noodles', 'amount' => '3.50', 'category' => 'food'],
['title' => 'Bus pass', 'amount' => '12', 'category' => 'Transport'],
['title' => 'Cinema', 'amount' => '8.25', 'category' => 'fun'],
['title' => 'Rice', 'amount' => '4.75', 'category' => ' FOOD '],
['title' => '', 'amount' => '5', 'category' => 'food'],
['title' => 'Taxi', 'amount' => 'free', 'category' => 'transport'],
['title' => 'Gift', 'amount' => '20', 'category' => 'gifts'],
['title' => 'Refund', 'amount' => '-4', 'category' => 'fun'],
];
$rejected = [];
foreach ($rawRows as $line => $row) {
try {
$repo->add(Expense::fromRow($row));
} catch (ValidationException $e) {
$rejected[] = 'row ' . ($line + 1) . ': ' . $e->getMessage();
}
}
$expenses = $repo->all();
echo 'Imported ' . count($expenses) . ' of ' . count($rawRows) . " rows\n";
foreach ($rejected as $message) {
echo " rejected $message\n";
}
$totals = [];
foreach ($expenses as $expense) {
$key = $expense->category->value;
$totals[$key] = ($totals[$key] ?? 0) + $expense->amountCents;
}
arsort($totals);
echo "\nTotals by category:\n";
foreach ($totals as $category => $cents) {
$amount = str_pad(money($cents), 8, ' ', STR_PAD_LEFT);
echo ' ' . str_pad($category, 10) . $amount . "\n";
}
$amounts = array_map(fn (Expense $e) => $e->amountCents, $expenses);
$biggest = $expenses[array_search(max($amounts), $amounts, true)];
echo "\nTotal: " . money(array_sum($amounts)) . "\n";
echo "Biggest: {$biggest->title} (" . money($biggest->amountCents) . ")\n";
echo 'Average: ' . money((int) round(array_sum($amounts) / count($amounts))) . "\n";Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- A safe way to turn text into an enum
return self::tryFrom(strtolower(trim($text)))trim နဲ့ strtolower ကြောင့် " FOOD " က Category::Food ဖြစ်ပါတယ်။ tryFrom() က မသိတဲ့တန်ဖိုးအတွက် null ပြန်ပြီး ?? throw က ValidationException အဖြစ် ပြောင်းပါတယ်။
- Rules enforced in the constructor
throw new ValidationException('Amount must be positive');Constructor ထဲမှာ စစ်ထားလို့ အမှားတန်ဖိုးနဲ့ Expense တစ်ခုကို ဘယ်နေရာကမှ ဆောက်လို့ မရပါဘူး၊ form ကပဲဖြစ်ဖြစ်၊ database ကနေ ပြန်ဖတ်တာပဲဖြစ်ဖြစ်ပါ။
- Untrusted input at the edge
$amount = filter_var($row['amount'] ?? '', FILTER_VALIDATE_FLOAT);"free" လို number မဟုတ်တာတွေအတွက် filter_var က false ပြန်ပါတယ်။ ?? '' ကြောင့် amount field မပါလည်း warning မတက်ပါဘူး။
- Money as whole cents
(int) round($amount * 100),ဒသမကိန်းတွေကို ပေါင်းရင် 0.1 + 0.2 က 0.3 နဲ့ အတိအကျ မညီတာမျိုး ဖြစ်တတ်ပါတယ်။ cent အပြည့်ကိန်းနဲ့ သိမ်းပြီး ပြတဲ့အခါမှ number_format နဲ့ ပြန်ပြောင်းပါတယ်။
- The repository's public face
public function add(Expense $expense): voidခေါ်တဲ့ code က Expense object ကိုပဲ ပေးရပြီး SQL၊ placeholder၊ column နာမည်တွေ မသိရပါဘူး။ နောက်ပိုင်း MySQL ကို ပြောင်းရင် repository ထဲမှာပဲ ပြင်ရပါမယ်။
- One bad row does not stop the import
} catch (ValidationException $e) {try/catch က loop ရဲ့ အတွင်းမှာ ရှိပါတယ်။ အပြင်မှာထားရင် ပထမ မှားတဲ့ row မှာတင် import တစ်ခုလုံး ရပ်သွားပါလိမ့်မယ်။ ဒါကြောင့် row 5 ကနေ 8 အထိ မှားပေမယ့် ပထမ ၄ ခု သိမ်းပြီးသားပါ။
- Array functions build the report
$amounts = array_map(fn (Expense $e) => $e->amountCents, $expenses);Object list ကနေ cent တွေကိုပဲ ထုတ်ယူပြီး array_sum၊ max၊ array_search တို့နဲ့ total၊ အကြီးဆုံး၊ average ကို တွက်ပါတယ်။ ရင်းနှီးတဲ့ array function တွေက loop အရှည်ကြီး အစား ကူပါတယ်။
Imported 4 of 8 rows
rejected row 5: Title is required
rejected row 6: Amount is not a number
rejected row 7: Unknown category 'gifts'
rejected row 8: Amount must be positive
Totals by category:
transport 12.00
food 8.25
fun 8.25
Total: 28.50
Biggest: Bus pass (12.00)
Average: 7.13Course topic တွေက နောက်ဘယ်ကို ဆက်သွားမလဲ
Topic တစ်ခုစီမှာ ပထမဆုံး ဆက်လေ့လာသင့်တာနဲ့ လက်တွေ့လုပ်ကြည့်ဖို့ project idea တစ်ခုစီ ရှိပါတယ်။ အားလုံးကို တစ်ပြိုင်နက် မလုပ်ပါနဲ့။ တစ်ခုကို ရွေးပြီး ပြီးအောင်လုပ်ပါ။
| Topic | ဆက်လေ့လာရန် | Project idea |
|---|---|---|
| Form နဲ့ validation | Request object တွေ၊ validation rule အစုအဝေး | စကားဝှက်စည်းမျဉ်းပါတဲ့ registration form |
| Session နဲ့ security | password_hash၊ password_verify၊ session cookie option | Login နဲ့ logout စနစ် |
| Class နဲ့ namespace | Composer autoload (PSR-4)၊ interface၊ dependency injection | Capstone ကို src/ ဖိုင်တွေအဖြစ် ခွဲပါ |
| PDO နဲ့ SQL | Migration၊ join၊ index၊ query log | Category table ခွဲပြီး user တွေ ထည့်ပါ |
| Exception | Error handler တစ်ခုတည်း၊ log ရေးတာ | ပယ်ချတဲ့ row တွေကို file ထဲ log လုပ်ပါ |
| Testing | PHPUnit | Expense နဲ့ repository အတွက် test ရေးပါ |
Composer နဲ့ PHPUnit နဲ့ capstone ကို စမ်းလို့ရအောင်
Composer ဟာ PHP ရဲ့ package manager ပါ။ composer.json ထဲက psr-4 autoload စည်းမျဉ်းက App\ namespace ကို src/ folder နဲ့ ချိတ်ပေးလို့ class တစ်ခုချင်းစီကို require လုပ်စရာ မလိုတော့ပါဘူး။ PHPUnit ကိုလည်း Composer နဲ့ ထည့်ပါတယ်။ အောက်က command တွေက ဒီအချိန်မှာ သင့် machine မှာ Composer ရှိမှ အလုပ်လုပ်လို့ ဒီ lesson ထဲမှာ run မပြပါဘူး။
{
"require": {
"php": ">=8.1"
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}composer install
composer require --dev phpunit/phpunit
vendor/bin/phpunit testsTest ကတော့ capstone ထဲက စည်းမျဉ်းတစ်ခုစီကို အတည်ပြုပါတယ်။ ဒီ test class က Expense ရဲ့ constructor စည်းမျဉ်းနဲ့ category ကို ပုံမှန်ပြောင်းတာ နှစ်ခုကို စစ်ပါတယ်။ Composer နဲ့ src/ ဖိုင်တွေ ခွဲထားမှ အလုပ်လုပ်တာမို့ ဒီမှာ run မပြပါဘူး။
<?php
declare(strict_types=1);
namespace Tests;
use App\Category;
use App\Expense;
use App\ValidationException;
use PHPUnit\Framework\TestCase;
final class ExpenseTest extends TestCase
{
public function testRejectsNonPositiveAmounts(): void
{
$this->expectException(ValidationException::class);
new Expense('Refund', -400, Category::Fun);
}
public function testNormalisesCategoryText(): void
{
$this->assertSame(Category::Food, Category::fromInput(' FOOD '));
}
}Framework နဲ့ PHP version အသစ်တွေ
Laravel နဲ့ Symfony က PHP framework အပြည့်အစုံ ဖြစ်ပြီး ကျယ်ပြန့်စွာ သုံးကြပါတယ်။ Routing၊ database layer၊ validation၊ template နဲ့ command-line tool တွေ ပါပါတယ်။ တစ်ခုကို ရွေးပြီး လေ့လာပါ၊ နှစ်ခုလုံး တစ်ပြိုင်နက် မလုပ်ပါနဲ့။ ဒီ course ထဲက သဘောတရားတွေ (request၊ validate၊ repository၊ response) က framework တိုင်းမှာ တစ်ထပ်တည်းကျပါတယ်၊ နာမည်တွေပဲ ကွာပါတယ်။
PHP version အသစ်တွေ ထွက်လာတဲ့အခါ မြှင့်တင်မလုပ်ခင် official migration guide ကို ဖတ်ပါ။ ပြီးရင် automated test တွေ run ပြီး ဘာမှ မပျက်တာ အတည်ပြုပါ။ ဘယ် version ကို လက်ရှိ အသစ်ဆုံးလို့ ဒီ lesson က မပြောပါဘူး၊ php.net ကို စစ်ပါ။
လက်တွေ့ project တွေမှာ
လက်တွေ့ project တွေမှာ
Professional PHP project တစ်ခုမှာ class တွေက src/ folder ထဲ ရှိပါတယ်။ Web server က ထောက်ပြတဲ့ ဖိုင်ကတော့ public/index.php တစ်ခုတည်း ဖြစ်ပြီး ကျန်တာတွေ browser က တိုက်ရိုက်မရောက်နိုင်ပါဘူး။ Password လို secret တွေကို code ထဲ မရေးဘဲ environment configuration ထဲ ထားပါတယ်။ Composer က dependency တွေကို စီမံပြီး CI ဆိုတဲ့ စနစ်က commit တိုင်းမှာ test နဲ့ PHPStan၊ Psalm လို static analysis tool တွေကို အလိုအလျောက် run ပါတယ်။
Production server မှာ display_errors ကို ပိတ်ပြီး error တွေကို log ထဲ ရေးပါတယ်၊ ဧည့်သည်ကို error အသေးစိတ် မပြပါဘူး။ HTTPS ကို အမြဲသုံးပြီး database ကို ပုံမှန် backup လုပ်ပါတယ်။ Code review လည်း ပါပါတယ်၊ အခြားသူက သင့် code ကို ဖတ်တာက bug တွေကို စောစောဖမ်းနိုင်တဲ့ နည်းလမ်းကောင်းတစ်ခုပါ။
အမှားများ
ဖြစ်လေ့ရှိတဲ့ အမှားများ
Project မပြီးခင် course အသစ်ကို စတာ
ဗဟုသုတအသစ်က လုပ်ပြီးတဲ့ project ထက် ပိုစိတ်ဝင်စားစရာကောင်းပါတယ်။ ဒါပေမယ့် project တစ်ခုကို အဆုံးထိ ပြီးမှ ပေါင်းစပ်ဖို့ ခက်တဲ့အပိုင်းတွေကို ကိုယ်တိုင်ကြုံရတာပါ။ ဒီ capstone ကို ကိုယ့်ရဲ့ အကြံနဲ့ ပြန်ရေးပြီး feature တစ်ခုထပ်ထည့်ပါ။
PHP အခြေခံမသိခင် framework ကို စတာ
Framework က request ကို ဘယ်လို လက်ခံပြီး validation နဲ့ database ကို ဘယ်လို ခေါ်သလဲ ဖုံးထားပါတယ်။ အခြေခံ PHP flow ကို မသိရင် framework က မျက်လှည့်လို့ ထင်ပြီး error တက်ရင် ဘာဖြစ်လို့လဲ မသိတော့ပါဘူး။
ကောင်းတဲ့လမ်းကြောင်းကိုပဲ စမ်းတာ
ဒီ capstone မှာ ပယ်ချတဲ့ row လေးကြောင်း (title ဗလာ၊ number မဟုတ်တဲ့ amount၊ မသိတဲ့ category၊ အနုတ် amount) ပါလို့ အဓိပ္ပာယ်ရှိတာပါ။ မှန်တဲ့ input တစ်ခုကို စမ်းရုံနဲ့ ကျေနပ်ရင် တကယ့် user ရဲ့ မှားတဲ့ input မှာ program ပျက်ပါလိမ့်မယ်။
ပိုက်ဆံကို float နဲ့ သိမ်းတာ
PHP မှာ 0.1 + 0.2 === 0.3 က false ပါ။ ဒသမကိန်းအများစုကို binary float နဲ့ အတိအကျ ကိုယ်စားမပြုနိုင်လို့ပါ။ ပိုက်ဆံကို cent လို အပြည့်ကိန်းနဲ့ သိမ်းပါ၊ ဒါမှမဟုတ် database ရဲ့ DECIMAL type ကို သုံးပါ။
Mini challenge
အသုံးစရိတ် အများဆုံး category တွေကို ဖော်ပြကြည့်ပါ
ရိုးရိုး array တွေပေါ်မှာ အလုပ်လုပ်တဲ့ function နှစ်ခု ရေးပါ။ topCategories() က expense list ကို category အလိုက် ပေါင်းပြီး စုစုပေါင်း အများဆုံး category ကနေ စီကာ $limit အရေအတွက်ပဲ ပြန်ပေးပါတယ်။ shareOfTotal() ကတော့ အဲဒီ category တွေရဲ့ စုစုပေါင်းကို ရာခိုင်နှုန်း (whole number) အဖြစ် ပြောင်းပေးပါတယ်။
- $limit က အနုတ်ဆိုရင် InvalidArgumentException ပစ်ပါ
- Total တူရင် category နာမည် အက္ခရာစဉ်အတိုင်း ထားပါ (ksort ပြီးမှ arsort)
- Key တွေ (category နာမည်) ကို ထိန်းထားပါ၊ array_slice ရဲ့ preserve_keys ကို သုံးပါ
- shareOfTotal() က စုစုပေါင်း 0 ဒါမှမဟုတ် ဗလာ array ဆိုရင် သုညနဲ့ မစားဘဲ ဗလာ array ပြန်ပါ
<?php
declare(strict_types=1);
// An expense is a plain array with the keys title (string),
// category (string) and cents (int).
function topCategories(array $expenses, int $limit): array
{
// TODO: throw InvalidArgumentException when $limit is negative
// TODO: add up the cents per category
// TODO: biggest total first; equal totals stay in A-Z order
// TODO: keep only the first $limit entries, with their keys
}
function shareOfTotal(array $totals): array
{
// TODO: whole-number percent of the grand total, same keys
// TODO: guard against a grand total of 0
}ရလဒ်: transport 1200 cents 59% နဲ့ food 825 cents 41% ဆိုပြီး နှစ်ကြောင်း ပေါ်ပါမယ် (ရာခိုင်နှုန်းက အဲဒီနှစ်ခုကြားမှာပဲ တွက်တာပါ)။ ပြီးရင် limit 0၊ data မရှိတာ၊ ဗလာ share တို့က [] ဖြစ်ပြီး နောက်ဆုံးမှာ "Limit must not be negative" error ပေါ်ပါမယ်။
အရိပ်အမြွက် ကြည့်ရန်
ksort($totals) ပြီးမှ arsort($totals) လုပ်ပါ။ PHP 8 ရဲ့ sort function တွေက stable ဖြစ်လို့ total တူတဲ့ category တွေက A-Z အစီအစဉ်ကို ထိန်းထားပါတယ်။ array_map ကို array တစ်ခုတည်းနဲ့ ခေါ်ရင် key တွေ ပြန်ရပါတယ်။
အဖြေ ကြည့်ရန်
<?php
declare(strict_types=1);
/** @return array<string, int> category => total cents, biggest first, at most $limit */
function topCategories(array $expenses, int $limit): array
{
if ($limit < 0) {
throw new InvalidArgumentException('Limit must not be negative');
}
$totals = [];
foreach ($expenses as $expense) {
$category = $expense['category'];
$totals[$category] = ($totals[$category] ?? 0) + $expense['cents'];
}
ksort($totals); // alphabetical first ...
arsort($totals); // ... then biggest first; PHP 8 sorting is stable, so ties stay A-Z
return array_slice($totals, 0, $limit, true);
}
/** @return array<string, int> category => whole-number percent of the grand total */
function shareOfTotal(array $totals): array
{
$grand = array_sum($totals);
if ($grand === 0) {
return [];
}
return array_map(fn (int $cents) => (int) round($cents * 100 / $grand), $totals);
}
$expenses = [
['title' => 'Noodles', 'category' => 'food', 'cents' => 350],
['title' => 'Bus pass', 'category' => 'transport', 'cents' => 1200],
['title' => 'Cinema', 'category' => 'fun', 'cents' => 825],
['title' => 'Rice', 'category' => 'food', 'cents' => 475],
];
$top = topCategories($expenses, 2);
foreach (shareOfTotal($top) as $category => $percent) {
echo str_pad($category, 10) . $top[$category] . " cents $percent%\n";
}
echo 'limit 0: ' . json_encode(topCategories($expenses, 0)) . "\n";
echo 'no data: ' . json_encode(topCategories([], 3)) . "\n";
echo 'share of nothing: ' . json_encode(shareOfTotal([])) . "\n";
try {
topCategories($expenses, -1);
} catch (InvalidArgumentException $e) {
echo 'error: ' . $e->getMessage() . "\n";
}Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- အလွှာတစ်ခုစီက အလုပ်တစ်ခုပဲ လုပ်ပါ: input စစ်၊ domain model၊ repository၊ report
- Raw input ကို အစွန်မှာ typed object အဖြစ် ပြောင်းပြီး exception နဲ့ မမှန်တာကို ပယ်ချပါ၊ row တစ်ခုစီကို သီးခြား try/catch လုပ်ပါ
- ပိုက်ဆံကို cent အပြည့်ကိန်းနဲ့ သိမ်းပါ
- နောက်ဆက် Composer၊ PHPUnit၊ security၊ framework ကို တစ်ခုချင်း project တစ်ခုနဲ့ လေ့လာပါ
Migrating to PHP 8.5 — PHP Documentation Group