PHP code example of trehinos / thor-pdo-table

1. Go to this page and download the library: Download trehinos/thor-pdo-table library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

trehinos / thor-pdo-table example snippets


use Thor\Database\PdoTable\PdoRow\Row;
use Thor\Database\PdoTable\PdoRow\Attributes\{Table, Column, Index};
use Thor\Database\PdoTable\PdoRow\TableType\{IntegerType, StringType};

#[Table('users', primaryKeys: ['id'], autoColumnName: 'id')]
#[Index(['id'], unique: true)]
abstract class UserRow extends Row
{
    #[Column('id', new IntegerType(), nullable: false)]
    protected ?int $id = null;

    #[Column('username', new StringType(64))]
    protected ?string $username = null;
}

use Thor\Database\PdoExtension\Requester;
use Thor\Database\PdoTable\CrudHelper;

$requester = new Requester($pdo); // from thor-pdo-extension
$crud = new CrudHelper(UserRow::class, $requester);

// Create
$user = new class() extends UserRow {};
$user->fromArray(['username' => 'alice']);
$primary = $crud->createOne($user); // returns primary string; if your row extends AbstractRow with public_id, it returns the public_id

// Read one by primary values (order must match Table primaryKeys)
$loaded = $crud->readOne([1]);

// Update
$loaded->fromArray(['username' => 'alice2']);
$crud->updateOne($loaded);

// Delete
$crud->deleteOne($loaded);

use Thor\Database\PdoTable\Cache\Cache;
use Thor\Database\PdoExtension\Criteria;

$cache = new Cache($crud);
$cache->loadAll();                 // warm up cache
$u = $cache->get('1');             // returns associative array or object (depending on CrudHelper)
$cache->set('1', $u);              // mark as pending
$cache->persistAll();              // flush pending changes to DB

// Or load a filtered list
$cache->loadList(Criteria::eq('active', 1));

use Thor\Database\PdoExtension\Requester;
use Thor\Database\PdoTable\SchemaHelper;
use Thor\Database\PdoTable\Driver\{MySqlDriver, SqliteDriver};

$requester = new Requester($pdo);
$driver = new MySqlDriver(); // or new SqliteDriver()
$schema = new SchemaHelper($requester, $driver, UserRow::class, isDebug: false);

// Create table and indexes
$schema->createTable();

// Drop table and indexes
$schema->dropTable();

// Debug mode (no execution, returns SQL string)
$schemaDebug = new SchemaHelper($requester, $driver, UserRow::class, isDebug: true);
$sql = $schemaDebug->createTable();