Kotchasan Framework Documentation
Config Class - Configuration Management
Config Class - Configuration Management
The Config class manages configuration for the Kotchasan Framework using the Singleton pattern with public properties for configuration storage.
Namespace
namespace Kotchasan;Overview
Config manages framework configuration through public properties including:
- Email Configuration - Mail server settings
- Application Settings - Website name, language, timezone
- Security Settings - Password encryption, cache
- Singleton Pattern - Single instance creation
When to use:
- Read application configuration
- Access email settings
- Manage timezone and language settings
- Load and save config files
System Requirements
- PHP 7.4 or higher
- Kotchasan Framework
Class Pattern
Config uses the Singleton Pattern:
- Only one instance can be created
- Access via
Config::create() - Properties are public and directly accessible
Kotchasan\Config (Singleton)Basic Usage
Create Instance
use Kotchasan\Config;
// Create/get singleton instance
$config = Config::create();
// Calling again returns same instance
$sameConfig = Config::create();Explanation:
- Create the DB instance
- Run a simple read operation
- The comment shows the expected result
Direct Property Access
$config = Config::create();
// Read values directly
$title = $config->web_title;
$timezone = $config->timezone;
$host = $config->email_Host;Using get() Method with Type Conversion
$config = Config::create();
// String (default)
$title = $config->get('web_title', 'Default Title');
// Integer - auto-converts to int
$port = $config->get('email_Port', 25); // returns int
// Boolean - auto-converts to bool
$auth = $config->get('email_SMTPAuth', false); // returns bool
// Float - auto-converts to float
$expire = $config->get('cache_expire', 0.0); // returns floatStatic Methods
create()
Creates or retrieves the singleton Config instance
public static function create(): staticParameters: None
Returns: static - Config instance (singleton)
Example:
use Kotchasan\Config;
// Create instance first time
$config = Config::create();
// Calling again returns same instance
$sameConfig = Config::create();
var_dump($config === $sameConfig); // trueload()
Loads config file and returns as object
public static function load(string $file): objectParameters:
$file(string, required) - Config file path (fullpath)
Returns: object - Config data as object
Example:
use Kotchasan\Config;
// Load config file
$config = Config::load(ROOT_PATH . 'settings/config.php');
// Access values
echo $config->web_title;
echo $config->database['host'];save()
Saves configuration to file
public static function save(array $config, string $file): boolParameters:
$config(array, required) - Config data to save$file(string, required) - File path (fullpath)
Returns: bool - true if saved successfully, false on failure
Features:
- Creates PHP config file with
var_export() - Automatically resets opcache (if available)
- Creates readable file format
Example:
use Kotchasan\Config;
$config = [
'web_title' => 'My Website',
'timezone' => 'Asia/Bangkok',
'database' => [
'host' => 'localhost',
'name' => 'mydb'
]
];
// Save to file
$success = Config::save($config, ROOT_PATH . 'settings/config.php');
if ($success) {
echo "Config saved successfully!";
}Instance Methods
get()
Gets property value with automatic type conversion based on default value
public function get(string $key, mixed $default = ''): mixedParameters:
$key(string, required) - Property name$default(mixed, optional, default: '') - Default value and desired type
Returns: mixed - Value with type conversion applied
Type Conversion Rules:
$defaultisint→ returnsint$defaultisfloat→ returnsfloat$defaultisbool→ returnsbool- Otherwise → returns original type
Example:
$config = Config::create();
// String (no conversion)
$title = $config->get('web_title', 'Default');
// returns string
// Integer (converts to int)
$port = $config->get('email_Port', 25);
// returns int, even if property is string
// Boolean (converts to bool)
$auth = $config->get('email_SMTPAuth', false);
// returns bool
// Float (converts to float)
$expire = $config->get('cache_expire', 0.0);
// returns float
// If property doesn't exist, returns 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 = 25Type: int
Default: 25
Common Values:
25- Standard SMTP465- SMTP over SSL587- SMTP with STARTTLS (recommended)
email_Username
Username for mail server authentication
public $email_Username = ''Type: string
Default: ''
email_Password
Password for mail server authentication
public $email_Password = ''Type: string
Default: ''
email_SMTPAuth
Enable SMTP authentication
public $email_SMTPAuth = falseType: bool
Default: false
Note: Must be true for Gmail or mail servers requiring authentication
email_SMTPSecure
SSL encryption protocol
public $email_SMTPSecure = ''Type: string
Default: ''
Values:
''- No encryption'ssl'- SSL encryption'tls'- TLS encryption
email_charset
Character set for emails
public $email_charset = 'utf-8'Type: string
Default: 'utf-8'
Common Values: 'utf-8', 'tis-620', 'iso-8859-1'
email_use_phpMailer
Select email sending program
public $email_use_phpMailer = 1Type: int
Default: 1
Values:
1- Use PHPMailer0- Use PHP mail() function
Application Settings (9 Properties)
web_title
Website title
public $web_title = 'Kotchasan PHP Framework'Type: string
Default: 'Kotchasan PHP Framework'
web_description
Website description
public $web_description = 'PHP Framework developed by Thai people'Type: string
Default: 'PHP Framework developed by Thai people'
char_set
System default 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 in use (folder name)
public $skin = 'default'Type: string
Default: 'default'
languages
Supported languages (in language/ folder)
public $languages = ['th']Type: array
Default: ['th']
Example: ['th', 'en', 'jp']
login_fields
Fields used for login
public $login_fields = ['username']Type: array
Default: ['username']
Example: ['username', 'email', 'phone']
noreply_email
Email address for no-reply emails
public $noreply_email = ''Type: string
Default: ''
Example: 'no-reply@yourdomain.com'
Security Settings (2 Properties)
password_key
Encryption key for password encryption
public $password_key = '1234567890'Type: string
Default: '1234567890'
Warning: ⚠️ Must change this in production!
cache_expire
Cache expiration time (seconds)
public $cache_expire = 0Type: int
Default: 0 (no cache)
Example: 3600 (1 hour), 86400 (1 day)
Usage Examples
Example 1: Basic Configuration
use Kotchasan\Config;
// Create instance
$config = Config::create();
// Read values
echo "Website: " . $config->web_title . "\n";
echo "Timezone: " . $config->timezone . "\n";
echo "Charset: " . $config->char_set . "\n";
// Use get() with default
$cache = $config->get('cache_expire', 3600);
echo "Cache Expire: {$cache} seconds\n";Example 2: Email Configuration
use Kotchasan\Config;
$config = Config::create();
// Configure SMTP for 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';
// Check configuration
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;
// Load main config
$mainConfig = Config::load(ROOT_PATH . 'settings/config.php');
// Load environment-specific config
$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;
// Create 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
];
// Save to file
$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
];
// Usage
$env = getenv('APP_ENV') ?: 'development';
$config = Config::create();
// Framework auto-loads settings/config.php
// Load env-specific config
$envConfig = Config::load(ROOT_PATH . "settings/{$env}.php");
foreach ($envConfig as $key => $value) {
$config->{$key} = $value;
}Best Practices
✅ DO:
// 1. Use Singleton pattern
$config = Config::create(); // Good
$config2 = Config::create(); // Returns same instance
// 2. Use get() for type conversion
$port = $config->get('email_Port', 25); // Converts to int
$auth = $config->get('email_SMTPAuth', false); // Converts to bool
// 3. Set secure password_key
$config->password_key = bin2hex(random_bytes(32));
// 4. Separate config by environment
Config::load("settings/{$env}.php");
// 5. Save with save() method
Config::save($configArray, $file);❌ DON'T:
// 1. Don't create new instance
$config = new Config(); // Bad - use create() instead
// 2. Don't use default password_key
$config->password_key = '1234567890'; // Dangerous!
// 3. Don't put sensitive data in version control
// Use environment variables instead
$config->email_Password = getenv('SMTP_PASSWORD');
// 4. Don't manually edit config files during runtime
// Use save() method insteadCommon Mistakes
❌ Mistake: Using non-existent methods
// ❌ Wrong - these methods don't exist!
Config::set('key', 'value'); // ❌ No set() method!
Config::all(); // ❌ No all() method!
Config::has('key'); // ❌ No has() method!
// ✅ Correct - use properties directly
$config = Config::create();
$config->web_title = 'New Title'; // Set value
$title = $config->web_title; // Read value❌ Mistake: Wrong type conversion
// ❌ Wrong - doesn't get desired type
$port = $config->get('email_Port'); // returns string or mixed
if ($port === 25) { // May be '25' (string) not 25 (int)
// ...
}
// ✅ Correct - specify default as desired type
$port = $config->get('email_Port', 25); // returns int
if ($port === 25) { // Correct!
// ...
}❌ Mistake: Not checking save result
// ❌ Wrong - doesn't check return value
Config::save($config, $file);
// ✅ Correct - check if save was successful
if (!Config::save($config, $file)) {
throw new \Exception("Failed to save config");
}FAQ (Frequently Asked Questions)
Q: Does Config class have set(), all(), has() methods?
A: No! These methods don't exist in the source code. Use direct property access instead:
$config->web_title = 'New'; // Instead of set()
$title = $config->web_title; // Instead of get()
isset($config->web_title); // Instead of has()Q: Is Config a Singleton?
A: Yes - Using Config::create() always returns the same instance
Q: How does get() method convert types?
A: Converts based on $default type:
get('key', 0)→ intget('key', 0.0)→ floatget('key', false)→ boolget('key', '')→ no conversion
Q: How to separate config by environment?
A: Create separate files (development.php, production.php) and load with load() based on environment variable
Q: Where does framework auto-load config from?
A: Constructor loads from:
ROOT_PATH/settings/config.phpAPP_PATH/settings/config.php(if exists)
Q: What's the best way to change password_key?
A: Use:
$config->password_key = bin2hex(random_bytes(32));Related Classes
- Email - Uses email configuration
- Language - Uses languages configuration
- Session - Session configuration
💡 Tip: Use
get()method when you need automatic type conversion⚠️ Security: Change
password_keyfrom default value before production use!📝 Note: Config is Singleton - calling
create()multiple times returns the same instance