PHP code example of cycle / active-record

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

    

cycle / active-record example snippets




declare(strict_types=1);

namespace App\Application;

use Spiral\Cycle\Bootloader as CycleBridge;
use Cycle\ActiveRecord\Bridge\Spiral\Bootloader\ActiveRecordBootloader;

class Kernel extends \Spiral\Framework\Kernel
{
    public function defineBootloaders(): array
    {
        return [
            // ...

            // ORM
            CycleBridge\SchemaBootloader::class,
            CycleBridge\CycleOrmBootloader::class,
            CycleBridge\AnnotatedBootloader::class,

            // ActiveRecord
            ActiveRecordBootloader::class,

            // ...
        ];
}

\Cycle\ActiveRecord\Facade::setContainer($container);

use Cycle\ActiveRecord\ActiveRecord;
use Cycle\Annotated\Annotation\Column;
use Cycle\Annotated\Annotation\Entity;

#[Entity(table: 'users')]
class User extends ActiveRecord
{
    #[Column(type: 'primary', typecast: 'int')]
    public ?int $id = null;

    #[Column(type: 'string')]
    public string $name;

    public function create(string $name)
    {
        return self::make([
            'name' => $name,
        ]);
    }
}

$user = User::create(name: 'John');
$user->saveOrFail();

// Find users with advanced Cycle ORM filtering
$user = User::query()
    ->where('name', 'John')
    ->where('active', true)
    ->fetchOne();

// Find by primary key
$user = User::findByPK(42);

// Find with conditions
$users = User::findAll(['status' => 'active']);
$user = User::findOne(['email' => '[email protected]']);

$user1 = new User('Alice');
$user2 = new User('Bob');

// Group multiple operations in a single transaction
ActiveRecord::groupActions(function (EntityManagerInterface $em) use ($user1, $user2) {
    $user1->save();
    $user2->save();
    // Both users saved in one transaction
}, TransactionMode::OpenNew);

// Advanced transaction handling
User::transact(function (DatabaseInterface $db, EntityManagerInterface $em) {
    $user = User::query()->forUpdate()->fetchOne(['name' => 'Charlie']);
    $user->name = 'Charles';
    $user->save();
});