Kotchasan Framework Documentation

Kotchasan Framework Documentation

ListItem Class - List Data Management

EN 03 Feb 2026 15:54

ListItem Class - List Data Management

The ListItem class is for managing list (array) data with the ability to save and load data from files.

Namespace

Kotchasan\ListItem

Overview

The ListItem class provides:

  • Manage data as associative array
  • Add/delete/modify items
  • Insert items before/after desired positions
  • Search for item by value (indexOf)
  • Load/save data from PHP files

Public Properties

public $datas;  // array - all data

Public Methods (18 methods)

init()

Initialize class with data

public function init(array $config): void

Example:

$list = new ListItem();
$list->init(['a' => 1, 'b' => 2, 'c' => 3]);

assign()

Add multiple items (merge)

public function assign(array $array): void

Example:

$list->assign(['d' => 4, 'e' => 5]);

set()

Set value at key

public function set(string $key, mixed $value): void

Example:

$list->set('name', 'John');
$list->set('age', 30);

get()

Get value from key

public function get(string $key): mixed

Example:

$name = $list->get('name');  // 'John'
$unknown = $list->get('notfound');  // null

delete()

Delete item

public function delete(string $key): bool

Returns: true if deleted successfully, false if not found

Example:

$list->delete('age');  // true
$list->delete('notfound');  // false

clear()

Clear all data

public function clear(): void

Example:

$list->clear();

count()

Count items

public function count(): int

Example:

echo $list->count();  // 3

items()

Get all as array

public function items(): array

Example:

$all = $list->items();
// ['name' => 'John', 'age' => 30]

keys()

Get array of keys

public function keys(): array

Example:

$keys = $list->keys();
// ['name', 'age']

values()

Get array of values

public function values(): array

Example:

$values = $list->values();
// ['John', 30]

firstItem()

Get first item

public function firstItem(): mixed

Example:

$first = $list->firstItem();

lastItem()

Get last item

public function lastItem(): mixed

Example:

$last = $list->lastItem();

indexOf()

Search for key by value

public function indexOf(mixed $value): mixed

Returns: key if found, or false

Example:

$list->init(['a' => 'apple', 'b' => 'banana']);
$key = $list->indexOf('banana');  // 'b'
$notfound = $list->indexOf('orange');  // false

insert()

Insert item after specified key

public function insert(mixed $key, mixed $item): void

Example:

$list->init(['a' => 1, 'c' => 3]);
$list->insert('a', ['b' => 2]);
// Result: ['a' => 1, 'b' => 2, 'c' => 3]

insertBefore()

Insert item before specified key

public function insertBefore(mixed $key, mixed $item): void

Example:

$list->init(['a' => 1, 'c' => 3]);
$list->insertBefore('c', ['b' => 2]);
// Result: ['a' => 1, 'b' => 2, 'c' => 3]

loadFromFile()

Load data from PHP file

public function loadFromFile(string $file): static

Example:

$list = new ListItem();
$list->loadFromFile('config/settings.php');

saveToFile()

Save data to file

public function saveToFile(): bool

Returns: true if saved successfully

Example:

$list->loadFromFile('config/settings.php');
$list->set('version', '2.0');
$list->saveToFile();

Complete Usage Examples

1. Configuration Management

use Kotchasan\ListItem;

// Load config
$config = new ListItem();
$config->loadFromFile('config/app.php');

// Read values
$appName = $config->get('app_name');
$version = $config->get('version');

// Modify values
$config->set('debug_mode', true);
$config->set('version', '2.0.1');

// Save
$config->saveToFile();

2. Dynamic Menu Management

use Kotchasan\ListItem;

// Create menu
$menu = new ListItem();
$menu->init([
    'home' => ['text' => 'Home', 'url' => '/'],
    'about' => ['text' => 'About', 'url' => '/about'],
    'contact' => ['text' => 'Contact', 'url' => '/contact']
]);

// Insert new menu after 'about'
$menu->insert('about', [
    'products' => ['text' => 'Products', 'url' => '/products']
]);

// Insert menu before 'contact'
$menu->insertBefore('contact', [
    'blog' => ['text' => 'Blog', 'url' => '/blog']
]);

// Delete menu
if ($menu->get('old_page')) {
    $menu->delete('old_page');
}

// Display menu
foreach ($menu->items() as $key => $item) {
    echo "<a href='{$item['url']}'>{$item['text']}</a>";
}

3. Settings Manager

use Kotchasan\ListItem;

class SettingsManager
{
    private $settings;

    public function __construct($file)
    {
        $this->settings = new ListItem();
        $this->settings->loadFromFile($file);
    }

    public function get($key, $default = null)
    {
        $value = $this->settings->get($key);
        return $value !== null ? $value : $default;
    }

    public function set($key, $value)
    {
        $this->settings->set($key, $value);
        return $this;
    }

    public function has($key)
    {
        return $this->settings->get($key) !== null;
    }

    public function remove($key)
    {
        return $this->settings->delete($key);
    }

    public function all()
    {
        return $this->settings->items();
    }

    public function save()
    {
        return $this->settings->saveToFile();
    }

    public function reset()
    {
        $this->settings->clear();
        return $this;
    }
}

// Usage
$config = new SettingsManager('config/app.php');

// Read values
$timezone = $config->get('timezone', 'Asia/Bangkok');
$debug = $config->get('debug', false);

// Set values
$config->set('app_name', 'My App')
       ->set('version', '1.0.0')
       ->save();

// Delete
if ($config->has('old_setting')) {
    $config->remove('old_setting')->save();
}

4. Data Cache with File

use Kotchasan\ListItem;

class CacheManager
{
    private $cache;

    public function __construct()
    {
        $this->cache = new ListItem();
        $this->cache->loadFromFile('cache/data.php');
    }

    public function get($key)
    {
        $data = $this->cache->get($key);

        if ($data && isset($data['expires'])) {
            if (time() > $data['expires']) {
                // Expired
                $this->cache->delete($key);
                return null;
            }
            return $data['value'];
        }

        return $data;
    }

    public function set($key, $value, $ttl = 3600)
    {
        $this->cache->set($key, [
            'value' => $value,
            'expires' => time() + $ttl
        ]);

        return $this->cache->saveToFile();
    }

    public function delete($key)
    {
        $this->cache->delete($key);
        return $this->cache->saveToFile();
    }

    public function clear()
    {
        $this->cache->clear();
        return $this->cache->saveToFile();
    }

    public function cleanup()
    {
        $now = time();
        $items = $this->cache->items();

        foreach ($items as $key => $data) {
            if (isset($data['expires']) && $now > $data['expires']) {
                $this->cache->delete($key);
            }
        }

        return $this->cache->saveToFile();
    }
}

// Usage
$cache = new CacheManager();

// Store
$cache->set('user_123', ['name' => 'John', 'email' => 'john@example.com'], 3600);

// Retrieve
$user = $cache->get('user_123');

// Cleanup expired cache
$cache->cleanup();

5. Translation Management

use Kotchasan\ListItem;

class Translator
{
    private $translations;
    private $locale;

    public function __construct($locale = 'th')
    {
        $this->locale = $locale;
        $this->translations = new ListItem();
        $this->translations->loadFromFile("lang/{$locale}.php");
    }

    public function trans($key, $params = [])
    {
        $text = $this->translations->get($key);

        if ($text === null) {
            return $key;
        }

        foreach ($params as $placeholder => $value) {
            $text = str_replace($placeholder, $value, $text);
        }

        return $text;
    }

    public function add($key, $value)
    {
        $this->translations->set($key, $value);
        return $this;
    }

    public function save()
    {
        return $this->translations->saveToFile();
    }

    public function switchLocale($locale)
    {
        $this->locale = $locale;
        $this->translations->clear();
        $this->translations->loadFromFile("lang/{$locale}.php");
    }
}

// Usage
$t = new Translator('en');

echo $t->trans('welcome');  // "Welcome"
echo $t->trans('hello_user', [':name' => 'John']);  // "Hello John"

// Add new translation
$t->add('goodbye', 'Goodbye')->save();

// Switch language
$t->switchLocale('en');
echo $t->trans('welcome');  // "Welcome"

Best Practices

1. File Management

// ✅ Good: Use loadFromFile before modifying
$config = new ListItem();
$config->loadFromFile('config/app.php');
$config->set('version', '2.0');
$config->saveToFile();

// ❌ Bad: saveToFile without loadFromFile first
$config = new ListItem();
$config->set('version', '2.0');
$config->saveToFile();  // Returns false - no source file

2. Key Management

// ✅ Good: Check before use
$value = $list->get('key');
if ($value !== null) {
    // Use $value
}

// ✅ Good: Use default value
$value = $list->get('key') ?? 'default';

// ✅ Good: Check before delete
if ($list->get('old_key') !== null) {
    $list->delete('old_key');
}

3. Performance

// ✅ Good: Save once after multiple modifications
$config->set('key1', 'value1');
$config->set('key2', 'value2');
$config->set('key3', 'value3');
$config->saveToFile();  // Save once

// ❌ Bad: Save every time
$config->set('key1', 'value1');
$config->saveToFile();
$config->set('key2', 'value2');
$config->saveToFile();  // Slow!

Summary

The ListItem class is a list data management class that:

  • ✅ Manage key-value data
  • ✅ Flexible insert/delete items
  • ✅ Load/save PHP files
  • ✅ Search data
  • 📝 Suitable for config files
  • 🔄 Chainable methods

Suitable for:

  • Configuration management
  • Dynamic menus
  • Settings storage
  • Data caching
  • Translation files

File Size: 279 lines
Public Methods: 18 methods
Storage: PHP array files