Kotchasan Framework Documentation

Kotchasan Framework Documentation

Config Class - Configuration Management

TH 05 Feb 2026 07:44

Config Class - Configuration Management

คลาส Config เป็นคลาสสำหรับจัดการ configuration ของ Kotchasan Framework ใช้ Singleton pattern และเก็บค่า configuration เป็น public properties

Namespace

namespace Kotchasan;

ภาพรวม

Config จัดการ configuration ของ framework ผ่าน public properties รวมถึง:

  • Email Configuration - การตั้งค่า mail server
  • Application Settings - ชื่อเว็บ, ภาษา, timezone
  • Security Settings - password encryption, cache
  • Singleton Pattern - สร้าง instance เพียงครั้งเดียว

ใช้เมื่อไหร่:

  • อ่านค่า configuration ของแอปพลิเคชัน
  • เข้าถึง email settings
  • จัดการ timezone และ language settings
  • โหลดและบันทึกไฟล์ config

ข้อกำหนดของระบบ

  • PHP 7.4 ขึ้นไป
  • Kotchasan Framework

Class Pattern

Config ใช้ Singleton Pattern:

  • สร้าง instance ได้เพียงครั้งเดียว
  • เข้าถึงผ่าน Config::create()
  • Properties เป็น public สามารถเข้าถึงโดยตรง
Kotchasan\Config (Singleton)

การใช้งานพื้นฐาน

สร้าง Instance

use Kotchasan\Config;

// สร้าง/ดึง singleton instance
$config = Config::create();

// เรียกซ้ำจะได้ instance เดิม
$sameConfig = Config::create();

คำอธิบาย:

  • สร้าง DB instance
  • เรียกอ่านข้อมูลแบบง่าย
  • บรรทัดคอมเมนต์ระบุผลลัพธ์ที่คาดหวัง

เข้าถึง Properties โดยตรง

$config = Config::create();

// อ่านค่าโดยตรง
$title = $config->web_title;
$timezone = $config->timezone;
$host = $config->email_Host;

ใช้ Method get() พร้อม Type Conversion

$config = Config::create();

// String (default)
$title = $config->get('web_title', 'Default Title');

// Integer - แปลงเป็น int อัตโนมัติ
$port = $config->get('email_Port', 25);  // returns int

// Boolean - แปลงเป็น bool อัตโนมัติ
$auth = $config->get('email_SMTPAuth', false);  // returns bool

// Float - แปลงเป็น float อัตโนมัติ
$expire = $config->get('cache_expire', 0.0);  // returns float

Static Methods

create()

สร้างหรือดึง singleton instance ของ Config

public static function create(): static

Parameters: ไม่มี

Returns: static - Config instance (singleton)

Example:

use Kotchasan\Config;

// สร้าง instance ครั้งแรก
$config = Config::create();

// เรียกอีกครั้งได้ instance เดิม
$sameConfig = Config::create();

var_dump($config === $sameConfig);  // true

load()

โหลดไฟล์ config และคืนค่าเป็น object

public static function load(string $file): object

Parameters:

  • $file (string, required) - Path ของไฟล์ config (fullpath)

Returns: object - Config data เป็น object

Example:

use Kotchasan\Config;

// โหลดไฟล์ config
$config = Config::load(ROOT_PATH . 'settings/config.php');

// เข้าถึงค่า
echo $config->web_title;
echo $config->database['host'];

save()

บันทึกค่า configuration ลงไฟล์

public static function save(array $config, string $file): bool

Parameters:

  • $config (array, required) - ข้อมูล config ที่ต้องการบันทึก
  • $file (string, required) - Path ของไฟล์ (fullpath)

Returns: bool - true ถ้าบันทึกสำเร็จ, false ถ้าล้มเหลว

Features:

  • สร้างไฟล์ PHP config ด้วย var_export()
  • Reset opcache อัตโนมัติ (ถ้ามี)
  • สร้างไฟล์ที่อ่านง่าย

Example:

use Kotchasan\Config;

$config = [
    'web_title' => 'My Website',
    'timezone' => 'Asia/Bangkok',
    'database' => [
        'host' => 'localhost',
        'name' => 'mydb'
    ]
];

// บันทึกลงไฟล์
$success = Config::save($config, ROOT_PATH . 'settings/config.php');

if ($success) {
    echo "Config saved successfully!";
}

Instance Methods

get()

ดึงค่า property พร้อมแปลงประเภทข้อมูลอัตโนมัติตาม default value

public function get(string $key, mixed $default = ''): mixed

Parameters:

  • $key (string, required) - ชื่อ property
  • $default (mixed, optional, default: '') - ค่า default และกำหนด type ที่ต้องการ

Returns: mixed - ค่าที่ได้พร้อมแปลงประเภทแล้ว

Type Conversion Rules:

  • $default เป็น int → คืนค่า int
  • $default เป็น float → คืนค่า float
  • $default เป็น bool → คืนค่า bool
  • อื่นๆ → คืนค่าตามประเภทเดิม

Example:

$config = Config::create();

// String (ไม่แปลงประเภท)
$title = $config->get('web_title', 'Default');
// returns string

// Integer (แปลงเป็น int)
$port = $config->get('email_Port', 25);
// returns int, แม้ว่า property จะเป็น string ก็แปลงเป็น int

// Boolean (แปลงเป็น bool)
$auth = $config->get('email_SMTPAuth', false);
// returns bool

// Float (แปลงเป็น float)
$expire = $config->get('cache_expire', 0.0);
// returns float

// ถ้าไม่มี property คืนค่า default
$missing = $config->get('not_exists', 'default value');
// returns 'default value'

Configuration Properties

Email Configuration (8 Properties)

email_Host

Mail server hostname

public $email_Host = 'localhost'

Type: string
Default: 'localhost'
Examples: 'localhost', 'smtp.gmail.com', 'mail.yourdomain.com'

email_Port

Mail server port number

public $email_Port = 25

Type: int
Default: 25
Common Values:

  • 25 - Standard SMTP
  • 465 - SMTP over SSL
  • 587 - SMTP with STARTTLS (recommended)

email_Username

Username สำหรับ authenticate กับ mail server

public $email_Username = ''

Type: string
Default: ''

email_Password

Password สำหรับ authenticate กับ mail server

public $email_Password = ''

Type: string
Default: ''

email_SMTPAuth

เปิดใช้ SMTP authentication หรือไม่

public $email_SMTPAuth = false

Type: bool
Default: false
Note: ต้องตั้งเป็น true ถ้าใช้ Gmail หรือ mail server ที่ต้อง authentication

email_SMTPSecure

SSL encryption protocol

public $email_SMTPSecure = ''

Type: string
Default: ''
Values:

  • '' - ไม่ใช้ encryption
  • 'ssl' - SSL encryption
  • 'tls' - TLS encryption

email_charset

Character set สำหรับอีเมล

public $email_charset = 'utf-8'

Type: string
Default: 'utf-8'
Common Values: 'utf-8', 'tis-620', 'iso-8859-1'

email_use_phpMailer

เลือกโปรแกรมส่งอีเมล

public $email_use_phpMailer = 1

Type: int
Default: 1
Values:

  • 1 - ใช้ PHPMailer
  • 0 - ใช้ PHP mail() function

Application Settings (9 Properties)

web_title

ชื่อเว็บไซต์

public $web_title = 'Kotchasan PHP Framework'

Type: string
Default: 'Kotchasan PHP Framework'

web_description

คำอธิบายเว็บไซต์

public $web_description = 'PHP Framework developed by Thai people'

Type: string
Default: 'PHP Framework developed by Thai people'

char_set

Character set หลักของระบบ

public $char_set = 'UTF-8'

Type: string
Default: 'UTF-8'

timezone

Server timezone

public $timezone = 'Asia/Bangkok'

Type: string
Default: 'Asia/Bangkok'
Common Values: 'Asia/Bangkok', 'UTC', 'America/New_York', 'Europe/London'

skin

Template ที่ใช้งาน (ชื่อ folder)

public $skin = 'default'

Type: string
Default: 'default'

languages

ภาษาที่รองรับ (อยู่ใน folder language/)

public $languages = ['th']

Type: array
Default: ['th']
Example: ['th', 'en', 'jp']

login_fields

ฟิลด์ที่ใช้สำหรับ login

public $login_fields = ['username']

Type: array
Default: ['username']
Example: ['username', 'email', 'phone']

noreply_email

Email สำหรับส่งอีเมลแบบ no-reply

public $noreply_email = ''

Type: string
Default: ''
Example: 'no-reply@yourdomain.com'

Security Settings (2 Properties)

password_key

Encryption key สำหรับเข้ารหัส password

public $password_key = '1234567890'

Type: string
Default: '1234567890'
Warning: ⚠️ ต้องเปลี่ยนค่านี้ใน production!

cache_expire

เวลา cache expiration (วินาที)

public $cache_expire = 0

Type: int
Default: 0 (ไม่ใช้ cache)
Example: 3600 (1 ชั่วโมง), 86400 (1 วัน)

ตัวอย่างการใช้งาน

Example 1: Basic Configuration

use Kotchasan\Config;

// สร้าง instance
$config = Config::create();

// อ่านค่า
echo "Website: " . $config->web_title . "\n";
echo "Timezone: " . $config->timezone . "\n";
echo "Charset: " . $config->char_set . "\n";

// ใช้ get() พร้อม default
$cache = $config->get('cache_expire', 3600);
echo "Cache Expire: {$cache} seconds\n";

Example 2: Email Configuration

use Kotchasan\Config;

$config = Config::create();

// ตั้งค่า SMTP สำหรับ Gmail
$config->email_Host = 'smtp.gmail.com';
$config->email_Port = 587;
$config->email_SMTPAuth = true;
$config->email_SMTPSecure = 'tls';
$config->email_Username = 'your-email@gmail.com';
$config->email_Password = 'your-app-password';
$config->email_charset = 'utf-8';
$config->noreply_email = 'no-reply@yourdomain.com';

// ตรวจสอบค่า
if ($config->email_SMTPAuth) {
    echo "SMTP Authentication: Enabled\n";
    echo "Server: {$config->email_Host}:{$config->email_Port}\n";
}

Example 3: Loading Config Files

use Kotchasan\Config;

// โหลด config หลัก
$mainConfig = Config::load(ROOT_PATH . 'settings/config.php');

// โหลด config ตาม environment
$env = getenv('APP_ENV') ?: 'development';
$envConfig = Config::load(ROOT_PATH . "settings/{$env}.php");

// Merge configs
$config = Config::create();
foreach ($mainConfig as $key => $value) {
    $config->{$key} = $value;
}
foreach ($envConfig as $key => $value) {
    $config->{$key} = $value;  // Override with env-specific
}

Example 4: Saving Config Files

use Kotchasan\Config;

// สร้าง config array
$config = [
    'web_title' => 'My Application',
    'web_description' => 'My awesome app',
    'timezone' => 'Asia/Bangkok',
    'char_set' => 'UTF-8',

    'email_Host' => 'smtp.gmail.com',
    'email_Port' => 587,
    'email_SMTPAuth' => true,
    'email_SMTPSecure' => 'tls',
    'email_Username' => 'admin@example.com',
    'email_Password' => 'secret',

    'languages' => ['th', 'en'],
    'login_fields' => ['username', 'email'],

    'password_key' => bin2hex(random_bytes(16)),
    'cache_expire' => 3600
];

// บันทึกลงไฟล์
$file = ROOT_PATH . 'settings/config.php';
if (Config::save($config, $file)) {
    echo "Configuration saved successfully!\n";
} else {
    echo "Failed to save configuration.\n";
}

Example 5: Multi-Environment Setup

use Kotchasan\Config;

// settings/config.php (base config)
return [
    'web_title' => 'My App',
    'char_set' => 'UTF-8',
    'timezone' => 'Asia/Bangkok',
    'languages' => ['th', 'en']
];

// settings/development.php
return [
    'email_Host' => 'localhost',
    'email_Port' => 1025,  // MailHog
    'cache_expire' => 0,    // No cache in dev
    'password_key' => 'dev-key-not-secure'
];

// settings/production.php
return [
    'email_Host' => 'smtp.gmail.com',
    'email_Port' => 587,
    'email_SMTPAuth' => true,
    'email_SMTPSecure' => 'tls',
    'cache_expire' => 3600,
    'password_key' => getenv('APP_KEY')  // From environment
];

// ใช้งาน
$env = getenv('APP_ENV') ?: 'development';

$config = Config::create();
// Framework จะโหลด settings/config.php อัตโนมัติ

// โหลด env-specific config
$envConfig = Config::load(ROOT_PATH . "settings/{$env}.php");
foreach ($envConfig as $key => $value) {
    $config->{$key} = $value;
}

Best Practices

✅ ควรทำ:

// 1. ใช้ Singleton pattern
$config = Config::create();  // ดี
$config2 = Config::create();  // ได้ instance เดิม

// 2. ใช้ get() สำหรับ type conversion
$port = $config->get('email_Port', 25);  // แปลงเป็น int
$auth = $config->get('email_SMTPAuth', false);  // แปลงเป็น bool

// 3. ตั้งค่า password_key ที่ปลอดภัย
$config->password_key = bin2hex(random_bytes(32));

// 4. แยก config ตาม environment
Config::load("settings/{$env}.php");

// 5. บันทึกด้วย save() method
Config::save($configArray, $file);

❌ ไม่ควรทำ:

// 1. อย่าสร้าง instance ใหม่
$config = new Config();  // ไม่ดี - ใช้ create() แทน

// 2. อย่าใช้ password_key default
$config->password_key = '1234567890';  // อันตราย!

// 3. อย่าใส่ sensitive data ใน version control
// ใช้ environment variables แทน
$config->email_Password = getenv('SMTP_PASSWORD');

// 4. อย่าแก้ไฟล์ config ด้วยมือในขณะ runtime
// ใช้ save() method แทน

Common Mistakes

❌ ข้อผิดพลาด: ใช้ method ที่ไม่มี

// ❌ ผิด - ไม่มี method เหล่านี้!
Config::set('key', 'value');  // ❌ ไม่มี set()!
Config::all();                 // ❌ ไม่มี all()!
Config::has('key');            // ❌ ไม่มี has()!

// ✅ ถูก - ใช้ properties โดยตรง
$config = Config::create();
$config->web_title = 'New Title';  // ตั้งค่า
$title = $config->web_title;        // อ่านค่า

❌ ข้อผิดพลาด: Type conversion ผิด

// ❌ ผิด - ไม่ได้ type ที่ต้องการ
$port = $config->get('email_Port');  // returns string หรือ mixed
if ($port === 25) {  // อาจเป็น '25' (string) ไม่ตรงกับ 25 (int)
    // ...
}

// ✅ ถูก - ระบุ default เป็น type ที่ต้องการ
$port = $config->get('email_Port', 25);  // returns int
if ($port === 25) {  // ถูกต้อง!
    // ...
}

❌ ข้อผิดพลาด: ลืม check ก่อน save

// ❌ ผิด - ไม่ check return value
Config::save($config, $file);

// ✅ ถูก - check ว่าบันทึกสำเร็จหรือไม่
if (!Config::save($config, $file)) {
    throw new \Exception("Failed to save config");
}

FAQ (คำถามที่พบบ่อย)

Q: Config class มี set(), all(), has() methods หรือไม่?
A: ไม่มี! Methods เหล่านี้ไม่มีใน source code ให้ใช้การเข้าถึง properties โดยตรงแทน:

$config->web_title = 'New';  // แทน set()
$title = $config->web_title;  // แทน get()
isset($config->web_title);    // แทน has()

Q: Config เป็น Singleton หรือไม่?
A: ใช่ ใช้ Config::create() จะได้ instance เดียวกันเสมอ

Q: get() method แปลงประเภทข้อมูลอย่างไร?
A: แปลงตามประเภทของ $default:

  • get('key', 0) → int
  • get('key', 0.0) → float
  • get('key', false) → bool
  • get('key', '') → ไม่แปลง

Q: จะแยก config ตาม environment ได้อย่างไร?
A: สร้างไฟล์แยก (development.php, production.php) แล้วโหลดด้วย load() ตาม environment variable

Q: Framework โหลด config อัตโนมัติจากที่ไหน?
A: จาก constructor โหลดจาก:

  1. ROOT_PATH/settings/config.php
  2. APP_PATH/settings/config.php (ถ้ามี)

Q: จะเปลี่ยน password_key อย่างไรดี?
A: ใช้:

$config->password_key = bin2hex(random_bytes(32));
  • Email - ใช้ email configuration
  • Language - ใช้ languages configuration
  • Session - Session configuration

💡 Tip: ใช้ get() method เมื่อต้องการ type conversion อัตโนมัติ

⚠️ Security: เปลี่ยน password_key จากค่า default ก่อนใช้งานจริง!

📝 Note: Config เป็น Singleton - เรียก create() กี่ครั้งก็ได้ instance เดิม