Kotchasan Framework Documentation
Collection Class - คอลเลกชันข้อมูลขั้นสูง
Collection Class - คอลเลกชันข้อมูลขั้นสูง
คลาส Collection เป็นคลาสสำหรับจัดการคอลเลกชันของข้อมูลแบบ key-value ใน Kotchasan Framework ที่รองรับ interfaces มาตรฐานของ PHP ทำให้สามารถใช้งานได้เหมือน array แต่ในรูปแบบ object-oriented
Namespace
Kotchasan\Collectionคุณสมบัติ
- ArrayAccess - เข้าถึงข้อมูลเหมือน array (
$collection['key']) - Countable - นับจำนวนสมาชิกด้วย
count() - IteratorAggregate - วนลูปด้วย
foreachได้ - Type-safe - จัดการข้อมูลแบบ key-value อย่างปลอดภัย
Implemented Interfaces
class Collection implements \Countable, \IteratorAggregate, \ArrayAccessAPI Reference
__construct()
สร้าง Collection ใหม่พร้อมข้อมูลเริ่มต้น
public function __construct(array $items = []): voidParameters:
$items(array) - อาร์เรย์ข้อมูลเริ่มต้น (optional)
Example:
use Kotchasan\Collection;
// สร้าง Collection ว่าง
$collection = new Collection();
// สร้างพร้อมข้อมูล
$user = new Collection([
'name' => 'John Doe',
'email' => 'john@example.com',
'age' => 30
]);set()
กำหนดค่าให้กับ key
public function set($key, $value): voidParameters:
$key(mixed) - key ที่ต้องการกำหนด$value(mixed) - ค่าที่ต้องการเก็บ
Example:
$collection = new Collection();
$collection->set('username', 'johndoe');
$collection->set('email', 'john@example.com');
$collection->set('settings', ['theme' => 'dark', 'lang' => 'th']);get()
ดึงค่าจาก key พร้อมค่า default ถ้าไม่พบ
public function get($key, $default = null): mixedParameters:
$key(mixed) - key ที่ต้องการดึง$default(mixed) - ค่า default ถ้าไม่พบ key (optional)
Returns: ค่าที่เก็บไว้ หรือ $default ถ้าไม่พบ
Example:
$config = new Collection(['debug' => true, 'timeout' => 30]);
// ดึงค่าที่มีอยู่
$debug = $config->get('debug'); // true
// ดึงค่าที่ไม่มี พร้อม default
$cache = $config->get('cache', false); // false
// ดึงค่าที่ไม่มี ไม่ระบุ default
$missing = $config->get('notfound'); // nullhas()
ตรวจสอบว่ามี key อยู่หรือไม่
public function has($key): boolParameters:
$key(mixed) - key ที่ต้องการตรวจสอบ
Returns: true ถ้ามี key, false ถ้าไม่มี
Example:
$data = new Collection(['name' => 'Alice', 'age' => null]);
var_dump($data->has('name')); // true
var_dump($data->has('age')); // true (มี key แม้ค่าเป็น null)
var_dump($data->has('email')); // falseremove()
ลบ key ออกจาก Collection
public function remove($key): voidParameters:
$key(mixed) - key ที่ต้องการลบ
Example:
$session = new Collection([
'user_id' => 123,
'token' => 'abc123',
'temp_data' => 'xyz'
]);
$session->remove('temp_data');
var_dump($session->has('temp_data')); // falsereplace()
แทนที่หรือเพิ่มข้อมูลหลาย key พร้อมกัน
public function replace(array $items): voidParameters:
$items(array) - อาร์เรย์ของ key-value ที่ต้องการแทนที่/เพิ่ม
Example:
$config = new Collection(['host' => 'localhost', 'port' => 3306]);
// แทนที่และเพิ่มข้อมูล
$config->replace([
'port' => 3307, // แทนที่
'database' => 'mydb', // เพิ่มใหม่
'charset' => 'utf8mb4' // เพิ่มใหม่
]);
// ผลลัพธ์: ['host' => 'localhost', 'port' => 3307, 'database' => 'mydb', 'charset' => 'utf8mb4']clear()
ลบข้อมูลทั้งหมดออกจาก Collection
public function clear(): voidExample:
$cache = new Collection(['key1' => 'value1', 'key2' => 'value2']);
echo count($cache); // 2
$cache->clear();
echo count($cache); // 0keys()
ดึงรายการ keys ทั้งหมด
public function keys(): arrayReturns: อาร์เรย์ของ keys ทั้งหมด
Example:
$data = new Collection([
'name' => 'John',
'email' => 'john@example.com',
'age' => 30
]);
$keys = $data->keys(); // ['name', 'email', 'age']toArray()
แปลง Collection เป็น array
public function toArray(): arrayReturns: อาร์เรย์ของข้อมูลทั้งหมด
Example:
$collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3]);
$array = $collection->toArray(); // ['a' => 1, 'b' => 2, 'c' => 3]
print_r($array);count()
นับจำนวนสมาชิก (Countable interface)
public function count(): intReturns: จำนวนสมาชิกใน Collection
Example:
$items = new Collection(['apple', 'banana', 'orange']);
echo count($items); // 3
echo $items->count(); // 3 (เหมือนกัน)getIterator()
ดึง Iterator สำหรับวนลูป (IteratorAggregate interface)
public function getIterator(): \ArrayIteratorReturns: ArrayIterator object
Example:
$collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3]);
// ใช้ foreach (เรียก getIterator() อัตโนมัติ)
foreach ($collection as $key => $value) {
echo "$key => $value\n";
}
// หรือเรียกโดยตรง
$iterator = $collection->getIterator();
while ($iterator->valid()) {
echo $iterator->key() . ' => ' . $iterator->current() . "\n";
$iterator->next();
}ArrayAccess Interface Methods
Collection รองรับการเข้าถึงแบบ array:
// offsetExists - isset($collection['key'])
public function offsetExists($key): bool
// offsetGet - $collection['key']
public function offsetGet($key): mixed
// offsetSet - $collection['key'] = $value
public function offsetSet($key, $value): void
// offsetUnset - unset($collection['key'])
public function offsetUnset($key): voidExample:
$user = new Collection();
// เพิ่มข้อมูล
$user['name'] = 'Alice';
$user['email'] = 'alice@example.com';
// อ่านข้อมูล
echo $user['name']; // "Alice"
// ตรวจสอบ
if (isset($user['email'])) {
echo "มีอีเมล";
}
// ลบ
unset($user['email']);ตัวอย่างการใช้งานจริง
1. Configuration Management
use Kotchasan\Collection;
class AppConfig
{
private $config;
public function __construct()
{
$this->config = new Collection([
'app_name' => 'My App',
'version' => '1.0.0',
'debug' => false,
'database' => [
'host' => 'localhost',
'port' => 3306
]
]);
}
public function get($key, $default = null)
{
return $this->config->get($key, $default);
}
public function set($key, $value)
{
$this->config->set($key, $value);
}
public function merge(array $config)
{
$this->config->replace($config);
}
public function all()
{
return $this->config->toArray();
}
}
// การใช้งาน
$config = new AppConfig();
echo $config->get('app_name'); // "My App"
$config->set('debug', true);
$config->merge(['timezone' => 'Asia/Bangkok']);2. API Response Builder
use Kotchasan\Collection;
class ApiResponse
{
private $data;
private $meta;
public function __construct()
{
$this->data = new Collection();
$this->meta = new Collection([
'status' => 'success',
'timestamp' => time()
]);
}
public function setData($key, $value)
{
$this->data[$key] = $value;
return $this;
}
public function setMeta($key, $value)
{
$this->meta[$key] = $value;
return $this;
}
public function setError($message, $code = 400)
{
$this->meta['status'] = 'error';
$this->meta['error'] = [
'message' => $message,
'code' => $code
];
return $this;
}
public function toJson()
{
return json_encode([
'data' => $this->data->toArray(),
'meta' => $this->meta->toArray()
], JSON_UNESCAPED_UNICODE);
}
}
// การใช้งาน
$response = new ApiResponse();
$response->setData('users', [
['id' => 1, 'name' => 'Alice'],
['id' => 2, 'name' => 'Bob']
])
->setMeta('total', 2)
->setMeta('page', 1);
echo $response->toJson();3. Session Manager
use Kotchasan\Collection;
class SessionManager
{
private $session;
public function __construct()
{
$this->session = new Collection($_SESSION ?? []);
}
public function set($key, $value)
{
$this->session->set($key, $value);
$_SESSION[$key] = $value;
}
public function get($key, $default = null)
{
return $this->session->get($key, $default);
}
public function has($key)
{
return $this->session->has($key);
}
public function remove($key)
{
$this->session->remove($key);
unset($_SESSION[$key]);
}
public function flash($key, $value)
{
$this->set($key, $value);
$this->set("_flash_{$key}", true);
}
public function getFlash($key)
{
$value = $this->get($key);
if ($this->has("_flash_{$key}")) {
$this->remove($key);
$this->remove("_flash_{$key}");
}
return $value;
}
public function destroy()
{
$this->session->clear();
$_SESSION = [];
session_destroy();
}
}
// การใช้งาน
$session = new SessionManager();
$session->set('user_id', 123);
$session->flash('success_message', 'บันทึกสำเร็จ');
// หน้าถัดไป
echo $session->getFlash('success_message'); // "บันทึกสำเร็จ"
echo $session->getFlash('success_message'); // null (ถูกลบแล้ว)4. Form Data Validator
use Kotchasan\Collection;
class FormValidator
{
private $data;
private $errors;
private $rules;
public function __construct(array $data)
{
$this->data = new Collection($data);
$this->errors = new Collection();
$this->rules = new Collection();
}
public function rule($field, $ruleName, $errorMessage)
{
if (!$this->rules->has($field)) {
$this->rules->set($field, []);
}
$fieldRules = $this->rules->get($field);
$fieldRules[$ruleName] = $errorMessage;
$this->rules->set($field, $fieldRules);
return $this;
}
public function validate()
{
$this->errors->clear();
foreach ($this->rules as $field => $fieldRules) {
$value = $this->data->get($field);
foreach ($fieldRules as $rule => $message) {
if (!$this->checkRule($value, $rule)) {
if (!$this->errors->has($field)) {
$this->errors->set($field, []);
}
$errors = $this->errors->get($field);
$errors[] = $message;
$this->errors->set($field, $errors);
}
}
}
return count($this->errors) === 0;
}
private function checkRule($value, $rule)
{
switch ($rule) {
case 'required':
return !empty($value);
case 'email':
return filter_var($value, FILTER_VALIDATE_EMAIL) !== false;
case 'numeric':
return is_numeric($value);
default:
return true;
}
}
public function errors()
{
return $this->errors->toArray();
}
public function getData()
{
return $this->data->toArray();
}
}
// การใช้งาน
$validator = new FormValidator($_POST);
$validator->rule('email', 'required', 'กรุณาระบุอีเมล')
->rule('email', 'email', 'รูปแบบอีเมลไม่ถูกต้อง')
->rule('age', 'numeric', 'อายุต้องเป็นตัวเลข');
if ($validator->validate()) {
// ข้อมูลถูกต้อง
$data = $validator->getData();
} else {
// มีข้อผิดพลาด
print_r($validator->errors());
}Best Practices
1. ใช้ Type Checking
use Kotchasan\Collection;
// ตรวจสอบประเภทข้อมูลก่อนเก็บ
class TypedCollection extends Collection
{
private $type;
public function __construct($type, array $items = [])
{
$this->type = $type;
parent::__construct($items);
}
public function set($key, $value): void
{
if (!($value instanceof $this->type)) {
throw new \InvalidArgumentException(
"Value must be instance of {$this->type}"
);
}
parent::set($key, $value);
}
}
// การใช้งาน
$users = new TypedCollection(User::class);
$users->set('user1', new User('Alice'));
// $users->set('user2', 'invalid'); // จะ throw Exception2. ใช้กับ Dependency Injection
class UserService
{
private $config;
public function __construct(Collection $config)
{
$this->config = $config;
}
public function createUser($data)
{
$host = $this->config->get('db.host', 'localhost');
$port = $this->config->get('db.port', 3306);
// ...
}
}
// Injection
$config = new Collection(['db' => ['host' => '127.0.0.1', 'port' => 3307]]);
$service = new UserService($config);3. Method Chaining
$response = new Collection();
$response->set('status', 200)
->set('message', 'Success')
->set('data', ['id' => 1, 'name' => 'Test']);
// แต่ต้องแก้ไข set() ให้ return $thisImportant Considerations
[!WARNING]
Key Overwriting: การใช้set()หรือreplace()จะเขียนทับค่าเดิมโดยไม่เตือน
$collection = new Collection(['name' => 'Alice']);
$collection->set('name', 'Bob'); // เขียนทับไม่มีเตือน[!NOTE]
Null Values:has()ใช้array_key_exists()ดังนั้นจะ returntrueแม้ค่าเป็นnull
$collection = new Collection(['key' => null]);
$collection->has('key'); // true
$collection->get('key'); // null[!TIP]
Performance: Collection เหมาะสำหรับจัดการข้อมูลขนาดเล็กถึงกลาง ถ้ามีข้อมูลขนาดใหญ่มากให้ใช้ array ธรรมดา
Related Classes
สรุป
คลาส Collection เป็นเครื่องมือที่ทรงพลังสำหรับจัดการข้อมูลแบบ key-value โดยรองรับ PHP interfaces มาตรฐาน (Countable, IteratorAggregate, ArrayAccess) ทำให้ใช้งานได้เหมือน array แต่มีความยืดหยุ่นและฟีเจอร์เพิ่มเติมในรูปแบบ object-oriented เหมาะสำหรับ:
- การจัดการ configuration
- การสร้าง API responses
- การจัดการ session data
- การ validate form data
- การสร้าง data collections ที่ต้องการ type safety