### Install Cycle Database Component Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/configuration.md Use this command to install the cycle/database component via Composer. ```bash composer require cycle/database ``` -------------------------------- ### Start Docker Containers for Testing Source: https://github.com/cycle/docs/blob/2.x/docs/en/contributing.md Navigate to the tests directory and start the necessary Docker containers to set up the ORM engine for local testing. ```bash cd tests docker-composer up ``` -------------------------------- ### Install cycle/entity-behavior Package Source: https://github.com/cycle/docs/blob/2.x/docs/en/entity-behaviors/install.md Install the entity-behavior package using composer. ```bash composer require cycle/entity-behavior ``` -------------------------------- ### Install Cycle Migrations Package Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/migrations.md Install the migrations package using Composer. This is the first step to enable database versioning. ```bash composer require cycle/migrations ``` -------------------------------- ### Install cycle/entity-behavior-uuid Source: https://github.com/cycle/docs/blob/2.x/docs/en/entity-behaviors/uuid.md Install the package as a dependency using Composer. ```bash composer require cycle/entity-behavior-uuid ``` -------------------------------- ### Cycle ORM Setup and Usage Source: https://github.com/cycle/docs/blob/2.x/docs/en/schema/dynamic-schema.md This snippet demonstrates the complete setup for Cycle ORM, including database configuration, schema definition, entity creation, persistence, and retrieval. Ensure the 'vendor/autoload.php' is correctly included. ```php [ 'default' => ['driver' => 'runtime'], ], 'connections' => [ 'runtime' => new Config\SQLiteDriverConfig( connection: new Config\SQLite\FileConnectionConfig( database: __DIR__.'./runtime/database.sqlite' ), queryCache: true, ), ], ])); // automatically migrate database schema if needed (optional) $users = $dbal->database('default')->table('users')->getSchema(); $users->primary('id'); $users->string('name'); $users->datetime('created_at'); $users->datetime('updated_at'); $users->save(); $orm = new ORM(new Factory($dbal), new Schema([ 'user' => [ Schema::MAPPER => StdMapper::class, Schema::DATABASE => 'default', Schema::TABLE => 'users', Schema::PRIMARY_KEY => 'id', Schema::COLUMNS => [ 'id' => 'id', // property => column_name 'name' => 'name', 'created_at' => 'created_at', 'updated_at' => 'updated_at', ], Schema::TYPECAST => [ 'id' => 'int', 'created_at' => 'datetime', 'updated_at' => 'datetime', ], Schema::RELATIONS => [], ], ])); $user = $orm->make('user', [ 'name' => 'test', 'created_at' => new DateTimeImmutable(), 'updated_at' => new DateTimeImmutable(), ]); (new EntityManager($orm))->persist($user)->run(); print_r( $orm->getRepository('user')->findAll() ); ``` -------------------------------- ### Instantiate DatabaseManager Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/connect.md Initialize the DatabaseManager service with a database configuration. Ensure all required dependencies are installed. ```php use Cycle\Database; use Cycle\Database\Config; $dbConfig = new Config\DatabaseConfig([ 'default' => 'default', 'databases' => [ 'default' => [ 'connection' => 'sqlite' ] ], 'connections' => [ 'sqlite' => new Config\SQLiteDriverConfig( connection: new Config\SQLite\MemoryConnectionConfig(), queryCache: true, ), ] ]); $dbal = new Database\DatabaseManager($dbConfig); ``` -------------------------------- ### Integer Column Type Examples Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/declaration.md Practical examples for using various integer column types, including setting nullability and default values. ```php // User age (0-150) $schema->tinyInteger('age')->nullable(false); // Order quantity (thousands) $schema->integer('quantity')->defaultValue(1); // File size in bytes (gigabytes) $schema->bigInteger('file_size_bytes')->nullable(false); ``` -------------------------------- ### Install cycle/orm-promise-mapper Source: https://github.com/cycle/docs/blob/2.x/docs/en/mapper/promise-mapper.md Use Composer to install the promise mapper package. ```bash composer require cycle/orm-promise-mapper ``` -------------------------------- ### Install Cycle ORM Annotated Extensions Source: https://github.com/cycle/docs/blob/2.x/docs/en/annotated/prerequisites.md Install the cycle/annotated and cycle/schema-builder extensions using Composer. ```bash composer require cycle/annotated cycle/schema-builder ``` -------------------------------- ### Usage Example for UserRepository Source: https://github.com/cycle/docs/blob/2.x/docs/en/active-record/active-repository.md Demonstrates how to instantiate and use the UserRepository to fetch a user by email and retrieve a collection of active users with their posts. ```php $repository = new UserRepository(); $user = $repository->getByEmail($email); $activeUsers = $repository ->whereActive() ->withPosts() ->findAll(); ``` -------------------------------- ### Install Cycle Schema Migrations Generator Source: https://github.com/cycle/docs/blob/2.x/docs/en/advanced/sync-schema.md Install the necessary package to enable automatic generation of migration files during schema compilation. ```bash composer require cycle/schema-migrations-generator ``` -------------------------------- ### Install Cycle ORM and Annotated Extension Source: https://context7.com/cycle/docs/llms.txt Install Cycle ORM and the annotated extension using Composer. This sets up the ORM for declarative schema definition. ```bash composer require cycle/orm composer require cycle/annotated ``` -------------------------------- ### Example String Type Usage Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/declaration.md Illustrates the basic usage of the `string` type with a specified column name and length. ```php $schema->string('email', 255) ``` -------------------------------- ### Example Text Type Usage Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/declaration.md Illustrates the basic usage of the `text` type with a specified column name. ```php $schema->text('description') ``` -------------------------------- ### Paginate Query Results with limit and offset Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/query-builders.md Use the `limit` and `offset` methods to paginate query results. This example fetches 10 records starting from the second record (offset 1). ```php $select = $db->table('test') ->select(['id', 'name', 'status']) ->limit(10) ->offset(1); foreach ($select as $row) { print_r($row); } ``` -------------------------------- ### Configure Database Connection Source: https://github.com/cycle/docs/blob/2.x/docs/en/intro/install.md Set up a database connection using DatabaseManager and a configuration object. This example configures an in-memory SQLite connection. ```php 'default', 'databases' => [ 'default' => ['connection' => 'sqlite'] ], 'connections' => [ 'sqlite' => new Config\SQLiteDriverConfig( connection: new Config\SQLite\MemoryConnectionConfig(), queryCache: true, ), ] ]) ); ``` -------------------------------- ### Configure Entity with Multiple Options Source: https://github.com/cycle/docs/blob/2.x/docs/en/annotated/entity.md A comprehensive example demonstrating how to configure an entity with various options, including table name, custom repository, scope, and typecast handlers. ```php use Cycle\Annotated\Annotation\Entity; #[Entity( table: 'users', repository: \App\Repository\UserRepository::class, scope: \App\Scope\SortByID::class, typecast: [\App\Typecast\JsonTypecast::class, \Cycle\ORM\Parser\Typecast::class] )] class User { // ... } ``` -------------------------------- ### Example Double Type Usage Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/declaration.md Illustrates the basic usage of the `double` type with a specified column name. ```php $schema->double('coordinates') ``` -------------------------------- ### Select All Columns with COUNT(*) Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/query-builders.md This example shows how to select all columns using `COUNT(*)` within the select statement. ```php $select = $db->table('test')->select(['COUNT(*)']); ``` -------------------------------- ### Example Float Type Usage Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/declaration.md Illustrates the basic usage of the `float` type with a specified column name. ```php $schema->float('rating') ``` -------------------------------- ### Install Cycle ORM Annotated Package Source: https://github.com/cycle/docs/blob/2.x/docs/en/intro/install.md Install the cycle/annotated package to define entity schemas using PHP attributes. Requires PHP 8.1+. ```bash composer require cycle/annotated ``` -------------------------------- ### Install Cycle ORM with Composer Source: https://github.com/cycle/docs/blob/2.x/docs/en/active-record/installation.md Use Composer to install the cycle/active-record package. This is the preferred method for adding Cycle ORM to your project. ```bash composer require cycle/active-record ``` -------------------------------- ### Example Decimal Type Usage Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/declaration.md Illustrates the basic usage of the `decimal` type with a specified column name, precision, and scale. ```php $schema->decimal('price', 10, 2) ``` -------------------------------- ### Example LongText Type Usage Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/declaration.md Illustrates the basic usage of the `longText` type with a specified column name. ```php $schema->longText('content') ``` -------------------------------- ### Basic ActiveRecord Usage Example Source: https://github.com/cycle/docs/blob/2.x/docs/en/advanced/active-record.md Demonstrates finding a user, updating their name, and saving the changes. Assumes a User model with a 'name' property and a find method. ```php $user = User::find()->findOne(['name' => 'John']) ?? new User(); $user->name = "new name"; $user->save(); ``` -------------------------------- ### Fetch Users with Combined Query Methods Source: https://github.com/cycle/docs/blob/2.x/docs/en/active-record/active-query.md Example of fetching user records using methods from both common and entity-specific query classes. ```php $users = User::query() ->active(false) ->emailVerified(true) ->subscribtionLevel(Subsctiption::Any) ->fetchAll(); $mailer->sendReminder($users); ``` -------------------------------- ### Fetching Relations with Collections Source: https://github.com/cycle/docs/blob/2.x/docs/en/relation/collections.md Example of fetching a user entity and accessing its 'posts' relation, which will be an instantiated collection. ```php $user = $orm->getRepository(User::class) ->select() ->with('posts')->limit(1)->fetchOne(); print_r($user->posts); ``` -------------------------------- ### Configure Separate Read and Write Connections Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/configuration.md Example of configuring separate connections for read (SELECT) and write (INSERT, UPDATE, DELETE) operations. This can improve performance and manage load. ```php use Cycle\Database\Driver; $dbal = new DatabaseManager(new DatabaseConfig([ 'databases' => [ // Will be used for read and write operations 'primary' => [ 'driver' => 'mysql', // or 'write' => 'mysql' // ... ], 'secondary' => [ 'write' => 'mysql', // Will be used for write operations 'read' => 'sqlite', // Will be used for read operations // ... ] ], 'connections' => [ // ... ], ])); ``` -------------------------------- ### Example TinyText Type Usage Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/declaration.md Illustrates the basic usage of the `tinyText` type with a specified column name. ```php $schema->tinyText('code') ``` -------------------------------- ### Example MediumText Type Usage Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/declaration.md Illustrates the basic usage of the `mediumText` type with a specified column name. ```php $schema->mediumText('article') ``` -------------------------------- ### Initialize Insert Builder Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/query-builders.md Get an instance of the InsertBuilder to prepare for inserting data into a specified table. This is the first step before adding values. ```php $insert = $db->insert('test'); ``` -------------------------------- ### Initialize ORM with Custom Schema Source: https://github.com/cycle/docs/blob/2.x/docs/en/schema/manual.md Instantiate the ORM with a custom schema object. This is the starting point for manual schema definition. ```php use Cycle\ORM\Schema; $orm = $orm->with(schema: new Schema([ // ... schema ... ])); ``` -------------------------------- ### Declare SQLite Connection with Runtime Configuration Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/configuration.md Example of declaring a new database connection using SQLite with a file-based configuration. Ensure the 'vendor/autoload.php' is included. ```php [ 'default' => [ 'driver' => 'runtime' ], ], 'connections' => [ 'runtime' => new Config\SQLiteDriverConfig( connection: new Config\SQLite\FileConnectionConfig( database: __DIR__.'./runtime/database.sqlite' ), queryCache: true, ), ], ])); ``` -------------------------------- ### Implement Migration Down Method Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/migrations.md Example of implementing the `down()` method in a migration to reverse the changes made by the `up()` method. This is crucial for safe rollbacks. ```php public function up(): void { // Add new required column with default value $this->table('users') ->addColumn('role', 'string', ['default' => 'user']) ->update(); } public function down(): void { // Rollback: drop the column (data will be lost) $this->table('users') ->dropColumn('role') ->update(); } ``` -------------------------------- ### Configure Cycle Migrations Source: https://github.com/cycle/docs/blob/2.x/docs/en/advanced/sync-schema.md Configure the migration directory and the database table used to store migration status. This setup is required before initializing the migrator. ```php use Cycle\Migrations; $config = new Migrations\Config\MigrationConfig([ 'directory' => __DIR__ . '/../migrations/', // where to store migrations 'table' => 'migrations' // database table to store migration status ]); $migrator = new Migrations\Migrator($config, $dbal, new Migrations\FileRepository($config)); // Init migration table $migrator->configure(); ``` -------------------------------- ### Fetch Users with Custom Query Methods Source: https://github.com/cycle/docs/blob/2.x/docs/en/active-record/active-query.md Example of fetching user records using custom methods defined in the CommonQuery class. ```php $users = User::query() ->active(false) ->sortByCreateTime(false) ->fetchAll(); ``` -------------------------------- ### Start and Commit Transaction Manually Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/transactions.md Use `begin` and `commit` methods on the Database instance to manage transactions manually. Ensure all queries are within the transaction block. ```php $db->begin(); // your queries $db->commit(); ``` -------------------------------- ### SQL Example: RefersTo Extra Update Query Source: https://github.com/cycle/docs/blob/2.x/docs/en/relation/refers-to.md Illustrates the sequence of SQL queries required for a `RefersTo` relation, highlighting the extra UPDATE query needed to set the foreign key. ```sql -- 1. Insert source INSERT INTO users (username) VALUES ('john'); -- 2. Insert target INSERT INTO comments (text) VALUES ('Great!'); -- 3. Update source with reference UPDATE users SET last_comment_id = 1 WHERE id = 1; ``` -------------------------------- ### Get ActiveQuery Instance in ActiveRecord Source: https://github.com/cycle/docs/blob/2.x/docs/en/active-record/active-query.md Entities extending ActiveRecord automatically provide a query() method to get an ActiveQuery instance. ```php public static function query(): ActiveQuery { return new ActiveQuery(static::class); } ``` -------------------------------- ### Load and Filter Relations Simultaneously Source: https://github.com/cycle/docs/blob/2.x/docs/en/query-builder/relations.md Combine `load` with filtering and `with` for complex selection criteria. This example loads published posts while filtering for flagged posts. ```php $select ->load('posts', [ 'where' => ['published' => true] ]) ->with('posts')->where('posts.flagged', true); ``` -------------------------------- ### Configure Database with Read/Write Connections Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/connect.md Set up a database to use separate connections for read and write operations, along with a prefix. ```php 'default' => [ 'connection' => 'mysql', 'readConnection' => 'mysqlSlave', 'prefix' => 'secondary_' ] ``` -------------------------------- ### Run Quick Test Suite (SQLite) Source: https://github.com/cycle/docs/blob/2.x/docs/en/contributing.md Execute a subset of tests focusing on the SQLite driver for faster feedback during development. Ensure Docker containers are running. ```bash ./vendor/bin/phpunit tests/ORM/Functional/Driver/SQLite ``` -------------------------------- ### Implementing a Custom Collection Factory Source: https://github.com/cycle/docs/blob/2.x/docs/en/relation/collections.md Demonstrates how to create a custom collection factory by implementing the CollectionFactoryInterface. ```php use Cycle\ORM\Collection\CollectionFactoryInterface; class ArrayCollectionFactory implements CollectionFactoryInterface { public function withCollectionClass(string $class): static { // Do nothing return $this; } public function collect(iterable $data): array { return match (true) { \is_array($data) => $data, $data instanceof \Traversable => \iterator_to_array($data), default => throw new CollectionFactoryException('Unsupported iterable type.'), }; } } ``` -------------------------------- ### Initialize Root and Link External Node Source: https://github.com/cycle/docs/blob/2.x/docs/en/advanced/node-parser.md Sets up a RootNode for users and links an ArrayNode for orders. This prepares for fetching orders via a separate query, using collected user IDs. ```php use Cycle\ORM\Parser; use Cycle\Database\StatementInterface; $query = $db->select('u.id', 'u.balance')->from('users as u'); $root = new Parser\RootNode( ['id', 'balance'], ['id'] ); $orders = new Parser\ArrayNode( ['id', 'user_id', 'total'], // column names ['id'], // primary keys ['user_id'], // inner keys ['id'] // outer keys (user.id) ); // notice the change $root->linkNode('orders', $orders); foreach ($query->run()->fetchAll(StatementInterface::FETCH_NUM) as $row) { // start from 1st (0) column $root->parseRow(0, $row); } ``` -------------------------------- ### Create User Entity using make() Method Source: https://github.com/cycle/docs/blob/2.x/docs/en/active-record/active-entity.md The `make()` method provides a convenient way to instantiate entities by passing an array of properties. Ensure the entity class is defined before use. ```php $user = User::make([ 'name' => $name, 'email' => $email, ]); ``` -------------------------------- ### Retrieve Table Primary Keys Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/introspection.md Get an array of primary keys defined for the table schema. ```php print_r($schema->getPrimaryKeys()); ``` -------------------------------- ### Install Cycle ORM with Composer Source: https://github.com/cycle/docs/blob/2.x/docs/en/intro/install.md Use this command to add the Cycle ORM package to your project dependencies. ```bash composer require cycle/orm ``` -------------------------------- ### Configure Database with Prefix Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/connect.md Register a new database with a specific connection and apply a prefix to all queries. ```php 'default' => [ 'connection' => 'sqlite', 'prefix' => 'secondary_' ] ``` -------------------------------- ### Select Users Query Source: https://github.com/cycle/docs/blob/2.x/docs/en/advanced/node-parser.md Initializes a simple database query to select 'id' and 'balance' from the 'users' table. ```php $query = $db->select('id', 'balance')->from('users'); ``` -------------------------------- ### Create and Save User Source: https://github.com/cycle/docs/blob/2.x/docs/en/advanced/active-record.md Demonstrates creating a new User entity, setting its properties, and saving it to the database using the Active Record pattern. ```php $user = new User(); $user->name = 'Antony'; $user->save(); print_r($u->id); ``` -------------------------------- ### Create User Entity with make() Source: https://github.com/cycle/docs/blob/2.x/docs/en/active-record/active-entity.md Use the `make()` static factory method to create new entity instances with provided properties. This is the recommended approach over direct constructor usage. ```php $user = User::make([ 'name' => 'John Doe', 'email' => 'johndoe@example.com', ]); ``` -------------------------------- ### Configure Database Connections Source: https://context7.com/cycle/docs/llms.txt Configures database connections for various types including MySQL, PostgreSQL, and SQLite. Demonstrates setting up default and secondary databases, read/write splitting, and table prefixes. ```php 'default', 'databases' => [ 'default' => [ 'connection' => 'mysql', 'prefix' => 'app_' // Optional table prefix ], 'secondary' => [ 'connection' => 'mysql', 'readConnection' => 'mysqlSlave' // Read/write splitting ] ], 'connections' => [ // MySQL connection 'mysql' => new Config\MySQLDriverConfig( connection: new Config\MySQL\TcpConnectionConfig( database: 'myapp', host: '127.0.0.1', port: 3306, user: 'root', password: 'secret', ), queryCache: true ), // PostgreSQL connection 'postgres' => new Config\PostgresDriverConfig( connection: new Config\Postgres\TcpConnectionConfig( database: 'myapp', host: '127.0.0.1', port: 5432, user: 'postgres', password: 'secret', ), schema: 'public', queryCache: true, ), // SQLite file connection 'sqlite' => new Config\SQLiteDriverConfig( connection: new Config\SQLite\FileConnectionConfig( database: __DIR__ . '/database.sqlite' ), queryCache: true, ), ] ]); $dbal = new Database\DatabaseManager($dbConfig); // Access database $db = $dbal->database('default'); print_r($db->getTables()); // Execute raw queries $results = $db->table('users')->select()->fetchAll(); ``` -------------------------------- ### Add a Named Composite Index Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/migrations.md Example of adding a composite index with a specific name and ensuring it is not unique. ```php $this->table('products') ->addIndex(['category_id', 'price'], [ 'name' => 'idx_products_category_price', 'unique' => false ]) ->update(); ``` -------------------------------- ### Configure and Run Database Migrations Source: https://context7.com/cycle/docs/llms.txt Instantiate MigrationConfig and Migrator to manage migration execution. Use the 'run' method to apply pending migrations and 'rollback' to revert the last applied migration. ```php // Configure and run migrations $config = new MigrationConfig([ 'directory' => __DIR__ . '/migrations/', 'table' => 'migrations', 'namespace' => 'Migration', 'safe' => false ]); $migrator = new Migrator($config, $dbal, new FileRepository($config)); $migrator->configure(); // Run pending migrations while (($migration = $migrator->run()) !== null) { echo "Executed: " . $migration->getState()->getName() . "\n"; } // Rollback last migration $migration = $migrator->rollback(); if ($migration) { echo "Rolled back: " . $migration->getState()->getName() . "\n"; } ``` -------------------------------- ### Make a Column Nullable Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/migrations.md Example of altering a column to allow NULL values. The `down()` method demonstrates reverting this change. ```php public function up(): void { $this->table('posts') ->alterColumn('excerpt', 'text', ['nullable' => true]) ->update(); } public function down(): void { $this->table('posts') ->alterColumn('excerpt', 'text', ['nullable' => false]) ->update(); } ``` -------------------------------- ### Initialize Migrator Instance Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/migrations.md Create and configure the migrator instance using the MigrationConfig, a database provider, and a file repository. Call `configure()` to ensure the migration tracking table exists. ```php use Cycle\Migrations\Migrator; use Cycle\Migrations\FileRepository; $migrator = new Migrator( $config, $dbal, // DatabaseProviderInterface instance new FileRepository($config) ); // Initialize the migration tracking table $migrator->configure(); ``` -------------------------------- ### Rename Table Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/declaration.md Rename an existing table by getting its schema object and then using the `setName()` method with the new table name. ```php $schema = $database->table('old_users')->getSchema(); $schema->setName('users'); $schema->save(); ``` -------------------------------- ### Get List of Available Migrations Source: https://github.com/cycle/docs/blob/2.x/docs/en/advanced/sync-schema.md Retrieve a list of all available migration files using the `getMigrations` method of the `Migrator` instance. ```php print_r($migrator->getMigrations()); ``` -------------------------------- ### Get Iterator from Select Source: https://github.com/cycle/docs/blob/2.x/docs/en/advanced/iterator.md Obtain an Iterator object from the `getIterator` method of the `Cycle\ORM\Select` class. This is the default way to initiate the iterator. ```php $select = $orm->getRepository('user')->select(); foreach ($select as $user) { print_r($user); } ``` -------------------------------- ### Basic Entity Persistence Source: https://github.com/cycle/docs/blob/2.x/docs/en/advanced/entity-manager.md Demonstrates the basic usage of persisting an entity and running the transaction. ```php $manager = new \Cycle\ORM\EntityManager($orm); $manager->persist($entity); $manager->run(); ``` -------------------------------- ### Group Results with groupBy Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/query-builders.md The `groupBy` method allows for grouping results based on specified columns. This example groups by 'status'. ```php $select = $db->table('test') ->select(['status', 'count(*) as count']) ->groupBy('status'); ``` -------------------------------- ### Initialize Database Manager Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/access.md Initialize the DatabaseManager with your configuration. Ensure DBAL component is configured properly before use. ```php declare(strict_types=1); require_once "vendor/autoload.php"; use Cycle\Database\Config\DatabaseConfig; use Cycle\Database\DatabaseManager; use Cycle\Database\Driver\SQLite\SQLiteDriver; $dbal = new DatabaseManager(new DatabaseConfig(...)); ``` -------------------------------- ### Run Full Test Suite Source: https://github.com/cycle/docs/blob/2.x/docs/en/contributing.md Execute the complete test suite for the Cycle ORM using PHPUnit. Ensure Docker containers are running. ```bash ./vendor/bin/phpunit ``` -------------------------------- ### Defining a HasMany relation with default ArrayCollection Source: https://github.com/cycle/docs/blob/2.x/docs/en/relation/collections.md Example of defining a User entity with a 'posts' relation using the default ArrayCollection. ```php use Cycle\Annotated\Annotation\Entity; use Cycle\Annotated\Annotation\Relation\HasMany; #[Entity] class User { // ... #[HasMany(target: Post::class)] public array $posts; } ``` -------------------------------- ### Manual Database Instance Creation Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/configuration.md Create a Database instance manually without using the DatabaseManager. This involves creating driver instances for read and write operations separately. ```php use Cycle\Database\Driver; use Cycle\Database\Config; $writeDriver = Driver\SQLite\SQLiteDriver::create( new Config\MemoryConnectionConfig() ); $readDriver = Driver\SQLite\SQLiteDriver::create( new Config\TempFileConnectionConfig() ); $db = new Database\Database( name: 'name', prefix: '', driver: $writeDriver, readDriver: $readDriver // read only driver (optional) ); print_r($db->getTables()); ``` -------------------------------- ### Custom Typecast Handler Implementation Source: https://github.com/cycle/docs/blob/2.x/docs/en/advanced/typecasting.md Implement `CastableInterface` and `UncastableInterface` for custom typecasting logic. This example handles UUID conversion. ```php use Cycle\ORM\Parser\CastableInterface; use Cycle\ORM\Parser\UncastableInterface; final class UuidTypecast implements CastableInterface, UncastableInterface { private array $rules = []; public function __construct( private DatabaseInterface $database ) { } public function setRules(array $rules): array { foreach ($rules as $key => $rule) { if ($rule === 'uuid') { unset($rules[$key]); $this->rules[$key] = $rule; } } return $rules; } public function cast(array $values): array { foreach ($this->rules as $column => $rule) { if (! isset($values[$column])) { continue; } $values[$column] = Uuid::fromString($values[$column]); } return $values; } public function uncast(array $values): array { foreach ($this->rules as $column => $rule) { if (! isset($values[$column]) || !$values[$column] instanceof UuidInterface) { continue; } $values[$column] = $values[$column]->toString(); } return $values; } } ``` -------------------------------- ### Get Database Access Source: https://github.com/cycle/docs/blob/2.x/docs/en/query-builder/extended.md Access the desired database using either the DatabaseManager or an entity source. This is a prerequisite for performing database operations. ```php // via DatabaseManager $db = $dbal->database('default'); // via Entity source $db = $orm->getSource(User::class)->getDatabase(); ``` -------------------------------- ### Get Generated SQL Statement Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/query-builders.md View the SQL query string that will be executed by the builder. Useful for debugging and understanding the generated query. ```php print_r( $db->users->select() ->columns('name') ->sqlStatement() ); ``` -------------------------------- ### Execute Aggregations with count, sum, avg, max, min Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/query-builders.md Use dedicated methods like `count`, `sum`, `avg`, `max`, and `min` to perform aggregations without manual column manipulation. This example demonstrates `count` and `sum`. ```php $select = $db->table('test') ->select(['id', 'name', 'status']); print_r($select->count()); print_r($select->sum('balance')); ``` -------------------------------- ### Get BulkLoader Instance via DI Source: https://github.com/cycle/docs/blob/2.x/docs/en/relation/bulk-loader.md Inject the BulkLoaderInterface into your services when using a Cycle ORM bridge by retrieving it from the DI container. ```php use Cycle\ORM\Relation\BulkLoaderInterface; final class Service { public function __construct( private BulkLoaderInterface $bulkLoader ) {} } ``` -------------------------------- ### Update with Expression Source: https://github.com/cycle/docs/blob/2.x/docs/en/query-builder/extended.md Use Expression and Fragment instances for dynamic update values. This example uses an Expression to convert the name to uppercase. ```php $update = $database->table('test')->update([ 'name' => new \Cycle\Database\Injection\Expression('UPPER(test.name)') ]); $update->where('id', '<', 10)->run(); ``` ```sql UPDATE `primary_test` SET `name` = UPPER(`primary_test`.`name`) WHERE `id` < 10 ``` -------------------------------- ### Update with Nested Query Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/query-builders.md Nested queries are supported in update values. This example sets the 'name' to a value selected from another table. ```php $update = $db->table('test') ->update([ 'name' => $database ->table('users') ->select('name') ->where('id', 1) ]) ->where('id', '<', 10)->run(); ``` -------------------------------- ### Configure Migration Settings Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/migrations.md Customize migration behavior and storage by creating a MigrationConfig instance. Specify directories for migration files, the database table name for tracking, the namespace for generated classes, and whether to run migrations in safe mode. ```php use Cycle\Migrations\Config\MigrationConfig; $config = new MigrationConfig([ // Directory where migration files are stored 'directory' => __DIR__ . '/../migrations/', // Additional vendor directories for third-party migrations 'vendorDirectories' => [ __DIR__ . '/../vendor/some-package/migrations/', ], // Database table name for tracking migration status 'table' => 'migrations', // Namespace for generated migration classes 'namespace' => 'Migration', // When true, migrations run without user confirmation (use carefully in production) 'safe' => false ]); ``` -------------------------------- ### Configure ORM with Manual Schema Definition Source: https://github.com/cycle/docs/blob/2.x/docs/en/basic/no-annotations.md Set up an ORM instance with manually defined mapping schemas for entities and their relations. This example configures database connections, entity mappings, columns, typecasting, and relations, including a HasOne relationship between User and Profile. ```php 'default', 'databases' => [ 'default' => ['connection' => 'sqlite'] ], 'connections' => [ 'sqlite' => new Config\SQLiteDriverConfig( connection: new SQLite\MemoryConnectionConfig(), queryCache: true, ), ] ]) ); $orm = new ORM\ORM(new ORM\Factory($dbal), new Schema([ 'user' => [ Schema::ENTITY => User::class, Schema::MAPPER => ORM\Mapper\Mapper::class, Schema::DATABASE => 'default', Schema::TABLE => 'user', Schema::PRIMARY_KEY => 'id', Schema::COLUMNS => [ 'id' => 'id', 'email' => 'email', 'balance' => 'balance', ], Schema::TYPECAST => [ 'id' => 'int', 'balance' => 'float', ], Schema::RELATIONS => [ 'profile' => [ Relation::TYPE => Relation::HAS_ONE, Relation::TARGET => 'profile', Relation::SCHEMA => [ Relation::CASCADE => true, Relation::INNER_KEY => 'id', Relation::OUTER_KEY => 'user_id', ], ], ], ], 'profile' => [ Schema::ENTITY => Profile::class, Schema::MAPPER => ORM\Mapper\Mapper::class, Schema::DATABASE => 'default', Schema::TABLE => 'profile', Schema::PRIMARY_KEY => 'id', Schema::COLUMNS => [ 'id' => 'id', 'user_id' => 'user_id', 'image' => 'image', ], Schema::TYPECAST => [ 'id' => 'int', 'user_id' => 'int', ], Schema::RELATIONS => [], ], ])); print_r($orm->getRepository(User::class)->findOne()); ``` -------------------------------- ### Declare MySQL Databases with Prefixes Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/configuration.md Demonstrates declaring multiple MySQL databases with distinct prefixes within the DatabaseManager configuration. Access databases using their declared names. ```php use Cycle\Database\Driver; $dbal = new DatabaseManager(new DatabaseConfig([ 'databases' => [ 'primary' => [ 'driver' => 'mysql', 'prefix' => 'primary_' ], 'secondary'=> [ 'driver' => 'mysql', 'prefix' => 'secondary_' ] ], 'connections' => [ // ... ], ])); print_r($dbal->database('primary')); print_r($dbal->database('secondary')); ``` -------------------------------- ### Get Tables in Dependency Order Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/declaration.md Retrieve tables sorted by their dependencies using Reflector. This allows for manual processing or inspection of the synchronization order. ```php $reflector = new Reflector(); $reflector->addTable($users); $reflector->addTable($posts); $reflector->addTable($comments); // Get tables in dependency order $sortedTables = $reflector->sortedTables(); foreach ($sortedTables as $table) { echo "Processing: " . $table->getName() . "\n"; } ``` -------------------------------- ### Insert Data using Database Access Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/migrations.md Demonstrates accessing the database instance within a migration's `up()` method to perform data operations like inserting initial records. ```php public function up(): void { // Access database for data operations $db = $this->database(); // Insert initial data $db->insert('roles')->values([ ['name' => 'admin'], ['name' => 'user'], ])->run(); } ``` -------------------------------- ### Get Table Schema Information Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/introspection.md Access the schema reader/builder for a table using the `getSchema` method. This provides low-level access to table properties. ```php foreach ($database->getTables() as $table) { print_r($table->getSchema()); } ``` -------------------------------- ### Get Repository by Entity Class Source: https://github.com/cycle/docs/blob/2.x/docs/en/basic/select.md Access the repository for a specific entity using its class name. This is the recommended way to interact with entity data. ```php $repository = $orm->getRepository(User::class); ``` -------------------------------- ### Attribute-Based Typecasting Source: https://github.com/cycle/docs/blob/2.x/docs/en/advanced/typecasting.md Apply typecasting rules directly to entity properties using the `typecast` attribute. This example configures UUID typecasting for a property. ```php use Cycle\Annotated\Annotation\Entity; use Ramsey\Uuid\UuidInterface; #[Entity( typecast: [ \Cycle\ORM\Parser\Typecast::class, App\UuidTypecast::class, 'carbon_typecast' ] )] class User { #[Cycle\Column(type: 'string', typecast: 'uuid')] public UuidInterface $uuid; } ``` -------------------------------- ### Implement Reversible Migrations Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/migrations.md Always implement both `up()` and `down()` methods for full reversibility. This ensures you can apply and revert changes safely. ```php // Good - Fully reversible public function up(): void { $this->table('users')->addColumn('deleted_at', 'datetime', ['nullable' => true])->update(); } public function down(): void { $this->table('users')->dropColumn('deleted_at')->update(); } ``` -------------------------------- ### Implement a Not Deleted Scope Source: https://github.com/cycle/docs/blob/2.x/docs/en/advanced/scope.md Implement the `Select\ScopeInterface` to define custom query constraints. This example filters entities by ensuring the 'deleted_at' column is null. ```php use Cycle\ORM\Select; class NotDeletedScope implements Select\ScopeInterface { public function apply(Select\QueryBuilder $query) { $query->where('deleted_at', '=', null); } } ``` -------------------------------- ### Custom Repository Implementation Source: https://context7.com/cycle/docs/llms.txt Create custom repositories by extending Select\Repository to encapsulate domain-specific queries and business logic. Define methods for common query patterns. ```php select()->where('status', 'active'); } public function findByEmail(string $email): ?User { return $this->findOne(['email' => $email]); } public function findActiveWithPosts(): Select { return $this->findActive() ->load('posts', ['where' => ['published' => true]]); } public function findRecentlyRegistered(int $days = 7): Select { $since = (new \DateTime())->modify("-{$days} days"); return $this->select() ->where('created_at', '>=', $since) ->orderBy('created_at', 'DESC'); } public function searchByUsername(string $query): Select { return $this->select() ->where('username', 'like', "%{$query}%") ->orderBy('username', 'ASC'); } public function findWithHighBalance(float $minimum): Select { return $this->findActive() ->where('balance', '>=', $minimum) ->orderBy('balance', 'DESC'); } } // Usage $userRepository = $orm->getRepository(User::class); $activeUsers = $userRepository->findActive()->fetchAll(); $recentUsers = $userRepository->findRecentlyRegistered(30)->limit(10)->fetchAll(); ``` -------------------------------- ### Create Relations and Save Source: https://github.com/cycle/docs/blob/2.x/docs/en/relation/many-to-many.md Demonstrates creating a User entity, associating multiple Tag entities with it, and persisting them using the EntityManager. Related entities are automatically saved. ```php setUsername("johndoe"); $tag1 = new Tag("php"); $tag2 = new Tag("database"); $tag3 = new Tag("orm"); $user->addTag($tag1); $user->addTag($tag2); $user->addTag($tag3); $manager = new \Cycle\ORM\EntityManager($orm); $manager->persist($user); $manager->run(); ``` -------------------------------- ### Batch Persistence and Heap Cleaning Source: https://github.com/cycle/docs/blob/2.x/docs/en/advanced/entity-manager.md Shows how to perform batch persistence operations within a loop and manually clean the ORM Heap afterwards. ```php $manager = new \Cycle\ORM\EntityManager($orm); for ($i=0; $i<1000; $i++) { $manager->persist($e); $manager->run(); } $orm->getHeap()->clean(); // or $manager->clean(cleanHeap: true); ``` -------------------------------- ### Get SelectQuery Builder Instance Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/query-builders.md Retrieve an instance of the SelectQuery Builder from either the database or a table instance. This builder is used for constructing SELECT statements. ```php $select = $db->table('test')->select(); // alternative $select = $db->select()->from('test'); // alternative $select = $db->test->select(); ``` -------------------------------- ### Appropriate Column Types Example Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/declaration.md Choose the smallest appropriate data type for columns to optimize storage and performance. Avoid oversized types like bigInteger for small ranges or float for exact monetary values. ```php // ✅ GOOD: Right-sized types $schema->tinyInteger('age'); // 0-255 $schema->string('country_code', 2); // 'US', 'UK' $schema->decimal('price', 10, 2); // Exact money values // ❌ AVOID: Oversized types $schema->bigInteger('age'); // Wastes space $schema->string('country_code', 255); // Wastes space $schema->float('price'); // Imprecise for money ``` -------------------------------- ### Get Table Schema Instance Source: https://github.com/cycle/docs/blob/2.x/docs/en/database/declaration.md Obtain an AbstractTable instance to interact with a table's schema. The system handles table creation and modification transparently. ```php use Cycle\Database\Database; $database = new Database(/* ... */); // Get schema for new or existing table $schema = $database->table('users')->getSchema(); // Check if table exists in database if ($schema->exists()) { echo "Table exists"; } else { echo "Table will be created"; } ``` -------------------------------- ### Initialize Schema Registry Source: https://github.com/cycle/docs/blob/2.x/docs/en/schema/schema-builder.md Create a `Registry` object to begin manually defining your ORM schema. This requires a `dbal` instance. ```php $registry = new \Cycle\Schema\Registry($dbal); ``` -------------------------------- ### Get Repository for StdClass Entity Source: https://github.com/cycle/docs/blob/2.x/docs/en/schema/dynamic-schema.md Access the repository for an entity defined as a StdClass object by its role name. This is required when working with entities mapped by StdMapper. ```php $userRepository = $orm->getRepository('user'); ```