PHP code example of icanboogie / activerecord

1. Go to this page and download the library: Download icanboogie/activerecord 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/ */

    

icanboogie / activerecord example snippets




use ICanBoogie\ActiveRecord;
use ICanBoogie\ActiveRecord\Validate\ValidateActiveRecord;
use ICanBoogie\ActiveRecord\ActiveRecordCache\RuntimeActiveRecordCache;
use ICanBoogie\ActiveRecord\Model;
use ICanBoogie\Prototype;

Prototype::configure([

    ActiveRecord::class => [

        'validate' => function(ActiveRecord $record) {

            static $validate;

            $validate ??= new ValidateActiveRecord;

            return $validate($record);

        }

    ],

    Model::class => [

        'lazy_get_activerecord_cache' => fn(Model $model) =>
            new RuntimeActiveRecordCache($model),

    ]

]);



use ICanBoogie\ActiveRecord\Connection;

# a connection to a MySQL database
$connection = new Connection('mysql:dbname=example', 'username', 'password');

# a connection to a SQLite temporary database stored in memory
$connection = new Connection('sqlite::memory:');



/* @var $connection \ICanBoogie\ActiveRecord\Connection */

$statement = $connection('SELECT * FROM `{table_name_prefix}nodes` LIMIT 10');



/* @var $connection \ICanBoogie\ActiveRecord\Connection */

$connection('ALTER TABLE nodes CHARACTER SET "{charset}" COLLATE "{collate}"');



namespace App\Modules\Nodes;

use ICanBoogie\ActiveRecord;
use ICanBoogie\ActiveRecord\ConnectionCollection;
use ICanBoogie\ActiveRecord\Model;
use ICanBoogie\ActiveRecord\ModelCollection;
use ICanBoogie\ActiveRecord\Schema\Character;
use ICanBoogie\ActiveRecord\Schema\Id;
use ICanBoogie\ActiveRecord\Schema\Integer;
use ICanBoogie\ActiveRecord\Schema\Serial;

/**
 * @extends Model<int, Node>
 */
 #[Model\Record(Node:::class)]
class NodeModel extends Model
{
}

/**
 * @extends ActiveRecord<int>
 */
class Node extends ActiveRecord
{
    #[Id, Serial]
    public int $id;

    #[Character(80)]
    public string $title;

    #[Integer]
    public int $number;

    // …
}

$config = (new ActiveRecord\ConfigBuilder())
    ->use_attributes()
    ->add_connection(/*...*/)
    ->add_record(NodeModel::class)
    ->build();

/* @var $connections ConnectionCollection */

$models = new ModelCollection($connections, $config->models);
$models->install();

$node_model = $models->model_for_record(Node::class);

$node = new Node($node_model);
//               ^^^^^^^^^^^
// because we don't use a model provider yet, we need to specify the model to the active record

$node->title = "My first node";
$node->number = 123;
$id = $node->save();
# or
$id = $node->id;

echo "Saved node, got id: $id\n";



/* @var $model \ICanBoogie\ActiveRecord\Model */

echo "table name: {$model->name}, original: {$model->unprefixed_name}.";



/* @var $model \ICanBoogie\ActiveRecord\Model */

$stmt = $model('SELECT * FROM `{self}` LIMIT 10');



/* @var \ICanBoogie\ActiveRecord\SchemaBuilder $schema */

$schema
    ->add_serial('id', primary: true)
    ->add_character('title', 80)
    ->add_integer('number')



/* @var $model \ICanBoogie\ActiveRecord\Model */

$model->install();



/* @var $model \ICanBoogie\ActiveRecord\Model */

if ($model->is_installed()) {
    echo "The model is already installed.";
}



namespace App;

use ICanBoogie\ActiveRecord\ConfigBuilder;
use ICanBoogie\ActiveRecord\SchemaBuilder;
use ICanBoogie\DateTime;

/* @var ConfigBuilder $config */

$config
    ->add_record(
        record_class: Node::class,
        schema_builder: fn(SchemaBuilder $b) => $b
            ->add_serial('nid', primary: true)
            ->add_character('title'),
    )
    ->add_record(
        record_class: Article::class,
        schema_builder: fn(SchemaBuilder $b) => $b
            ->add_character('body')
            ->add_date('date'),
    );

// …

$article = Article::from([
    'title' => "My Article",
    'body' => "Testing",
    'date' => DateTime::now()
]);

$article->save();



/* @var $news \ICanBoogie\ActiveRecord\Model */

echo $news->parent::class;       // NodeModel
echo $news->parent_model::class; // ContentModel



use ICanBoogie\ActiveRecord;
use ICanBoogie\ActiveRecord\Model;
use ICanBoogie\ActiveRecord\Schema\Id;
use ICanBoogie\ActiveRecord\Schema\Serial;
use ICanBoogie\ActiveRecord\Schema\BelongsTo;
use ICanBoogie\ActiveRecord\Schema\Character;
use ICanBoogie\ActiveRecord\ModelCollection;
use ICanBoogie\ActiveRecord\SchemaBuilder;

class Article extends ActiveRecord
{
    #[Id, Serial]
    public int $id;

    #[BelongsTo(User::class)]
    public int $uid;
}

class User extends ActiveRecord
{
    #[Id, Serial]
    public int $uid;

    #[Character]
    public string $name;
}

// …

/* @var $news Model */

$record = $news->query()->one;

echo "{$record->title} belongs to {$record->user->name}.";



use ICanBoogie\ActiveRecord;
use ICanBoogie\ActiveRecord\Model;
use ICanBoogie\ActiveRecord\Schema\Id;
use ICanBoogie\ActiveRecord\Schema\Serial;
use ICanBoogie\ActiveRecord\Schema\BelongsTo;
use ICanBoogie\ActiveRecord\Schema\Character;
use ICanBoogie\ActiveRecord\Schema\HasMany;
use ICanBoogie\ActiveRecord\ModelCollection;
use ICanBoogie\ActiveRecord\SchemaBuilder;

class Article extends ActiveRecord
{
    #[Id, Serial]
    public int $id;

    #[BelongsTo(User::class)]
    public int $uid;
}

#[HasMany(Article::class)]
class User extends ActiveRecord
{
    #[Id, Serial]
    public int $uid;

    #[Character]
    public string $name;
}

// …

/* @var $user User */

foreach ($user->articles as $article) {
    echo "User {$user->name} has article {$article->id}.";
}




namespace App;

use ICanBoogie\ActiveRecord;

class Node extends ActiveRecord
{
    // …

    protected function get_next()
    {
        return $this->model->own->visible->where('date > ?', $this->date)->order('date')->one;
    }

    protected function get_previous()
    {
        return $this->model->own->visible->where('date < ?', $this->date)->order('date DESC')->one;
    }

    // …
}



$record = Article::from([

    'title' => "An example",
    'body' => "My first article",
    'language' => "en",
    'is_online' => true

]);



use ICanBoogie\ActiveRecord;

// …

class User extends ActiveRecord
{
    use ActiveRecord\Property\CreatedAtProperty;
    use ActiveRecord\Property\UpdatedAtProperty;

    #[Id, Serial]
    public int $id;
    #[Character]
    public string $username;
    #[Character(unique: true)]
    public string $email;

    // …

    /**
     * @inheritdoc
     */
    public function create_validation_rules()
    {
        return [

            'username' => '



/* @var $model \ICanBoogie\ActiveRecord\Model */

$record = $model->find(10);
$record->is_online = false;
$record->save();



use ICanBoogie\ActiveRecord\RecordNotValid;

try
{
    $record->save();
}
catch (RecordNotValid $e)
{
    $errors = $e->errors;

    // …
}



use ICanBoogie\ActiveRecord;

$record->save([ ActiveRecord::SAVE_SKIP_VALIDATION => true ]);



/* @var $model \ICanBoogie\ActiveRecord\Model */

$record = $model->find(190);
$record->delete();



namespace App;

use ICanBoogie\ActiveRecord;
use ICanBoogie\ActiveRecord\Property\CreatedAtProperty;
use ICanBoogie\ActiveRecord\Property\UpdatedAtProperty;

class Node extends ActiveRecord
{
    public $title;

    use CreatedAtProperty;
    use UpdatedAtProperty;
}

$node = new Node;

echo get_class($node->created_at);   // ICanBoogie\Datetime
echo $node->created_at->is_empty;    // true
$node->created_at = 'now';
echo $node->created_at;              // 2014-02-21T15:00:00+0100



/* @var $query \ICanBoogie\ActiveRecord\Query */

$article = $model->find(10);



/* @var $query \ICanBoogie\ActiveRecord\Query */

$articles = $model->find(10, 32, 89);



use ICanBoogie\ActiveRecord\Config\ConnectionDefinition;
use ICanBoogie\ActiveRecord\ConnectionCollection;

$connections = new ConnectionCollection([

    new ConnectionDefinition(id: 'read', dsn: 'sqlite::memory:'),
    new ConnectionDefinition(id: 'write', dsn: 'mysql:dbname=my_database'),

]);

$connection = $connections->connection_for_id('read');



/* @var $connections \ICanBoogie\ActiveRecord\ConnectionCollection */

if (isset($connections->definitions['one']))
{
    echo "The connection 'one' is defined.\n";
}



/* @var $connections \ICanBoogie\ActiveRecord\ConnectionCollection */

foreach ($connections->established as $id => $connection)
{
    echo "The connection '$id' is established.\n";
}



/* @var $connections \ICanBoogie\ActiveRecord\ConnectionCollection */

foreach ($connections as $id => $connection)
{
    echo "The connection '$id' is established.\n";
}



use ICanBoogie\ActiveRecord\Model;
use ICanBoogie\ActiveRecord\ModelCollection;

/* @var $connections \ICanBoogie\ActiveRecord\ConnectionCollection */

$models = new ModelCollection($connections, [

    'nodes' => [

        // …
        Model::SCHEMA => [

            'nid' => 'serial',
            'title' => 'varchar'
            // …
        ]
    ],

    'contents' => [

        // …
        Model::EXTENDING => 'nodes'
    ]
]);

$model = $models->model_for_id('nodes');



use ICanBoogie\ActiveRecord\Model;

/* @var $models \ICanBoogie\ActiveRecord\ModelCollection */

$models['new'] = [

    // …
    Model::EXTENDING => 'contents'
];



/* @var $models \ICanBoogie\ActiveRecord\ModelCollection */

$nodes = $models['nodes'];



/* @var $models \ICanBoogie\ActiveRecord\ModelCollection */

foreach ($models->instances as $class => $model)
{
    echo "The model '$class' has been instantiated.\n";
}



/* @var $models \ICanBoogie\ActiveRecord\ModelCollection */

$models->install();
var_dump($models->is_installed()); // [ "NodeModel" => true, "ContentModel" => true ]
$models->uninstall();
var_dump($models->is_installed()); // [ "NodeModel" => false, "ContentModel" => false ]



use ICanBoogie\ActiveRecord;
use ICanBoogie\ActiveRecord\StaticModelProvider;

/* @var $provider ActiveRecord\ModelProvider */

StaticModelProvider::set(fn() => $provider);

$nodes = StaticModelProvider::model_for_record(Node::class);



use ICanBoogie\ActiveRecord\Model;
use ICanBoogie\Prototype;

Prototype::from('ICanBoogie\ActiveRecord\Model')['lazy_get_activerecord_cache'] = function(Model $model) {

    return new MyActiveRecordCache($model);

};



// config/prototype.php

return [

    'ICanBoogie\ActiveRecord\Model::lazy_get_activerecord_cache' => 'my_activerecord_cache_provider'

];



try
{
    // …
}
catch (\ICanBoogie\ActiveRecord\Exception $e)
{
    // an ActiveRecord exception
}
catch (\Exception $e)
{
    // some other exception
}