Kotchasan Framework Documentation
Country Class - Country Data Management
Country Class - Country Data Management
The Country class is a tool for managing country data in the Kotchasan Framework, supporting country name display in multiple languages.
namespace
Kotchasan\Country;Features
The Country class contains comprehensive country data with names in Thai, English, and local languages, supporting usage in forms and display systems.
Main Methods
get()
Retrieve country name from ISO code
class ExampleClass {
<?php
public static function get($iso): string;
}Parameters:
$iso- ISO country code (e.g., 'TH', 'US', 'JP')
Returns: Country name in current language, or empty string if not found
Usage Examples:
use Kotchasan\Country;
// Get country name in current language
echo Country::get('TH'); // Thailand (if English) or ไทย (if Thai)
echo Country::get('US'); // United States or สหรัฐอเมริกา
echo Country::get('JP'); // Japan or ญี่ปุ่น
// Check for non-existent country
$country = Country::get('XX');
if (empty($country)) {
echo 'Country not found';
}
// User information display system
function displayUserInfo($user) {
return [
'name' => $user['name'],
'email' => $user['email'],
'country' => Country::get($user['country_code']) ?: 'Not specified',
'country_code' => $user['country_code']
];
}
$user = [
'name' => 'John Doe',
'email' => 'john@example.com',
'country_code' => 'US'
];
$userInfo = displayUserInfo($user);
echo "Country: " . $userInfo['country']; // Country: United States;all()
Retrieve all countries list
class ExampleClass {
<?php
public static function all(): array;
}Returns: Array of all countries using ISO code as key and country name as value
Usage Examples:
use Kotchasan\Country;
// Get all countries
$countries = Country::all();
// Display in dropdown
echo '<select name="country">';
echo '<option value="">-- Select Country --</option>';
foreach ($countries as $iso => $name) {
echo "<option value=\"{$iso}\">{$name}</option>";
}
echo '</select>';
// Country search system
function searchCountries($keyword) {
$countries = Country::all();
$results = [];
foreach ($countries as $iso => $name) {
if (stripos($name, $keyword) !== false) {
$results[$iso] = $name;
}
}
return $results;
}
// Usage
$searchResults = searchCountries('Asia');
foreach ($searchResults as $iso => $name) {
echo "{$iso}: {$name}\n";
}
// Registration form system
class RegistrationForm {
public function getCountryOptions($selectedCountry = '') {
$countries = Country::all();
$options = '<option value="">-- Select Country --</option>';
foreach ($countries as $iso => $name) {
$selected = ($iso === $selectedCountry) ? 'selected' : '';
$options .= "<option value=\"{$iso}\" {$selected}>{$name}</option>";
}
return $options;
}
public function renderForm($data = []) {
$countryOptions = $this->getCountryOptions($data['country'] ?? '');
return "
<form method='post'>
<label>Name:</label>
<input type='text' name='name' value='" . ($data['name'] ?? '') . "' required>
<label>Email:</label>
<input type='email' name='email' value='" . ($data['email'] ?? '') . "' required>
<label>Country:</label>
<select name='country' required>
{$countryOptions}
</select>
<button type='submit'>Register</button>
</form>";
}
}
// Usage
$form = new RegistrationForm();
echo $form->renderForm(['country' => 'US']);
// User statistics by country system
class UserStatistics {
private $database;
public function __construct($database) {
$this->database = $database;
}
public function getCountryStats() {
$stats = $this->database->createQuery()
->select('country_code', 'COUNT(*) as user_count')
->from('users')
->where(['country_code', '!=', ''])
->groupBy('country_code')
->orderBy('user_count DESC')
->toArray()
->execute();
$countries = Country::all();
$result = [];
foreach ($stats as $stat) {
$countryName = $countries[$stat['country_code']] ?? $stat['country_code'];
$result[] = [
'country_code' => $stat['country_code'],
'country_name' => $countryName,
'user_count' => $stat['user_count']
];
}
return $result;
}
public function renderStatsChart() {
$stats = $this->getCountryStats();
$html = '<div class="country-stats">';
$html .= '<h3>User Statistics by Country</h3>';
$html .= '<table border="1">';
$html .= '<tr><th>Country</th><th>User Count</th></tr>';
foreach ($stats as $stat) {
$html .= "<tr>";
$html .= "<td>{$stat['country_name']}</td>";
$html .= "<td>{$stat['user_count']}</td>";
$html .= "</tr>";
}
$html .= '</table>';
$html .= '</div>';
return $html;
}
}
// Country data API system
class CountryAPI {
public function getCountry($iso) {
$country = Country::get($iso);
if (empty($country)) {
return [
'success' => false,
'message' => 'Country not found'
];
}
return [
'success' => true,
'data' => [
'iso' => $iso,
'name' => $country
]
];
}
public function getAllCountries($search = '') {
$countries = Country::all();
if (!empty($search)) {
$filtered = [];
foreach ($countries as $iso => $name) {
if (stripos($name, $search) !== false || stripos($iso, $search) !== false) {
$filtered[$iso] = $name;
}
}
$countries = $filtered;
}
return [
'success' => true,
'data' => $countries,
'total' => count($countries)
];
}
public function handleRequest() {
$action = $_GET['action'] ?? '';
switch ($action) {
case 'get':
$iso = $_GET['iso'] ?? '';
header('Content-Type: application/json');
echo json_encode($this->getCountry($iso));
break;
case 'all':
$search = $_GET['search'] ?? '';
header('Content-Type: application/json');
echo json_encode($this->getAllCountries($search));
break;
default:
header('Content-Type: application/json');
echo json_encode([
'success' => false,
'message' => 'Action not supported'
]);
}
}
}
// API Usage
// GET /api/country.php?action=get&iso=US
// GET /api/country.php?action=all&search=Asia
$api = new CountryAPI();
$api->handleRequest();
// Data validation and cleaning system
class CountryValidator {
public static function isValidCountryCode($code) {
return !empty(Country::get($code));
}
public static function validateUserData($data) {
$errors = [];
if (empty($data['name'])) {
$errors['name'] = 'Name is required';
}
if (empty($data['email']) || !filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'Valid email is required';
}
if (empty($data['country']) || !self::isValidCountryCode($data['country'])) {
$errors['country'] = 'Please select a valid country';
}
return [
'valid' => empty($errors),
'errors' => $errors,
'data' => $data
];
}
public static function cleanCountryData($data) {
if (isset($data['country'])) {
$data['country'] = strtoupper(trim($data['country']));
// Remove if not a valid country code
if (!self::isValidCountryCode($data['country'])) {
unset($data['country']);
}
}
return $data;
}
}
// Validator usage
$userData = [
'name' => 'John Doe',
'email' => 'john@example.com',
'country' => 'us' // Will be converted to US
];
$cleanData = CountryValidator::cleanCountryData($userData);
$validation = CountryValidator::validateUserData($cleanData);
if ($validation['valid']) {
echo 'Data is valid';
} else {
foreach ($validation['errors'] as $field => $error) {
echo "{$field}: {$error}\n";
}
}Advanced Usage Examples
use Kotchasan\Database;
use Kotchasan\Country;
// Comprehensive country management system
class CountryManager {
private $cache = [];
public function getCountryInfo($iso) {
if (!isset($this->cache[$iso])) {
$name = Country::get($iso);
if (!empty($name)) {
$this->cache[$iso] = [
'iso' => $iso,
'name' => $name,
'flag_url' => $this->getFlagUrl($iso),
'region' => $this->getRegion($iso)
];
} else {
$this->cache[$iso] = null;
}
}
return $this->cache[$iso];
}
private function getFlagUrl($iso) {
return "/assets/flags/" . strtolower($iso) . ".png";
}
private function getRegion($iso) {
$regions = [
'TH' => 'Southeast Asia',
'JP' => 'East Asia',
'KR' => 'East Asia',
'CN' => 'East Asia',
'US' => 'North America',
'GB' => 'Europe',
'DE' => 'Europe',
'FR' => 'Europe'
];
return $regions[$iso] ?? 'Unknown';
}
public function getCountriesByRegion($region) {
$countries = Country::all();
$result = [];
foreach ($countries as $iso => $name) {
$info = $this->getCountryInfo($iso);
if ($info && $info['region'] === $region) {
$result[$iso] = $info;
}
}
return $result;
}
public function renderCountrySelector($selectedCountry = '', $options = []) {
$countries = Country::all();
$showFlags = $options['show_flags'] ?? false;
$groupByRegion = $options['group_by_region'] ?? false;
$html = '<select name="country" class="country-selector">';
$html .= '<option value="">-- Select Country --</option>';
if ($groupByRegion) {
$regions = [];
foreach ($countries as $iso => $name) {
$info = $this->getCountryInfo($iso);
if ($info) {
$regions[$info['region']][$iso] = $info;
}
}
foreach ($regions as $regionName => $regionCountries) {
$html .= "<optgroup label=\"{$regionName}\">";
foreach ($regionCountries as $iso => $info) {
$selected = ($iso === $selectedCountry) ? 'selected' : '';
$flag = $showFlags ? "🏳️ " : "";
$html .= "<option value=\"{$iso}\" {$selected}>{$flag}{$info['name']}</option>";
}
$html .= "</optgroup>";
}
} else {
foreach ($countries as $iso => $name) {
$selected = ($iso === $selectedCountry) ? 'selected' : '';
$flag = $showFlags ? "🏳️ " : "";
$html .= "<option value=\"{$iso}\" {$selected}>{$flag}{$name}</option>";
}
}
$html .= '</select>';
return $html;
}
}
// International user system
class InternationalUserSystem {
private $countryManager;
private $database;
public function __construct($database) {
$this->countryManager = new CountryManager();
$this->database = $database;
}
public function createUser($userData) {
// Validate country data
$countryInfo = $this->countryManager->getCountryInfo($userData['country']);
if (!$countryInfo) {
throw new \InvalidArgumentException('Invalid country code');
}
// Add full country information
$userData['country_name'] = $countryInfo['name'];
$userData['region'] = $countryInfo['region'];
$userData['created_at'] = date('Y-m-d H:i:s');
// Save to database
return $this->database->createQuery()
->insert('users')
->values($userData)
->execute();
}
public function getUsersByCountry($countryCode) {
return $this->database->createQuery()
->select()
->from('users')
->where(['country', $countryCode])
->orderBy('created_at DESC')
->toArray()
->execute();
}
public function getRegionalStatistics() {
$stats = $this->database->createQuery()
->select('region', 'COUNT() as user_count')
->from('users')
->where(['region', '!=', ''])
->groupBy('region')
->orderBy('user_count DESC')
->toArray()
->execute();
return $stats;
}
public function generateCountryReport() {
$countries = Country::all();
$report = [];
foreach ($countries as $iso => $name) {
$userCount = $this->database->createQuery()
->select('COUNT(*) as count')
->from('users')
->where(['country', $iso])
->first();
$countryInfo = $this->countryManager->getCountryInfo($iso);
$report[] = [
'iso' => $iso,
'name' => $name,
'user_count' => $userCount ? $userCount->count : 0,
'region' => $countryInfo ? $countryInfo['region'] : 'Unknown'
];
}
// Sort by user count
usort($report, function($a, $b) {
return $b['user_count'] - $a['user_count'];
});
return $report;
}
}
// System usage
$database = \Kotchasan\Database::create();
$userSystem = new InternationalUserSystem($database);
// Create new user
try {
$newUser = [
'name' => 'Jane Smith',
'email' => 'jane@example.com',
'country' => 'GB'
];
$userId = $userSystem->createUser($newUser);
echo "User created successfully ID: {$userId}";
} catch (Exception $e) {
echo "Error occurred: " . $e->getMessage();
}
// View regional statistics
$regionalStats = $userSystem->getRegionalStatistics();
foreach ($regionalStats as $stat) {
echo "{$stat['region']}: {$stat['user_count']} users\n";
}
// Generate country report
$countryReport = $userSystem->generateCountryReport();
foreach (array_slice($countryReport, 0, 10) as $country) {
echo "{$country['name']}: {$country['user_count']} users\n";
}Usage Notes
- Language Support: Displays country names according to current system language
- Comprehensive Data: Contains worldwide country data with local language names
- Usage: Suitable for forms and systems requiring country selection
- Performance: Data stored as static array for fast access
- Standards: Uses ISO 3166-1 alpha-2 country codes
The Country class is an efficient tool for managing country data in the Kotchasan Framework, perfect for systems supporting international users.