Kotchasan Framework Documentation
Barcode Class - การสร้างบาร์โค้ด
Barcode Class - การสร้างบาร์โค้ด
คลาส Barcode เป็นเครื่องมือสำหรับการสร้างบาร์โค้ดในรูปแบบ Code 128 ในกรอบงาน Kotchasan
Namespace
namespace Kotchasan;ภาพรวม
คลาส Barcode ใช้สำหรับสร้างบาร์โค้ดมาตรฐาน Code 128 และส่งออกเป็นภาพ PNG รองรับการแสดงข้อความ (label) ใต้บาร์โค้ดด้วยฟอนต์ที่กำหนดได้
ใช้เมื่อไหร่:
- ต้องการสร้างบาร์โค้ดสำหรับสินค้า
- ต้องการระบบติดตามสินค้าด้วยบาร์โค้ด
- ต้องการสร้างป้ายราคาพร้อมบาร์โค้ด
- ต้องการระบบจัดการสต๊อกด้วยบาร์โค้ด
ข้อกำหนดของระบบ
- PHP 7.4 ขึ้นไป
- GD Extension (สำหรับสร้างภาพ)
- Font file:
skin/fonts/thsarabunnew-webfont.ttf(สำหรับแสดงข้อความ)
Class Properties
Public Properties
public string $font = ROOT_PATH.'skin/fonts/thsarabunnew-webfont.ttf';- Type: string
- Default:
ROOT_PATH.'skin/fonts/thsarabunnew-webfont.ttf' - Description: เส้นทางไปยังไฟล์ฟอนต์ที่ใช้แสดงข้อความใต้บาร์โค้ด สามารถเปลี่ยนได้หลังจากสร้าง instance
Private Properties
private int $height; // ความสูงของบาร์โค้ด
private int $bar_width = 1; // ความกว้างของแต่ละแถบ (pixels)
private int $width = 0; // ความกว้างรวมของบาร์โค้ด
private array $datas; // ข้อมูลแถบบาร์โค้ด (array of 0/1)
private string $code; // รหัสที่แปลงเป็นบาร์โค้ด
private int $fontSize = 0; // ขนาดฟอนต์สำหรับแสดงข้อความ (0 = ไม่แสดง)ℹ️ Note: Properties เหล่านี้เป็น internal state ไม่สามารถเข้าถึงจากภายนอกได้
Constructor
protected function __construct(string $code, int $height, int $fontSize = 0)⚠️ Warning: Constructor เป็น protected ไม่สามารถเรียกใช้โดยตรงได้ ใช้ factory method create() แทน
Factory Methods
create()
สร้าง Barcode instance (Factory method)
public static function create(
string $code,
int $height = 30,
int $fontSize = 0
): staticParameters:
$code(string, required) - รหัสที่ต้องการแปลงเป็นบาร์โค้ด (รองรับตัวอักษร ตัวเลข และสัญลักษณ์พิเศษตาม Code 128)$height(int, optional, default: 30) - ความสูงของบาร์โค้ดเป็น pixels$fontSize(int, optional, default: 0) - ขนาดฟอนต์สำหรับแสดงข้อความใต้บาร์โค้ด (0 = ไม่แสดงข้อความ)
Returns: Instance ของ Barcode class
Example:
use Kotchasan\Barcode;
// สร้างบาร์โค้ดแบบพื้นฐาน (ความสูง 30px, ไม่มีข้อความ)
$barcode = Barcode::create('123456789');
// สร้างบาร์โค้ดความสูง 50px พร้อมข้อความขนาด 12px
$barcode = Barcode::create('PRODUCT001', 50, 12);
// สร้างบาร์โค้ดขนาดใหญ่พร้อมข้อความ
$barcode = Barcode::create('SKU-2024-001', 80, 14);Public Methods
toPng()
สร้างภาพบาร์โค้ดเป็นรูปแบบ PNG
public function toPng(): stringParameters: ไม่มี
Returns: string - ข้อมูลภาพ PNG แบบ binary (สามารถบันทึกเป็นไฟล์หรือส่งออกตรงๆ)
Example:
use Kotchasan\Barcode;
// สร้างและแสดงบาร์โค้ดในเบราว์เซอร์
$barcode = Barcode::create('123456789', 50, 12);
$imageData = $barcode->toPng();
header('Content-Type: image/png');
echo $imageData;ตัวอย่างการใช้งาน
Example 1: สร้างและบันทึกบาร์โค้ดพื้นฐาน
require_once 'load.php';
use Kotchasan\Barcode;
try {
// สร้าง Barcode instance
$barcode = Barcode::create('123456789');
// สร้างภาพ PNG
$imageData = $barcode->toPng();
// บันทึกเป็นไฟล์
$result = file_put_contents('barcode_123456789.png', $imageData);
if ($result !== false) {
echo "บาร์โค้ดถูกสร้างเรียบร้อย: {$result} bytes\n";
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}Output:
บาร์โค้ดถูกสร้างเรียบร้อย: 1234 bytesExample 2: สร้างบาร์โค้ดพร้อมข้อความและฟอนต์กำหนดเอง
use Kotchasan\Barcode;
// สร้างบาร์โค้ดความสูง 60px พร้อมข้อความขนาด 14px
$barcode = Barcode::create('PRODUCT-2024-001', 60, 14);
// เปลี่ยนฟอนต์ (optional)
$barcode->font = ROOT_PATH . 'skin/fonts/custom-font.ttf';
// สร้างและบันทึกภาพ
$imageData = $barcode->toPng();
file_put_contents('product_barcode.png', $imageData);
echo "บาร์โค้ดพร้อมข้อความถูกสร้างแล้ว\n";Example 3: ระบบสร้างบาร์โค้ดสินค้า
use Kotchasan\Barcode;
/**
* ฟังก์ชันสร้างบาร์โค้ดสินค้าตามขนาดที่กำหนด
*/
function generateProductBarcode(string $productCode, string $size = 'medium'): string
{
// กำหนดขนาดบาร์โค้ด
$sizes = [
'small' => ['height' => 40, 'fontSize' => 10],
'medium' => ['height' => 60, 'fontSize' => 12],
'large' => ['height' => 80, 'fontSize' => 14]
];
$config = $sizes[$size] ?? $sizes['medium'];
// สร้างบาร์โค้ด
$barcode = Barcode::create(
$productCode,
$config['height'],
$config['fontSize']
);
return $barcode->toPng();
}
// ใช้งาน
$productCode = 'SKU-12345';
$barcodeImage = generateProductBarcode($productCode, 'large');
// บันทึกไฟล์
file_put_contents("barcodes/{$productCode}.png", $barcodeImage);
echo "สร้างบาร์โค้ดสำหรับสินค้า {$productCode} เรียบร้อย\n";Example 4: ระบบจัดการบาร์โค้ดแบบสมบูรณ์
use Kotchasan\Barcode;
/**
* คลาสจัดการบาร์โค้ดสินค้า
*/
class BarcodeManager
{
private string $basePath;
public function __construct(string $basePath = 'barcodes/')
{
$this->basePath = rtrim($basePath, '/') . '/';
// สร้างโฟลเดอร์ถ้าไม่มี
if (!is_dir($this->basePath)) {
mkdir($this->basePath, 0755, true);
}
}
/**
* สร้างบาร์โค้ดเดียว
*/
public function generate(string $code, array $options = []): array
{
$height = $options['height'] ?? 60;
$fontSize = $options['fontSize'] ?? 12;
$barcode = Barcode::create($code, $height, $fontSize);
// เปลี่ยนฟอนต์ถ้าระบุ
if (isset($options['font'])) {
$barcode->font = $options['font'];
}
$imageData = $barcode->toPng();
return [
'code' => $code,
'data' => $imageData,
'size' => strlen($imageData)
];
}
/**
* สร้างและบันทึกบาร์โค้ด
*/
public function save(string $code, array $options = []): array
{
$result = $this->generate($code, $options);
$filename = $options['filename'] ?? $code . '.png';
$filepath = $this->basePath . $filename;
$bytesWritten = file_put_contents($filepath, $result['data']);
return [
'success' => $bytesWritten !== false,
'code' => $code,
'filepath' => $filepath,
'filename' => $filename,
'size' => $bytesWritten
];
}
/**
* สร้างบาร์โค้ดหลายรายการพร้อมกัน
*/
public function batchGenerate(array $codes, array $options = []): array
{
$results = [];
foreach ($codes as $code) {
$results[$code] = $this->save($code, $options);
}
return $results;
}
/**
* ตรวจสอบว่าบาร์โค้ดมีอยู่แล้วหรือไม่
*/
public function exists(string $code): bool
{
return file_exists($this->basePath . $code . '.png');
}
/**
* ลบบาร์โค้ด
*/
public function delete(string $code): bool
{
$filepath = $this->basePath . $code . '.png';
if (file_exists($filepath)) {
return unlink($filepath);
}
return false;
}
}
// ตัวอย่างการใช้งาน BarcodeManager
// สร้าง manager
$manager = new BarcodeManager('storage/barcodes/');
// สร้างบาร์โค้ดเดียว
$result = $manager->save('PRODUCT001', [
'height' => 70,
'fontSize' => 14
]);
if ($result['success']) {
echo "บันทึกบาร์โค้ดที่: {$result['filepath']}\n";
echo "ขนาดไฟล์: {$result['size']} bytes\n";
}
// สร้างบาร์โค้ดหลายรายการ
$productCodes = ['PROD001', 'PROD002', 'PROD003', 'PROD004', 'PROD005'];
$results = $manager->batchGenerate($productCodes, [
'height' => 60,
'fontSize' => 12
]);
echo "\nสร้างบาร์โค้ดทั้งหมด: " . count($results) . " รายการ\n";
foreach ($results as $code => $result) {
if ($result['success']) {
echo "✓ {$code}: {$result['size']} bytes\n";
} else {
echo "✗ {$code}: ล้มเหลว\n";
}
}Output:
บันทึกบาร์โค้ดที่: storage/barcodes/PRODUCT001.png
ขนาดไฟล์: 1456 bytes
สร้างบาร์โค้ดทั้งหมด: 5 รายการ
✓ PROD001: 1234 bytes
✓ PROD002: 1256 bytes
✓ PROD003: 1245 bytes
✓ PROD004: 1267 bytes
✓ PROD005: 1289 bytesExample 5: การผสานกับระบบฐานข้อมูล
use Kotchasan\Barcode;
/**
* ระบบบาร์โค้ดสำหรับสินค้าในฐานข้อมูล
*/
class ProductBarcode
{
private $db;
private BarcodeManager $barcodeManager;
public function __construct($database)
{
$this->db = $database;
$this->barcodeManager = new BarcodeManager('public/barcodes/');
}
/**
* สร้างบาร์โค้ดสำหรับสินค้า
*/
public function createForProduct(int $productId): array
{
// ดึงข้อมูลสินค้า
$product = $this->db->createQuery()
->select('id', 'code', 'name')
->from('products')
->where(['id', $productId])
->first();
if (!$product) {
return [
'success' => false,
'error' => 'ไม่พบสินค้า'
];
}
// สร้างบาร์โค้ด
$result = $this->barcodeManager->save($product->code, [
'height' => 60,
'fontSize' => 12
]);
if ($result['success']) {
// อัพเดทข้อมูลในฐานข้อมูล
$this->db->createQuery()
->update('products')
->set([
'barcode_path' => $result['filepath'],
'barcode_generated_at' => date('Y-m-d H:i:s')
])
->where(['id', $productId])
->execute();
}
return $result;
}
/**
* สร้างบาร์โค้ดสำหรับสินค้าทั้งหมดที่ยังไม่มีบาร์โค้ด
*/
public function generateForAllProducts(): array
{
$products = $this->db->createQuery()
->select('id', 'code')
->from('products')
->where(['barcode_path', 'IS', null])
->toArray()
->execute();
$results = [
'total' => count($products),
'success' => 0,
'failed' => 0,
'details' => []
];
foreach ($products as $product) {
$result = $this->createForProduct($product['id']);
if ($result['success']) {
$results['success']++;
} else {
$results['failed']++;
}
$results['details'][$product['code']] = $result;
}
return $results;
}
/**
* ดาวน์โหลดบาร์โค้ดสำหรับสินค้า
*/
public function download(string $productCode): void
{
$barcode = Barcode::create($productCode, 60, 12);
$imageData = $barcode->toPng();
header('Content-Type: image/png');
header('Content-Disposition: attachment; filename="barcode_' . $productCode . '.png"');
header('Content-Length: ' . strlen($imageData));
echo $imageData;
}
}Best Practices
✅ ควรทำ:
// 1. ใช้ try-catch เพื่อจัดการ error
try {
$barcode = Barcode::create('CODE123', 60, 12);
$data = $barcode->toPng();
file_put_contents('barcode.png', $data);
} catch (Exception $e) {
error_log("Barcode error: " . $e->getMessage());
}
// 2. ตรวจสอบว่าสร้างภาพสำเร็จ
$imageData = $barcode->toPng();
if (strlen($imageData) > 0) {
file_put_contents('barcode.png', $imageData);
}
// 3. ใช้ขนาดที่เหมาะสม
$barcode = Barcode::create('CODE', 60, 12); // ดี - อ่านง่าย
// 4. จัดเก็บไฟล์อย่างเป็นระบบ
$path = "barcodes/" . date('Y/m/') . $code . '.png';❌ ไม่ควรทำ:
// 1. อย่าสร้างบาร์โค้ดที่เล็กเกินไป
$barcode = Barcode::create('CODE', 10, 6); // ไม่ดี - อ่านยาก
// 2. อย่าลืมตรวจสอบว่า GD extension ติดตั้งแล้ว
if (!extension_loaded('gd')) {
die('GD extension required');
}
// 3. อย่าใช้ฟอนต์ที่ไม่มีจริง
$barcode->font = 'path/to/nonexistent/font.ttf'; // จะ error
// 4. อย่าสร้างบาร์โค้ดซ้ำซ้อนโดยไม่จำเป็น
// ควรเช็คว่ามีไฟล์อยู่แล้วหรือไม่ก่อนสร้างใหม่ข้อควรระวัง
1. การรองรับตัวอักษร
⚠️ Warning: Code 128 รองรับตัวอักษรและสัญลักษณ์เฉพาะบางตัวเท่านั้น
// ✅ รองรับ
$barcode = Barcode::create('ABC123');
$barcode = Barcode::create('Product-001');
$barcode = Barcode::create('SKU_2024_01');
// ❌ อาจมีปัญหา - ตัวอักษรพิเศษบางตัว
$barcode = Barcode::create('สินค้า123'); // ไทย - ไม่รองรับ
$barcode = Barcode::create('產品123'); // จีน - ไม่รองรับ2. GD Extension
📋 Requirements: ต้องติดตั้ง GD extension
// ตรวจสอบก่อนใช้งาน
if (!extension_loaded('gd')) {
throw new Exception('GD extension is required for barcode generation');
}3. Font File
ℹ️ Note: ถ้า fontSize > 0 ต้องมีไฟล์ฟอนต์
// ตรวจสอบไฟล์ฟอนต์
$barcode = Barcode::create('CODE', 60, 12);
if (!file_exists($barcode->font)) {
// ถ้าไม่มีฟอนต์ ให้ปิดการแสดงข้อความ
$barcode = Barcode::create('CODE', 60, 0); // fontSize = 0
}4. Memory และ Performance
// สร้างบาร์โค้ดจำนวนมาก - ควรทำทีละชุด
$codes = range(1, 10000); // 10,000 บาร์โค้ด
// ✅ ดี - แบ่งทำทีละ batch
$batches = array_chunk($codes, 100);
foreach ($batches as $batch) {
foreach ($batch as $code) {
$barcode = Barcode::create($code);
file_put_contents("barcode_{$code}.png", $barcode->toPng());
}
// Clear memory
gc_collect_cycles();
}Common Mistakes
❌ ข้อผิดพลาด: เรียก toPng() ด้วย parameters
// ❌ ผิด - toPng() ไม่รับ parameters
$barcode = Barcode::create('CODE');
$imageData = $barcode->toPng('CODE', 200, 80); // ERROR!
// ✅ ถูก - กำหนดค่าที่ create()
$barcode = Barcode::create('CODE', 80, 14);
$imageData = $barcode->toPng();วิธีแก้: parameters ทั้งหมดต้องส่งผ่าน create() เท่านั้น
❌ ข้อผิดพลาด: ไม่ตรวจสอบว่าสร้างภาพสำเร็จ
// ❌ ไม่ดี
$imageData = $barcode->toPng();
file_put_contents('barcode.png', $imageData);
// ✅ ดี
$imageData = $barcode->toPng();
if (strlen($imageData) > 0) {
$result = file_put_contents('barcode.png', $imageData);
if ($result === false) {
throw new Exception('Failed to save barcode');
}
}❌ ข้อผิดพลาด: ใช้ชื่อไฟล์ที่มีตัวอักษรพิเศษ
// ❌ อาจมีปัญหา
file_put_contents('barcode/สินค้า 001.png', $imageData);
// ✅ ดี - ใช้ชื่อ safe
$filename = 'barcode_' . preg_replace('/[^a-zA-Z0-9_-]/', '_', $code) . '.png';
file_put_contents($filename, $imageData);คำถามที่พบบ่อย (FAQ)
Q: สามารถเปลี่ยนสีบาร์โค้ดได้หรือไม่?
A: ไม่ได้โดยตรง คลาส Barcode สร้างบาร์โค้ดสีดำบนพื้นขาวเท่านั้น หากต้องการสีอื่นต้องประมวลผลภาพภายหลัง
Q: รองรับ barcode format อื่นนอกจาก Code 128 หรือไม่?
A: ไม่ คลาสนี้รองรับเฉพาะ Code 128 เท่านั้น
Q: สามารถแสดงบาร์โค้ดในเบราว์เซอร์โดยตรงได้หรือไม่?
A: ได้ ใช้ header('Content-Type: image/png') และ echo ข้อมูลภาพออกไป
Q: ขนาดที่เหมาะสมสำหรับบาร์โค้ดคือเท่าไร?
A: แนะนำความสูง 60-80 pixels สำหรับการแสดงผลทั่วไป และ fontSize 12-14 สำหรับข้อความ
Related Classes
💡 Tip: สำหรับระบบขนาดใหญ่ ควรสร้าง BarcodeManager class เพื่อจัดการบาร์โค้ดแบบรวมศูนย์
⚠️ Important: ตรวจสอบว่า GD extension ติดตั้งแล้วก่อนใช้งาน
การติดตั้ง/เตรียมความพร้อม
สิ่งที่ต้องเตรียมหรือกำหนดค่าก่อนใช้งาน
การใช้งานพื้นฐาน
ตัวอย่างสั้นๆ ที่รันได้ พร้อมคำอธิบายและผลลัพธ์ที่คาดหวัง
// การใช้งานฐานข้อมูลเบื้องต้น (เน้นการสร้าง SQL)
$db = \Kotchasan\DB::create();
$user = $db->first('user', ['id' => 1]);
// ผลลัพธ์: object ของผู้ใช้ id 1 หรือ nullฟีเจอร์หลัก
ความสามารถสำคัญและกรณีใช้งานทั่วไป
- รูปแบบการใช้ DB แบบง่าย
- รองรับ parameter binding เป็นค่าเริ่มต้น
- ใช้ร่วมกับ QueryBuilder สำหรับเคสซับซ้อน
ตัวอย่างขั้นสูง
ตัวอย่างที่ซับซ้อนขึ้นและการใช้งานร่วมกับส่วนอื่น
// ใช้ QueryBuilder สำหรับเคสซับซ้อน
$db = \Kotchasan\Database::create();
$q = $db->select(['u.id', 'u.name'])->from('users u')
->where(['u.status', 1])
->orderBy('u.name');
$sql = $q->toSql();
// ผลลัพธ์: SELECT ที่มี WHERE และ ORDER BYAPI Reference
สรุปเมธอดสำคัญและพารามิเตอร์ (ดูรายละเอียดด้านบน)
เพิ่มเติม
ลิงก์ไปยังหัวข้ออื่นที่เกี่ยวข้องในเอกสารนี้