Kotchasan Framework Documentation
คลาส Utility - ยูทิลิตี้เสริม
คลาส Utility - ยูทิลิตี้เสริม
คลาส Utility ใน Kotchasan Framework เป็นกลุ่มคลาสที่ให้ฟังก์ชันช่วยเหลือสำหรับการจัดการข้อมูลประเภทต่างๆ รวมถึง ArrayTool, Text, Number และ Date ซึ่งช่วยให้การทำงานกับข้อมูลต่างๆ เป็นไปอย่างมีประสิทธิภาพ
สารบัญ
- ArrayTool - จัดการ Array
- Text - จัดการข้อความ
- Number - จัดการตัวเลข
- Date - จัดการวันที่และเวลา
- Best Practices
ArrayTool - จัดการ Array
การใช้งานพื้นฐาน
use Kotchasan\ArrayTool;
// ตัวอย่างข้อมูล
$users = [
['id' => 1, 'name' => 'John', 'email' => 'john@email.com', 'status' => 'active'],
['id' => 2, 'name' => 'Jane', 'email' => 'jane@email.com', 'status' => 'inactive'],
['id' => 3, 'name' => 'Bob', 'email' => 'bob@email.com', 'status' => 'active'],
];
$products = [
(object)['id' => 1, 'name' => 'Laptop', 'price' => 25000, 'category' => 'electronics'],
(object)['id' => 2, 'name' => 'Mouse', 'price' => 500, 'category' => 'electronics'],
(object)['id' => 3, 'name' => 'Book', 'price' => 250, 'category' => 'education'],
];การดึงค่าจาก Column
// ดึงชื่อผู้ใช้ทั้งหมด
$names = ArrayTool::columns($users, 'name');
// Result: [0 => 'John', 1 => 'Jane', 2 => 'Bob']
// ดึงชื่อผู้ใช้โดยใช้ ID เป็น key
$namesByIds = ArrayTool::columns($users, 'name', 'id');
// Result: [1 => 'John', 2 => 'Jane', 3 => 'Bob']
// ทำงานกับ Object array
$productNames = ArrayTool::columns($products, 'name', 'id');
// Result: [1 => 'Laptop', 2 => 'Mouse', 3 => 'Book']
// สร้าง dropdown options
$statusOptions = ArrayTool::columns($users, 'status', 'id');
$selectOptions = '';
foreach ($statusOptions as $id => $status) {
$selectOptions .= "<option value=\"{$id}\">{$status}</option>";
}การค้นหาและกรอง
// ค้นหาผู้ใช้ที่มี status = 'active'
$activeUsers = ArrayTool::search($users, 'status', 'active');
// Result: [0 => ['id' => 1, 'name' => 'John', ...], 2 => ['id' => 3, 'name' => 'Bob', ...]]
// กรองข้อมูลตามคำค้นหา
$filteredUsers = ArrayTool::filter($users, 'john');
// Result: แค่ผู้ใช้ที่มีชื่อ 'John'
// สร้างระบบค้นหาผลิตภัณฑ์
$searchTerm = 'laptop';
$searchResults = ArrayTool::filter($products, $searchTerm);
// ผสมกับการแปลงข้อมูล
$productList = [];
foreach ($searchResults as $product) {
$productList[] = [
'id' => $product->id,
'name' => $product->name,
'price_formatted' => number_format($product->price, 2)
];
}การเรียงลำดับ
// เรียงผู้ใช้ตามชื่อ
$sortedUsers = ArrayTool::sort($users, 'name');
// เรียงผลิตภัณฑ์ตามราคาจากสูงไปต่ำ
$sortedProducts = ArrayTool::sort($products, 'price', true);
// เรียงลำดับข้อมูลที่ซับซ้อน
$orders = [
['order_id' => 101, 'total' => 1500, 'date' => '2024-01-15'],
['order_id' => 102, 'total' => 2500, 'date' => '2024-01-12'],
['order_id' => 103, 'total' => 800, 'date' => '2024-01-18'],
];
$ordersByTotal = ArrayTool::sort($orders, 'total', true); // สูงไปต่ำ
$ordersByDate = ArrayTool::sort($orders, 'date'); // เก่าไปใหม่;การจัดการและแก้ไขข้อมูล
// ลบข้อมูลตาม key
$remainingUsers = array_diff_key($users, array_flip([0, 2])); // ลบ index 0 และ 2
$remainingUsers = array_diff_key($users, array_flip(explode(',', '1,2'))); // ลบ index 1 และ 2
// ดึงข้อมูลแบบ safe
$userEmail = $users[0]['email'] ?? 'No email';
$userPhone = $users[0]['phone'] ?? 'No phone'; // ไม่มี key นี้
// แทนที่ข้อมูล
$updatedUser = ArrayTool::replace($users[0], [
'status' => 'premium',
'last_login' => date('Y-m-d H:i:s')
]);
// เพิ่มข้อมูลก่อนหรือหลัง
$menu = ['home' => 'หน้าแรก', 'contact' => 'ติดต่อ'];
$menuWithAbout = ArrayTool::insertAfter($menu, 'home', 'about', 'เกี่ยวกับเรา');
// Result: ['home' => 'หน้าแรก', 'about' => 'เกี่ยวกับเรา', 'contact' => 'ติดต่อ']การแปลงข้อมูลซับซ้อน
// แปลง nested array เป็น string
$nestedData = [
'user' => ['name' => 'John', 'age' => 30],
'preferences' => ['theme' => 'dark', 'language' => 'th'],
'tags' => ['admin', 'moderator']
];
$dataString = ArrayTool::toString(' | ', $nestedData);
// Result: "John|30|dark|th|admin|moderator"
// Unserialize ข้อมูล
$serializedData = serialize(['setting1' => 'value1', 'setting2' => 'value2']);
$defaultSettings = ['setting2' => 'default2', 'setting3' => 'default3'];
$finalSettings = ArrayTool::unserialize($serializedData, $defaultSettings, false);
// Result: ['setting2' => 'default2', 'setting3' => 'default3', 'setting1' => 'value1']
// ตรวจสอบการมีอยู่แบบยืดหยุ่น
$needles = ['admin', 'user'];
$userRoles = ['admin', 'moderator', 'editor'];
$hasAccess = ArrayTool::inArrayAny($needles, $userRoles); // true
// สร้างระบบ permission
$requiredPermissions = ['read', 'write'];
$userPermissions = ['read', 'write', 'delete'];
$canAccess = ArrayTool::inArrayAny($requiredPermissions, $userPermissions);การใช้งานในระบบจริง
class UserManager
{
public function getUserDropdown($users, $selectedId = null)
{
$options = ArrayTool::columns($users, 'name', 'id');
$html = '<select name="user_id">';
foreach ($options as $id => $name) {
$selected = ($id == $selectedId) ? 'selected' : '';
$html .= "<option value=\"{$id}\" {$selected}>{$name}</option>";
}
$html .= '</select>';
return $html;
}
public function filterUsersByRole($users, $role)
{
return ArrayTool::search($users, 'role', $role);
}
public function sortUsersByLastActivity($users)
{
return ArrayTool::sort($users, 'last_activity', true);
}
public function buildUserSearchResults($users, $searchTerm)
{
$filtered = ArrayTool::filter($users, $searchTerm);
return ArrayTool::sort($filtered, 'name');
}
}Text - จัดการข้อความ
การจัดรูปแบบข้อความ
use Kotchasan\Text;
// ตัดข้อความยาว
$longText = "This is a very long text that needs to be truncated for display purposes";
$shortText = Text::cut($longText, 30);
// Result: "This is a very long text th.."
// ทำความสะอาดข้อความหลายบรรทัด
$multilineText = " This is line 1 \n\n This is line 2 \t\n This is line 3 ";
$cleanText = Text::oneLine($multilineText);
// Result: "This is line 1 This is line 2 This is line 3"
$cleanTextWithLimit = Text::oneLine($multilineText, 25);
// Result: "This is line 1 This is .."
// สร้างข้อความที่ปลอดภัย
$unsafeText = "<script>alert('XSS')</script>Hello & Welcome";
$safeText = Text::htmlspecialchars($unsafeText);
// Result: "<script>alert('XSS')</script>Hello & Welcome"
// แปลงกลับ
$originalText = Text::unhtmlspecialchars($safeText);
// Result: "<script>alert('XSS')</script>Hello & Welcome"การจัดการ Password และ Username
// ทำความสะอาด password
$rawPassword = "P@ssw0rd!@#$%^&()_+{}[]|\"':;?><,./`~กขค";
$cleanPassword = Text::password($rawPassword);
// Result: "P@ssw0rd!#$&{}[]_-.กขค"
// ทำความสะอาด username
$rawUsername = "user@domain.com!@#$%^&(){}[]|\"':;?><,./`~";
$cleanUsername = Text::username($rawUsername);
// Result: "user@domain.com_-."
// สร้างรหัสผ่านแบบสุ่ม
$randomPassword = Text::generateRandomString(8, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');
$randomCode = Text::generateRandomString(6); // เฉพาะตัวเลข
$randomPin = Text::generateRandomString(4, '0123456789');การแปลงและไฮไลท์ข้อความ
// แปลง BBCode และ URL
$bbcodeText = "Hello [b]World[/b]! Check out https://example.com for more info.";
$htmlText = Text::highlighter($bbcodeText);
// Result: "Hello <b>World</b>! Check out <a href=\"https://example.com\" target=\"_blank\">https://example.com</a> for more info."
// ทำงานกับรายการ
$listText = "[ul]Item 1<br>Item 2<br>Item 3[/ul]";
$htmlList = Text::highlighter($listText);
// Result: "<ul><li>Item 1</li><li>Item 2</li><li>Item 3</li></ul>"
// YouTube embed
$youtubeText = "Watch this video: [youtube]dQw4w9WgXcQ[/youtube]";
$embedCode = Text::highlighter($youtubeText);การจัดรูปแบบขนาดไฟล์
// แปลงขนาดไฟล์
$fileSize1 = Text::formatFileSize(1024); // "1 KB"
$fileSize2 = Text::formatFileSize(1048576); // "1 MB"
$fileSize3 = Text::formatFileSize(1073741824); // "1 GB"
$fileSize4 = Text::formatFileSize(1536, 1); // "1.5 KB"
// สร้างรายการไฟล์
$files = [
['name' => 'document.pdf', 'size' => 2097152],
['name' => 'image.jpg', 'size' => 524288],
['name' => 'video.mp4', 'size' => 52428800],
];
foreach ($files as $file) {
echo $file['name'] . ' (' . Text::formatFileSize($file['size']) . ')' . "\n";
}
// Output:
// document.pdf (2 MB)
// image.jpg (512 KB)
// video.mp4 (50 MB)การใช้งานขั้นสูง
// แทนที่ข้อความด้วย template
$template = "Hello {name}, your order #{order_id} total is {total} baht.";
$replacements = [
'{name}' => 'John Doe',
'{order_id}' => '12345',
'{total}' => '1,500.00'
];
$message = Text::replace($template, $replacements);
// Result: "Hello John Doe, your order #12345 total is 1,500.00 baht."
// ทำความสะอาด URL
$unsafeUrl = "javascript:alert('XSS')";
$safeUrl = Text::url($unsafeUrl); // Result: "alert('XSS')"
$normalUrl = "https://example.com/page?param=value";
$cleanUrl = Text::url($normalUrl); // Result: "https://example.com/page?param=value"
// จัดการข้อความสำหรับ editor
$editorText = "Content with <tags> & special chars {variables}";
$editorSafe = Text::toEditor($editorText);
// Result: "Content with <tags> & special chars {variables}"
// จัดการหัวข้อข่าว/บทความ
$rawTopic = " Breaking News:\n\n Important Update! ";
$cleanTopic = Text::topic($rawTopic);
// Result: "Breaking News: Important Update!"การใช้งานในระบบจริง
class ContentManager
{
public function processUserComment($comment)
{
// ทำความสะอาดพื้นฐาน
$clean = Text::htmlspecialchars($comment);
// จำกัดความยาว
$clean = Text::cut($clean, 500);
// แปลง URL และ BBCode
$clean = Text::highlighter($clean);
return $clean;
}
public function generateSlug($title)
{
// ทำความสะอาดหัวข้อ
$clean = Text::topic($title, false);
// แปลงเป็น slug
$slug = strtolower($clean);
$slug = preg_replace('/[^a-z0-9\-]/', '-', $slug);
$slug = preg_replace('/-+/', '-', $slug);
$slug = trim($slug, '-');
return $slug;
}
public function formatFileUploadInfo($filename, $size)
{
$cleanName = Text::htmlspecialchars($filename);
$formattedSize = Text::formatFileSize($size);
return "{$cleanName} ({$formattedSize})";
}
public function generateEmailTemplate($template, $userData)
{
$replacements = [];
foreach ($userData as $key => $value) {
$replacements["{{$key}}"] = Text::htmlspecialchars($value);
}
return Text::replace($template, $replacements);
}
}Number - จัดการตัวเลข
การจัดรูปแบบตัวเลข
use Kotchasan\Number;
// จัดรูปแบบตัวเลขด้วยเครื่องหมายจุลภาค
$price = 1234567; // .89;
$formattedPrice = Number::format($price);
// Result: "1,234,567.89"
// ใช้เครื่องหมายอื่น
$formattedEuropean = Number::format($price, '.');
// Result: "1.234.567.89"
// ตัวเลขไม่มีทศนิยม
$quantity = 150; // 0;
$formattedQuantity = Number::format($quantity);
// Result: "1,500"
// ใช้กับข้อมูลการเงิน
$amounts = [1234.56, 987654, 12.345, 0.99];
foreach ($amounts as $amount) {
echo Number::format($amount, ',') . " บาท\n";
}
// Output:
// 1,234.56 บาท
// 987,654 บาท
// 12.345 บาท
// 0.99 บาทการหารที่ปลอดภัย
// หารปกติอาจเกิด error เมื่อหารด้วย 0
$dividend = 10; // 0;
$divisor = 0;
// วิธีที่ปลอดภัย
$result = Number::division($dividend, $divisor);
// Result: 0 (แทนที่จะเป็น error)
// การใช้งานจริง
$totalSales = 5000; // 0;
$totalDays = 3; // 0;
$averageDaily = Number::division($totalSales, $totalDays);
// Result: 1666.67
// คำนวณเปอร์เซ็นต์
$passed = 8; // 5;
$total = 10; // 0;
$percentage = Number::division($passed * 100, $total);
// Result: 85
// ป้องกัน division by zero ในการคำนวณ
$scores = [95, 87, 92, 88, 76];
$totalScore = array_sum($scores);
$count = count($scores);
$average = Number::division($totalScore, $count);
// Result: 87.6การจัดรูปแบบด้วย Template วันที่
// ใช้ placeholder วันที่ในการสร้างเลขที่เอกสาร
$documentFormat = "DOC-%Y%m%d-%04d"; // ปี ค.ศ.
$documentNumber = 1;
$docId = Number::printf($documentFormat, $documentNumber);
// Result: "DOC-20240115-0001" (ถ้าวันนี้คือ 15 มกราคม 2024)
$invoiceFormat = "INV-%YY%M-%05d"; // ปี พ.ศ. แบบย่อ
$invoiceNumber = 12; // 3;
$invoiceId = Number::printf($invoiceFormat, $invoiceNumber, 'TH');
// Result: "INV-67-01-00123" (ถ้าเป็นปี 2567 เดือนมกราคม)
// รูปแบบอื่นๆ
$formats = [
"ORD-%y%m%d-%d" => 1, // ORD-240115-1
"REF-%Y%M-%d" => 15, // REF-2567-1-15
"TXN-%yy%mm%dd-%05d" => 999 // TXN-24-01-15-00999
];
foreach ($formats as $format => $number) {
echo Number::printf($format, $number) . "\n";
}การใช้งานในระบบจริง
class FinancialCalculator
{
public function formatCurrency($amount, $currency = 'THB')
{
$formatted = Number::format($amount, ',');
$symbols = [
'THB' => '฿',
'USD' => '$',
'EUR' => '€'
];
$symbol = $symbols[$currency] ?? $currency;
return $symbol . ' ' . $formatted;
}
public function calculatePercentage($value, $total)
{
$percentage = Number::division($value 100, $total);
return Number::format($percentage, ',') . '%';
}
public function calculateAverage($values)
{
$sum = array_sum($values);
$count = count($values);
return Number::division($sum, $count);
}
public function generateInvoiceNumber($sequence)
{
return Number::printf("INV-%Y%M-%05d", $sequence);
}
}
class SalesReport
{
public function formatSalesData($salesData)
{
$formatted = [];
foreach ($salesData as $item) {
$formatted[] = [
'product' => $item['product'],
'quantity' => Number::format($item['quantity']),
'price' => Number::format($item['price'], ','),
'total' => Number::format($item['quantity'] $item['price'], ','),
'percentage' => $this->calculatePercentage($item['total'], $item['grand_total'])
];
}
return $formatted;
}
private function calculatePercentage($value, $total)
{
return Number::format(Number::division($value * 100, $total), ',') . '%';
}
}Date - จัดการวันที่และเวลา
การเปรียบเทียบวันที่
use Kotchasan\Date;
// คำนวณอายุ
$birthDate = '1990-05-15';
$today = date('Y-m-d');
$ageData = Date::compare($birthDate, $today);
// Result: ['days' => 12345, 'year' => 33, 'month' => 8, 'day' => 1]
$ageText = Date::age($birthDate);
// Result: "33 {LNG_year} 8 {LNG_month} 1 {LNG_days}"
// เปรียบเทียบวันที่สองวันที่
$startDate = '2024-01-01';
$endDate = '2024-12-31';
$diff = Date::compare($startDate, $endDate);
// Result: ['days' => 365, 'year' => 0, 'month' => 11, 'day' => 30]
// คำนวณระยะเวลาการทำงาน
$hireDate = '2020-03-15';
$currentDate = date('Y-m-d');
$workPeriod = Date::compare($hireDate, $currentDate);
echo "ทำงานมาแล้ว {$workPeriod['year']} ปี {$workPeriod['month']} เดือน";การจัดรูปแบบวันที่
// จัดรูปแบบวันที่ปัจจุบัน
$formattedToday = Date::format();
// ใช้รูปแบบจากไฟล์ภาษา DATE_FORMAT
// จัดรูปแบบวันที่เฉพาะ
$timestamp = strtotime('2024-01-15 14:30:00');
$formatted = Date::format($timestamp, 'd/m/Y H:i');
// Result: "15/01/2567 14:30" (ถ้าใช้ปี พ.ศ.)
// จัดรูปแบบวันที่จาก string
$dateString = '2024-01-15 14:30:00';
$formatted = Date::format($dateString, 'l, F d, Y');
// Result: "จ., มกราคม 15, 2567" (ขึ้นกับการตั้งค่าภาษา)
// รูปแบบต่างๆ
$formats = [
'd/m/Y' => '15/01/2567',
'Y-m-d' => '2567-01-15',
'l, F d' => 'จันทร์, มกราคม 15',
'H:i:s' => '14:30:00'
];
foreach ($formats as $format => $expected) {
echo Date::format($dateString, $format) . "\n";
}การทำงานกับชื่อวันและเดือน
// ชื่อวัน (0=อาทิตย์, 6=เสาร์)
$dayShort = Date::dateName(1); // "จ."
$dayFull = Date::dateName(1, false); // "จันทร์"
// ชื่อเดือน (1=มกราคม, 12=ธันวาคม)
$monthShort = Date::monthName(1); // "ม.ค."
$monthFull = Date::monthName(1, false); // "มกราคม"
// สร้างปฏิทิน
$calendar = [];
for ($month = 1; $month <= 12; $month++) {
$calendar[$month] = [
'short' => Date::monthName($month, true),
'full' => Date::monthName($month, false)
];
}
// สร้างตัวเลือกวัน
$dayOptions = '';
for ($day = 0; $day < 7; $day++) {
$dayName = Date::dateName($day, false);
$dayOptions .= "<option value=\"{$day}\">{$dayName}</option>";
}การแปลงและแยกวันที่
// แยกส่วนประกอบของวันที่
$dateComponents = Date::parse('2024-01-15 14:30:45');
// Result: ['y' => '2024', 'm' => '01', 'd' => '15', 'h' => '14', 'i' => '30', 's' => '45']
$dateOnly = Date::parse('2024-01-15');
// Result: ['y' => '2024', 'm' => '01', 'd' => '15']
// สร้างวันที่จากส่วนประกอบ
if ($dateComponents) {
$customDate = "{$dateComponents['d']}/{$dateComponents['m']}/{$dateComponents['y']}";
// Result: "15/01/2024"
}
// คำนวณความแตกต่างของเวลา
$time1 = '2024-01-15 10:00:00';
$time2 = '2024-01-15 14:30:00';
$timeDiff = Date::timeDiff($time1, $time2);
// Result: 16200 (seconds) = 4.5 hoursTime Ago - เวลาที่ผ่านมา
// แสดงเวลาที่ผ่านมาแบบเป็นมิตรกับผู้ใช้
$postDate = '2024-01-14 10:00:00';
$timeAgo = Date::timeAgo($postDate);
// Result: "1 {LNG_days} {LNG_ago}" หรือ "2 {LNG_hours} {LNG_ago}"
// ตัวอย่างการใช้งาน
$posts = [
['title' => 'Post 1', 'created_at' => '2024-01-15 10:00:00'],
['title' => 'Post 2', 'created_at' => '2024-01-14 15:30:00'],
['title' => 'Post 3', 'created_at' => '2024-01-10 08:00:00'],
];
foreach ($posts as $post) {
$timeAgo = Date::timeAgo($post['created_at']);
echo "{$post['title']} - {$timeAgo}\n";
}
// Output:
// Post 1 - 2 {LNG_hours} {LNG_ago}
// Post 2 - 1 {LNG_days} {LNG_ago}
// Post 3 - 1 {LNG_week} {LNG_ago}การใช้งานในระบบจริง
class DateTimeManager
{
public function formatUserBirthday($birthDate)
{
$age = Date::age($birthDate);
$formatted = Date::format($birthDate, 'd F Y');
return [
'formatted_date' => $formatted,
'age_text' => $age,
'age_data' => Date::compare($birthDate, date('Y-m-d'))
];
}
public function generateMonthlyReport($year)
{
$report = [];
for ($month = 1; $month <= 12; $month++) {
$report[] = [
'month_number' => $month,
'month_short' => Date::monthName($month, true),
'month_full' => Date::monthName($month, false),
'days_in_month' => date('t', mktime(0, 0, 0, $month, 1, $year))
];
}
return $report;
}
public function formatPostTimestamps($posts)
{
return array_map(function($post) {
$post['formatted_date'] = Date::format($post['created_at'], 'd/m/Y H:i');
$post['time_ago'] = Date::timeAgo($post['created_at']);
$post['date_components'] = Date::parse($post['created_at']);
return $post;
}, $posts);
}
public function calculateWorkingDays($startDate, $endDate)
{
$diff = Date::compare($startDate, $endDate);
// คำนวณวันทำงาน (ไม่นับวันหยุดสุดสัปดาห์)
$totalDays = $diff['days'];
$weeks = floor($totalDays / 7);
$remainingDays = $totalDays % 7;
$workingDays = $weeks * 5; // 5 วันทำงานต่อสัปดาห์
// ตรวจสอบวันที่เหลือ
$start = new DateTime($startDate);
for ($i = 0; $i < $remainingDays; $i++) {
$dayOfWeek = $start->format('w');
if ($dayOfWeek != 0 && $dayOfWeek != 6) { // ไม่ใช่วันเสาร์-อาทิตย์
$workingDays++;
}
$start->add(new DateInterval('P1D'));
}
return $workingDays;
}
}Best Practices
1. การใช้งาน ArrayTool
// ✅ ดี - ใช้ null coalescing เพื่อป้องกัน undefined index
$email = $_POST['email'] ?? '';
// ✅ ดี - ใช้ columns() เพื่อสร้าง options
$categoryOptions = ArrayTool::columns($categories, 'name', 'id');
// ✅ ดี - ใช้ search() แทน loop ซับซ้อน
$activeUsers = ArrayTool::search($users, 'status', 'active');
// ✅ ดี - ใช้ sort() สำหรับการเรียงลำดับ
$sortedProducts = ArrayTool::sort($products, 'price', true);2. การใช้งาน Text
// ✅ ดี - ทำความสะอาดข้อมูลก่อนแสดงผล
$title = Text::htmlspecialchars($_POST['title']);
$summary = Text::cut(Text::oneLine($_POST['content']), 100);
// ✅ ดี - ใช้ template สำหรับข้อความ
$template = "สวัสดี {name}, ยอดเงินคงเหลือของคุณคือ {balance} บาท";
$message = Text::replace($template, [
'{name}' => $userName,
'{balance}' => Number::format($balance)
]);
// ✅ ดี - ตรวจสอบ URL ก่อนใช้งาน
$cleanUrl = Text::url($_POST['website']);
if (!empty($cleanUrl)) {
// ใช้งาน URL
}3. การใช้งาน Number
// ✅ ดี - ใช้ division() เพื่อป้องกัน division by zero
$average = Number::division($total, $count);
// ✅ ดี - จัดรูปแบบตัวเลขก่อนแสดงผล
$formattedPrice = Number::format($price, ',') . ' บาท';
// ✅ ดี - ใช้ printf() สำหรับเลขที่เอกสาร
$invoiceNo = Number::printf("INV-%Y%m-%05d", $sequence);4. การใช้งาน Date
// ✅ ดี - ใช้ format() สำหรับการแสดงผล
$displayDate = Date::format($timestamp, 'd/m/Y');
// ✅ ดี - ใช้ timeAgo() สำหรับ social media style
$postTime = Date::timeAgo($post['created_at']);
// ✅ ดี - ใช้ compare() สำหรับการคำนวณ
$workPeriod = Date::compare($hireDate, date('Y-m-d'));
// ✅ ดี - ตรวจสอบผลลัพธ์จาก parse()
$dateInfo = Date::parse($dateString);
if ($dateInfo) {
// ใช้งานข้อมูลวันที่
}5. Performance Tips
// ✅ ดี - Cache ผลลัพธ์ที่ใช้บ่อย
class UtilityCache
{
private static $monthNames = [];
public static function getMonthName($month, $short = true)
{
$key = $month . '_' . ($short ? 'short' : 'full');
if (!isset(self::$monthNames[$key])) {
self::$monthNames[$key] = Date::monthName($month, $short);
}
return self::$monthNames[$key];
}
}
// ✅ ดี - ใช้ bulk operations
$userNames = ArrayTool::columns($users, 'name', 'id');
$formattedPrices = array_map(function($price) {
return Number::format($price, ',');
}, $prices);
// ✅ ดี - รวมการ filter และ sort
$filteredAndSorted = ArrayTool::sort(
ArrayTool::filter($data, $searchTerm),
'name'
);คลาส Utility เหล่านี้ช่วยให้การจัดการข้อมูลต่างๆ เป็นไปอย่างมีประสิทธิภาพและปลอดภัย การใช้งานอย่างถูกต้องจะช่วยลดโค้ดที่ซ้ำซากและป้องกันข้อผิดพลาดที่อาจเกิดขึ้น