PHP code example of amtgard / active-record-orm

1. Go to this page and download the library: Download amtgard/active-record-orm 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/ */

    

amtgard / active-record-orm example snippets


use Amtgard\ActiveRecordOrm\Configuration\DataAccessPolicy\UncachedDataAccessPolicy;use Amtgard\ActiveRecordOrm\Configuration\Repository\DatabaseConfiguration;use Amtgard\ActiveRecordOrm\Configuration\Repository\MysqlPdoProvider;use Amtgard\ActiveRecordOrm\Factory\TableFactory;use Amtgard\ActiveRecordOrm\Repository\Database;use Dotenv\Dotenv;

// Configure database connection from local .env file
$dotenvPath = __DIR__;
$dotenv = Dotenv::createImmutable($dotenvPath);
$dotenv->safeLoad();
$config = DatabaseConfiguration::fromEnvironment();
$provider = MysqlPdoProvider::fromConfiguration($config);
$db = Database::fromProvider($provider);

// Set up data access policy
$tablePolicy = UncachedDataAccessPolicy::builder()->database($db)->build();

// Create a table instance
$itemTable = TableFactory::build($db, $tablePolicy, 'items');

// Find by ID
// Clearing is good practice
$itemTable->clear();
$itemTable->id = 1;
$itemTable->find();
$itemTable->next();
echo $itemTable->string_value; // Access field values

// Find all records
$itemTable->clear();
if ($itemTable->find()) {
    while ($itemTable->next()) {
        echo $itemTable->id . ": " . $itemTable->string_value . "\n";
    }
}

// Find with conditions, a list of conditions is at the end of the README
$itemTable->clear();
// gt is "greaterThan" - greaterThan() may also be used; see list of operators at the end of this document
$itemTable->gt('int_value', 3);
if ($itemTable->find()) {
    while ($itemTable->next()) {
        echo $itemTable->int_value . "\n";
    }
}

// LIKE queries
$itemTable->clear();
$itemTable->like('string_value', '%bunny%');
$itemTable->find();

// IN queries
$itemTable->clear();
$itemTable->in('int_value', [3, 5]);
$itemTable->find();

// NOT LIKE queries
$itemTable->clear();
$itemTable->notLike('string_value', 'bunny rabbit foo-foo');
$itemTable->find();

// Ordering
$itemTable->clear();
$itemTable->orderBy('id', OrderBy::DESC);
$itemTable->gt('id', 1);
$itemTable->find();

$itemTable->clear();
$itemTable->string_value = "New Item";
$itemTable->int_value = 42;
$itemTable->save();
echo "New ID: " . $itemTable->id;

// Find the record first
$itemTable->clear();
$itemTable->id = 1;
$itemTable->find();
$itemTable->next();

// Update fields
$itemTable->string_value = "Updated Value";
$itemTable->int_value = 77;
$itemTable->save();

// Delete by ID
$itemTable->clear();
$itemTable->id = 1;
$itemTable->delete();

// Delete with conditions
$itemTable->clear();
// alternatively $itemTable->startsWith('string_value', 'bunny');
$itemTable->like('string_value', 'bunny%');
$itemTable->delete();

// Delete all records
$itemTable->clear();
$itemTable->delete();

// Pagination
$itemTable->clear();
$itemTable->page(2, 1); // 2 records per page, page 1
$itemTable->find();

// Limits
$itemTable->clear();
$itemTable->limit(10); // Limit to 10 records
$itemTable->find();

// Limit with offset
$itemTable->clear();
$itemTable->limit(5, 10); // Offset 5, limit 10
$itemTable->find();

$itemTable->clear();
$count = $itemTable->count();
echo "Total records: " . $itemTable->row_count;

$db->clear();
$db->execute("delete from integ where string_value like 'insert_item_test_%'");
$db->clear();

$db->clear();
$db->execute("truncate table integ");
$db->clear();
$db->string_value = "2";
$db->int_value = 3;
$db->execute("insert into integ (string_value, int_value) values (:string_value, :int_value)");
$db->clear();
$records = $db->execute("select * from integ");
$records->next();

echo $records->size());
// value "2"
echo $records->string_value;

$db->clear();
$records = $db->execute("select a.one, a.two, b.one as three, c.two as four from a left join b on a.id = b.fk");
echo $records->one . " => " $records.four;

use Amtgard\ActiveRecordOrm\EntityManager;
use Amtgard\ActiveRecordOrm\Entity\Policy\UncachedPolicy;
use Amtgard\ActiveRecordOrm\Entity\EntityMapper;

// Configure EntityManager
$entityManager = EntityManager::builder()
    ->database($db)
    ->dataAccessPolicy($tablePolicy)
    ->repositoryPolicy(UncachedPolicy::builder()->build())
    ->build();

// Configure as singleton
EntityManager::configure($entityManager);

// Create an EntityOf
$entityMapper = EntityMapper::builder()
    ->table($itemTable)
    ->build();

// Find and get entity
$entityMapper->clear();
$entityMapper->id = 1;
$entityMapper->find();
$entityMapper->next();

$entity = $entityMapper->getEntity();
echo $entity->string_value; // Access entity properties
echo $entity->int_value;

// Modify entity
$entity->string_value = "Modified Value";
$entity->int_value = 99;

// $entity id 1 is automatically persisted on shutdown

// Execute custom SQL
$entityMapper->clear();
$entityMapper->query("SELECT * FROM integ WHERE id = :id");
$entityMapper->id = 1;
$entityMapper->execute();
$entityMapper->next();

$entity = $entityMapper->getEntity();
echo $entity->string_value;

// Get entity by ID from EntityManager
$entity = EntityManager::getManager()->getEntity('table_name', 1);

$entity->string_value = "new value";

// Persist a specific entity
EntityManager::getManager()->persist($entity);

// Persist all entities across all mappers
EntityManager::getManager()->persistAll();

// Persist all entities for a specific mapper
EntityManager::getManager()->persistMapper('table_name');

// Persist with no arguments (same as persistAll)
EntityManager::getManager()->persist();

use Amtgard\ActiveRecordOrm\Attribute\RepositoryOf;
use Amtgard\ActiveRecordOrm\Entity\Repository\Repository;
use Amtgard\ActiveRecordOrm\Interface\EntityRepositoryInterface;

#[RepositoryOf("items", ItemEntity::class)]
class ItemRepository extends Repository implements EntityRepositoryInterface
{
    public static function getTableName()
    {
        return 'items';
    }

    public static function getEntityClass()
    {
        return ItemEntity::class;
    }
}

use Amtgard\ActiveRecordOrm\Attribute\EntityOf;
use Amtgard\ActiveRecordOrm\Attribute\Field;
use Amtgard\ActiveRecordOrm\Attribute\PrimaryKey;
use Amtgard\ActiveRecordOrm\Entity\Repository\RepositoryEntity;
use Amtgard\Traits\Builder\Builder;
use Amtgard\Traits\Builder\Data;
use Amtgard\Traits\Builder\ToBuilder;

#[EntityOf(ItemRepository::class)]
class ItemEntity extends RepositoryEntity
{
    use Builder, ToBuilder, Data;

    #[PrimaryKey]
    private ?int $id;

    #[Field('string_value')]
    private ?string $name;

    #[Field('int_value')]
    private ?int $quantity;
}

// Get repository from EntityManager
$itemRepository = EntityManager::getManager()->getRepository(ItemRepository::class);

// Fetch an entity by ID
$item = $itemRepository->fetch(1);
echo $item->getName();

// Create a new entity
$newItem = $itemRepository->createEntity();
$newItem->setName("New Item");
$newItem->setQuantity(10);

// Persist the entity
EntityManager::getManager()->persist($newItem);

// Or use the builder pattern
$item = ItemEntity::builder()
    ->name("Another Item")
    ->quantity(5)
    ->build();

EntityManager::getManager()->persist($item);

// Fetch with conditions
$item = $itemRepository->fetchBy('name', 'Specific Item');

// Update entity
$item->setName("Updated Name");
EntityManager::getManager()->persist($item);

use Amtgard\ActiveRecordOrm\Attribute\EntityOf;
use Amtgard\ActiveRecordOrm\Attribute\Field;
use Amtgard\ActiveRecordOrm\Attribute\PrimaryKey;
use Amtgard\ActiveRecordOrm\Entity\Repository\RepositoryEntity;
use Amtgard\ActiveRecordOrm\Feature\Entity\Repository\AuditRepositoryEntityTrait;
use Amtgard\Traits\Builder\Builder;
use Amtgard\Traits\Builder\Data;
use Amtgard\Traits\Builder\ToBuilder;

#[EntityOf(ItemRepository::class)]
class ItemEntity extends RepositoryEntity
{
    use Builder, ToBuilder, Data, AuditRepositoryEntityTrait;

    #[PrimaryKey]
    private ?int $id;

    #[Field('string_value')]
    private ?string $name;

    #[Field('int_value')]
    private ?int $quantity;
}

// Create an entity with audit logging
$item = ItemEntity::builder()
    ->name("New Item")
    ->quantity(10)
    ->build();

// Persist the entity - this automatically creates an audit log entry
EntityManager::getManager()->persist($item);

// The audit log table 'items_audit_log' now contains:
// - record_id: 1 (the new item's ID)
// - action: "insert"
// - fields: ["name", "quantity"]
// - log_datetime: [current timestamp]

// Update the entity
$item->setQuantity(20);
EntityManager::getManager()->persist($item);

// The audit log now has a second entry:
// - record_id: 1
// - action: "update"
// - fields: ["quantity"]
// - log_datetime: [timestamp of update]

// Delete the entity
EntityManager::getManager()->delete($item);

// The audit log now has a third entry:
// - record_id: 1
// - action: "delete"
// - fields: []
// - log_datetime: [timestamp of deletion]

// Access the audit log table
$auditLogTable = TableFactory::build($db, $tablePolicy, 'items_audit_log');

// Find all audit entries for a specific record
$auditLogTable->clear();
$auditLogTable->record_id = 1;
$auditLogTable->find();

while ($auditLogTable->next()) {
    echo "Action: " . $auditLogTable->action . "\n";
    echo "Fields: " . $auditLogTable->fields . "\n";
    echo "Date: " . $auditLogTable->log_datetime . "\n";
}

use Amtgard\ActiveRecordOrm\Interface\DataAccessPolicy;

class CustomDataAccessPolicy implements DataAccessPolicy
{
    // Implement your custom caching or data access logic
}

$table = Table::builder()
    ->database($db)
    ->tableSchema($schema)
    ->queryBuilder($queryBuilder)
    ->dataAccessPolicy($policy)
    ->fieldSet($fieldSet)
    ->tableName('users')
    ->build();
bash
# Direct execution (if executable)
./repository <command> [options]

# Or via PHP
php bin/repository.php <command> [options]
bash
repository.php classes --env=<path> [--table=<table>] --out-dir=<path>
bash
repository.php schema --source=<path> [--table=<table>]
bash
# Generate SQL for a specific table
repository.php schema --source=./src/Entity --table=user_profiles

# Generate SQL for all RepositoryEntity classes
repository.php schema --source=./src/Entity
bash
repository.php phinx --source=<path> [--table=<table>] --file=<path>
bash
# Generate Phinx migration for a specific table
repository.php phinx --source=./src/Entity --table=user_profiles --file=./db/migrations/20251215143314_create_user_profiles.php

# Generate Phinx migration for all RepositoryEntity classes
repository.php phinx --source=./src/Entity --file=./db/migrations/20251215143314_create_all_tables.php
bash
repository.php audit --classes --env=<path> [--table=<table>] --out-dir=<path>
bash
# From RepositoryEntity classes
repository.php audit --schema --source=<path> [--table=<table>]

# From MySQL database
repository.php audit --schema --env=<path> [--table=<table>] --out-dir=<path>
bash
# From RepositoryEntity classes
repository.php audit --phinx --source=<path> [--table=<table>] --file=<path>

# From MySQL database
repository.php audit --phinx --env=<path> [--table=<table>] --out-dir=<path>
bash
repository.php audit --migrate --env=<path> [--table=<table>] --out-dir=<path>