### Configure Database Connection with DatabaseManager Source: https://cycle-orm.dev/docs/intro-quick-start/1.x/en Sets up a database connection using Cycle ORM's DatabaseManager. This example configures a SQLite connection, which is initiated on demand. It requires the 'spiral/database' package. ```php 'default', 'databases' => [ 'default' => ['connection' => 'sqlite'] ], 'connections' => [ 'sqlite' => [ 'driver' => Database\Driver\SQLite\SQLiteDriver::class, 'connection' => 'sqlite:database.db', 'username' => '', 'password' => '', ] ] ]) ); ``` -------------------------------- ### Full Cycle ORM Setup with Manual Schema and Entity Persistence (PHP) Source: https://cycle-orm.dev/docs/schema-dynamic-schema/current/en A comprehensive example demonstrating the complete setup of Cycle ORM, including database configuration, schema definition, entity creation, and persistence using an EntityManager. This script sets up a SQLite database, defines a 'user' entity schema, creates a user instance, persists it, and then retrieves all users. ```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() ); ``` -------------------------------- ### Check Class Visibility with ClassLocator (PHP) Source: https://cycle-orm.dev/docs/intro-quick-start/1.x/en Demonstrates how to verify if the ClassLocator has successfully indexed and made your entity classes visible. This is a simple debugging step after setting up the ClassLocator. ```php print_r($classLocator->getClasses()); ``` -------------------------------- ### RefersTo Usage Examples Source: https://cycle-orm.dev/docs/relation-refers-to/current/en Provides practical code examples for creating, updating, and removing RefersTo relations, illustrating the ORM's behavior during these operations. ```APIDOC ## RefersTo Usage Examples ### Description Illustrates how to perform common operations with RefersTo relations. ### Creating Relations **Description:** The ORM automatically saves the related entity and links to it, unless `cascade: false` is set. **Example:** ```php $user = new User(); $user->setUsername("johndoe"); $comment = new Comment("Great article!"); $user->addComment($comment); // Assuming addComment method sets the relation $manager = new \Cycle\ORM\EntityManager($orm); $manager->persist($user); $manager->run(); ``` **Persist Order:** 1. Source entity (`User`) is persisted first (without FK reference). 2. Target entity (`Comment`) is persisted with its generated ID. 3. Source entity is updated with the FK reference to the target. ### Updating Relations **Description:** To update a relation, simply change the reference to the new related entity. **Example:** ```php $user = $orm->getRepository(User::class)->findByPK(1); $newComment = new Comment("Updated comment"); $user->addComment($newComment); // Assuming addComment method sets the relation $manager = new \Cycle\ORM\EntityManager($orm); $manager->persist($user); $manager->run(); ``` ### Removing Relations **Description:** To remove a relation, set the reference to `null`. **Example:** ```php $user = $orm->getRepository(User::class)->findByPK(1); $user->removeLastComment(); // Assuming removeLastComment method sets the relation to null $manager = new \Cycle\ORM\EntityManager($orm); $manager->persist($user); $manager->run(); ``` ``` -------------------------------- ### Complete Foreign Key Example with Multiple Actions in PHP Source: https://cycle-orm.dev/docs/database-declaration/current/en Provides a comprehensive example of defining foreign key constraints with various actions. It demonstrates how to implement `CASCADE` for automatic deletion/update, `SET NULL` for orphaned records, and `RESTRICT` to prevent changes when child records exist, using `ForeignKeyInterface` constants. ```php use CycleDatabaseForeignKeyInterface; // Posts are deleted when user is deleted $posts->integer('author_id')->nullable(false); $posts->foreign('author_id') ->references('users', 'id') ->onDelete(ForeignKeyInterface::CASCADE) ->onUpdate(ForeignKeyInterface::CASCADE); // Comments orphaned when post is deleted $comments->integer('post_id')->nullable(true); $comments->foreign('post_id') ->references('posts', 'id') ->onDelete(ForeignKeyInterface::SET_NULL) ->onUpdate(ForeignKeyInterface::CASCADE); // Orders cannot be deleted if they have items $orderItems->integer('order_id')->nullable(false); $orderItems->foreign('order_id') ->references('orders', 'id') ->onDelete(ForeignKeyInterface::RESTRICT) ->onUpdate(ForeignKeyInterface::CASCADE); ``` -------------------------------- ### Manually Configure ORM Schema in PHP Source: https://cycle-orm.dev/docs/intro-quick-start/1.x/en Demonstrates how to manually configure the ORM schema in PHP by providing an array of entity configurations to the ORM instance. This bypasses the need for automatic schema generation and annotation processing. ```php use Cycle\ORM\Schema; use Cycle\ORM\Mapper\Mapper; $orm = $orm->withSchema(new Schema([ 'user' => [ Schema::MAPPER => Mapper::class, // default POPO mapper Schema::ENTITY => User::class, Schema::DATABASE => 'default', Schema::TABLE => 'users', Schema::PRIMARY_KEY => 'id', Schema::COLUMNS => [ 'id' => 'id', // property => column 'name' => 'name' ], Schema::TYPECAST => [ 'id' => 'int' ], Schema::RELATIONS => [] ] ])); ``` -------------------------------- ### Example Rollback with Data Preservation (PHP) Source: https://cycle-orm.dev/docs/database-migrations/current/en Provides an example of implementing `up()` and `down()` methods for a migration that adds a column. The `down()` method demonstrates how to revert this change by dropping the column, emphasizing the importance of handling potential data loss. ```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(); } ``` -------------------------------- ### Install Cycle ORM Bootstrap Toolkit Source: https://cycle-orm.dev/docs/intro-cli/1.x/en Installs the Cycle ORM bootstrap toolkit using Composer. This command-line instruction assumes the user has Composer installed and is in the project's root directory. ```bash $ composer require cycle/bootstrap ``` -------------------------------- ### Install Cycle Migrations Generator Source: https://cycle-orm.dev/docs/advanced-sync-schema/current/en Installs the Cycle Migrations extension using Composer. This is the first step to enable automatic migration generation. ```php composer require cycle/schema-migrations-generator ``` -------------------------------- ### Get SelectQuery Builder Instance Source: https://cycle-orm.dev/docs/database-query-builders/current/en Demonstrates how to obtain a SelectQuery builder instance from either a database connection or a table instance. This is the starting point for constructing SELECT queries. ```php $select = $db->table('test')->select(); // alternative $select = $db->select()->from('test'); // alternative $select = $db->test->select(); ``` -------------------------------- ### Locate Entities using Symfony Finder and ClassLocator (PHP) Source: https://cycle-orm.dev/docs/intro-quick-start/1.x/en Illustrates how to use Symfony's Finder component to locate entity files within a directory and then create a ClassLocator instance from Spiral Framework. This is a prerequisite for the schema generation pipeline. ```php $finder = (new \Symfony\Component\Finder\Finder())->files()->in([__DIR__]); // __DIR__ here is folder with entities $classLocator = new \Spiral\Tokenizer\ClassLocator($finder); ``` -------------------------------- ### Install Cycle Database Component Source: https://cycle-orm.dev/docs/database-configuration/current/en Installs the cycle/database component using Composer. This is the primary method for adding the database functionality to your project, especially for alternative bundles or standalone usage. ```bash composer require cycle/database ``` -------------------------------- ### Active Record Entity Example (PHP) Source: https://cycle-orm.dev/docs/advanced-active-record/current/en Demonstrates how to implement an Active Record-like entity in PHP using Cycle ORM. This example shows finding a user, updating their name, and saving the changes. It assumes a User entity and a database connection are already set up. ```php $user = User::find()->findOne(['name' => 'John']) ?? new User(); $user->name = "new name"; $user->save(); ``` -------------------------------- ### Manually Create Database Instance (PHP) Source: https://cycle-orm.dev/docs/database-configuration/current/en Shows how to manually create a Database instance without relying on the DatabaseManager. This provides more control over the driver and connection configuration, including specifying separate read and write drivers. ```php use Cycle\Database\Driver; use Cycle\Database\Config; use Cycle\Database\Database; $writeDriver = Driver\SQLite\SQLiteDriver::create( new Config\MemoryConnectionConfig() ); $readDriver = Driver\SQLite\SQLiteDriver::create( new Config\TempFileConnectionConfig() ); $db = new Database( name: 'name', prefix: '', driver: $writeDriver, readDriver: $readDriver // read only driver (optional) ); print_r($db->getTables()); ``` -------------------------------- ### Compile ORM Schema with Schema Builder Pipeline (PHP) Source: https://cycle-orm.dev/docs/intro-quick-start/1.x/en Sets up and compiles the ORM schema using a pipeline of generators from 'cycle/schema-builder' and 'cycle/annotated'. This process registers entities, defines tables and relations, and synchronizes the schema with the database. ```php use Cycle\Schema; use Cycle\Annotated; use Doctrine\Common\Annotations\AnnotationRegistry; // autoload annotations AnnotationRegistry::registerLoader('class_exists'); $schema = (new Schema\Compiler())->compile(new Schema\Registry($dbal), [ new Schema\Generator\ResetTables(), // re-declared table schemas (remove columns) new Annotated\Embeddings($classLocator), // register embeddable entities new Annotated\Entities($classLocator), // register annotated entities new Annotated\MergeColumns(), // add @Table column declarations new Schema\Generator\GenerateRelations(), // generate entity relations new Schema\Generator\ValidateEntities(), // make sure all entity schemas are correct new Schema\Generator\RenderTables(), // declare table schemas new Schema\Generator\RenderRelations(), // declare relation keys and indexes new Annotated\MergeIndexes(), // add @Table column declarations new Schema\Generator\SyncTables(), // sync table changes to database new Schema\Generator\GenerateTypecast(), // typecast non string columns ]); ``` -------------------------------- ### Install Cycle ORM with Composer Source: https://cycle-orm.dev/docs/intro-install/current/en Installs the core Cycle ORM package into your project using Composer. This is the primary step for integrating the ORM. ```bash composer require cycle/orm ``` -------------------------------- ### Declare MySQL Databases Source: https://cycle-orm.dev/docs/database-configuration/current/en Shows how to declare multiple MySQL databases within the configuration, specifying drivers and table prefixes. It then demonstrates accessing these declared databases. ```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')); ``` -------------------------------- ### Inverse Relation Setup with 'inverse' Option (PHP) Source: https://cycle-orm.dev/docs/annotated-relations/1.x/en Example of setting up an inverse relation using the 'inverse' option within a Cycle ORM entity. This allows for automatic inverse relation creation. ```php /** @Entity */ class Post { // ... /** @BelongsTo(target = "User", inverse = @Inverse(as = "posts", type = "hasMany")) */ protected $user; } Image ``` -------------------------------- ### Enable SQL Profiling/Logging (PHP) Source: https://cycle-orm.dev/docs/basic-connect/1.x/en Illustrates how to enable SQL profiling and logging for a database driver. It involves getting the driver instance from a database connection and setting a logger that implements `PsrLogLoggerAwareInterface`. ```php $driver = $dbal->database('default')->getDriver(); $driver->setLogger($myLogger); ``` -------------------------------- ### Review Schema Changes Before Production (PHP) Source: https://cycle-orm.dev/docs/database-declaration/current/en Before applying schema changes to a production environment, thoroughly review them to identify potential issues like dropped columns. This example demonstrates how to use a schema comparator to check for dropped columns and prompt for confirmation. ```php // ✅ GOOD: Check before saving $comparator = $schema->getComparator(); if ($comparator->droppedColumns()) { // Confirm you want to drop these columns foreach ($comparator->droppedColumns() as $col) { echo "WARNING: Will drop " . $col->getName() . "\n"; } } $schema->save(); ``` -------------------------------- ### Configure Database Aliases Source: https://cycle-orm.dev/docs/database-configuration/current/en Illustrates how to set up database aliases to access different physical databases using simpler names within the application. This enhances flexibility in database access. ```php use Cycle\Database\Driver; $dbal = new DatabaseManager(new DatabaseConfig([ 'aliases' => [ 'db' => 'primary', 'other' => 'secondary' ], 'databases' => [ // ... ], 'connections' => [ // ... ], ])); print_r($dbal->database('db')); print_r($dbal->database('other')); ``` -------------------------------- ### Testing Cycle ORM Locally Source: https://cycle-orm.dev/docs/contributing/1.x/en Instructions for setting up and running tests for the Cycle ORM engine locally. This involves downloading the repository, starting Docker containers, and executing the test suite using PHPUnit. ```bash cd tests/ docker-composer up ``` ```bash ./vendor/bin/phpunit ``` ```bash ./vendor/bin/phpunit tests/ORM/Driver/SQLite ``` -------------------------------- ### Accessing Databases with Cycle ORM Source: https://cycle-orm.dev/docs/database-access/current/en Demonstrates how to instantiate and access different databases configured within Cycle ORM. It shows how to get the default database connection and connections using specific aliases. ```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(...)); // Assuming DatabaseConfig is properly set up // Default database print_r($dbal->database()); // Using alias 'default' which points to the primary database print_r($dbal->database('default')); // Secondary database print_r($dbal->database('secondary')); ``` -------------------------------- ### Column Type Examples - PHP Source: https://cycle-orm.dev/docs/database-migrations/current/en Demonstrates the usage of `addColumn()` for various data types including strings, numerics, dates/times, binary, JSON, booleans, and enums. Each example shows how to specify the column type and relevant options. ```php // String types ->addColumn('username', 'string', ['length' => 64]) ->addColumn('bio', 'text') // Numeric types ->addColumn('age', 'integer') ->addColumn('price', 'decimal', ['precision' => 10, 'scale' => 2]) ->addColumn('rating', 'float') // Date/Time types ->addColumn('created_at', 'datetime') ->addColumn('published_date', 'date') ->addColumn('start_time', 'time') ->addColumn('updated_at', 'timestamp') // Binary and JSON ->addColumn('avatar', 'binary') ->addColumn('metadata', 'json') // Boolean ->addColumn('is_active', 'boolean', ['default' => true]) // Enum ->addColumn('status', 'enum', ['values' => ['pending', 'active', 'inactive']]) ``` -------------------------------- ### Full Cycle ORM Example with SQLite in PHP Source: https://cycle-orm.dev/docs/advanced-dynamic-schema/1.x/en A comprehensive PHP script illustrating the setup and usage of Cycle ORM with an SQLite database. It includes database configuration, schema definition, ORM initialization, entity creation, transaction persistence, and repository querying. ```php 'default', 'databases' => [ 'default' => [ 'connection' => 'sqlite', ], ], 'connections' => [ 'sqlite' => [ 'driver' => SQLiteDriver::class, 'connection' => 'sqlite:database.db', 'username' => '', 'password' => '', ], ], ])); // automatically migrate database schema if needed (optional) $users = $dbm->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($dbm), 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 => [], ], ])); $u = $orm->make('user', [ 'name' => 'test', 'created_at' => new DateTimeImmutable(), 'updated_at' => new DateTimeImmutable(), ]); (new Transaction($orm))->persist($u)->run(); print_r( $orm->getRepository('user') ->findAll() ); ``` -------------------------------- ### Initialize Entity Manager in PHP Source: https://cycle-orm.dev/docs/intro-install/current/en Shows how to instantiate the `EntityManager` in PHP, which is the primary tool for interacting with entities in Cycle ORM. It requires an already configured ORM instance. ```php use Cycle\ORM\EntityManager; $orm = /** ... */; $em = new EntityManager($orm); ``` -------------------------------- ### Persist Entity using Cycle ORM Transaction Source: https://cycle-orm.dev/docs/intro-quick-start/1.x/en Shows how to create a new entity instance, set its properties, and persist it to the database using Cycle ORM's Transaction component. This assumes the ORM has already been configured. ```php use Cycle\ORM\Transaction; $user = new User(); $user->setName("John"); (new Transaction($orm))->persist($user)->run(); ``` -------------------------------- ### Abstract Type Mapping Example - PHP Source: https://cycle-orm.dev/docs/database-declaration/current/en Shows how Cycle DBAL's abstract data types are mapped to database-specific column types. This example demonstrates the `string` type and its representation in MySQL, PostgreSQL, and SQLite, highlighting cross-database compatibility. ```php // This declaration: $schema->string('username', 64); // Generates in MySQL: // `username` VARCHAR(64) NULL // Generates in PostgreSQL: // "username" CHARACTER VARYING(64) NULL // Generates in SQLite: // "username" TEXT NULL ``` -------------------------------- ### Configure Database Connection with Cycle ORM Source: https://cycle-orm.dev/docs/intro-install/current/en Sets up a default SQLite database connection using Cycle ORM's DatabaseManager. It requires the 'cycle/database' package and defines connection details within a DatabaseConfig object. The example demonstrates an in-memory SQLite connection. ```php 'default', 'databases' => [ 'default' => ['connection' => 'sqlite'] ], 'connections' => [ 'sqlite' => new Config\SQLiteDriverConfig( connection: new Config\SQLite\MemoryConnectionConfig(), queryCache: true, ), ] ]) ); ``` -------------------------------- ### Install cycle/entity-behavior Package Source: https://cycle-orm.dev/docs/entity-behaviors-install/current/en This command installs the cycle/entity-behavior package using Composer. This package provides attributes to add behaviors to Cycle ORM entities and allows for the creation of custom behavior attributes. ```bash composer require cycle/entity-behavior ``` -------------------------------- ### Install Cycle ORM with Annotated Entities Support Source: https://cycle-orm.dev/docs/basic-install/1.x/en Installs Cycle ORM along with the necessary package for supporting annotated entities. This command also fetches dependencies like spiral/database and doctrine/collections. ```bash $ composer require cycle/annotated ``` -------------------------------- ### Cycle ORM LogRunner Implementation Example (PHP) Source: https://cycle-orm.dev/docs/advanced-transaction/1.x/en An example implementation of the `RunnerInterface` that logs the order of executed commands before passing them to the original runner. This demonstrates how to wrap and extend existing transaction runner functionality. ```php runner = new \Cycle\ORM\Transaction\Runner(); } public function run(CommandInterface $command) { print_r($command); $this->runner->run($command); } public function complete() { $this->runner->complete(); } public function rollback() { $this->runner->rollback(); } } ``` -------------------------------- ### PHP: ORM Setup with Manual Schema and HasOne Relation Source: https://cycle-orm.dev/docs/basic-no-annotations/current/en Demonstrates setting up Cycle ORM with a manually defined schema for User and Profile entities, establishing a HasOne relationship between them. This example bypasses attribute usage and configures the database connection and ORM instance. ```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', Schema::RELATION => [ 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()); ``` -------------------------------- ### Install cycle/orm-promise-mapper Package Source: https://cycle-orm.dev/docs/mapper-promise-mapper/current/en Installs the cycle/orm-promise-mapper package using Composer. This is the primary method for adding the Promise Mapper functionality to your Cycle ORM project. ```bash composer require cycle/orm-promise-mapper ``` -------------------------------- ### Cycle ORM Event Listener Class Implementation in PHP Source: https://cycle-orm.dev/docs/entity-behaviors-event-listener/current/en Provides an example of a Cycle ORM event listener class, CommentListener. It shows how to use the Listen attribute to subscribe methods to specific entity events like OnCreate, OnUpdate, and OnDelete. The example illustrates dependency injection for services like spam filters and repositories, and demonstrates event handling logic. ```php use Cycle\ORM\Entity\Behavior\Attribute\Listen; use Cycle\ORM\Entity\Behavior\Event\Mapper\Command; use Cycle\ORM\EntityManagerInterface; final class CommentListener { public function __construct( private CommentSpamFilter $spamFilter, private CommentRepository $commentRepository, private EntityManagerInterface $em ) { } #[Listen(Command\OnCreate::class)] #[Listen(Command\OnUpdate::class)] public function filterSpam(Command\OnCreate|Command\OnUpdate $event): void { $event->state->register( 'body', $this->spamFilter->filter( $event->state->getData()['body'] ) ); } #[Listen(Command\OnDelete::class)] public function deleteChildComments(Command\OnDelete $event): void { // Please don't use this example in production. // This example contains recursion with too low performance. $comments = $this->commentRepository->findAll([ 'parent_id' => $event->entity->id ]); foreach ($comments as $comment) { $this->em->delete($comment); } // Will fire 'Command\OnDelete' for each child comment $this->em->run(); } } ``` -------------------------------- ### Install Cycle ORM Active Record using Composer Source: https://cycle-orm.dev/docs/active-record-installation/current/en This snippet shows the Composer command to install the Cycle ORM Active Record package. It's the primary method for adding the package to your PHP project. ```bash composer require cycle/active-record ``` -------------------------------- ### Get and Check Table Schema Instance - PHP Source: https://cycle-orm.dev/docs/database-declaration/current/en Demonstrates how to obtain an AbstractTable instance for a given table name from a Cycle ORM Database connection and check if the table currently exists in the database. This is the first step in schema management. ```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"; } ``` -------------------------------- ### Using the UserRepository (PHP) Source: https://cycle-orm.dev/docs/active-record-active-repository/current/en Demonstrates how to instantiate and use the UserRepository to fetch a single user by email or retrieve a collection of active users with their posts. This showcases the practical application of the defined repository methods. ```php $repository = new UserRepository(); $user = $repository->getByEmail($email); $activeUsers = $repository ->whereActive() ->withPosts() ->findAll(); ``` -------------------------------- ### Persist Entity in Database - PHP Source: https://cycle-orm.dev/docs/intro-quick-start/1.x/en Initializes and persists a new entity to the database. The entity must be registered within a transaction before its changes are applied. ```php $u = new \Example\User(); $u->setName("Hello World"); $t = new \Cycle\ORM\Transaction($orm); $t->persist($u); $t->run(); print_r($u); ``` -------------------------------- ### Pagination for Large Collections Source: https://cycle-orm.dev/docs/relation-has-many/current/en Shows how to implement pagination for HasMany relationships when dealing with large collections. This example retrieves a specific subset of posts for a user, ordered by creation date, using `limit()` and `offset()`. ```php $user = $orm->getRepository(User::class)->findByPK(1); $posts = $orm->getRepository(Post::class) ->select() ->where('user_id', $user->getId()) ->orderBy('created_at', 'DESC') ->limit(20) ->offset(0) ->fetchAll(); ``` -------------------------------- ### Delete Entity from Database - PHP Source: https://cycle-orm.dev/docs/intro-quick-start/1.x/en Deletes an entity from the database by calling the `delete` method on the transaction object. This operation requires the entity to be previously fetched or identified. ```php (new \Cycle\ORM\Transaction($orm))->delete($u)->run(); ``` -------------------------------- ### Access Database Tables via DatabaseManager Source: https://cycle-orm.dev/docs/intro-quick-start/1.x/en Checks if the database connection is accessible by attempting to retrieve the list of tables. This is a simple way to verify the database configuration. ```php print_r($dbal->database('default')->getTables()); ``` -------------------------------- ### Consider Migration Systems (PHP) Source: https://cycle-orm.dev/docs/database-declaration/current/en For production applications, it is highly recommended to use a dedicated migration system instead of direct schema saves. Migrations provide version control for your database schema, allowing for controlled, repeatable, and reversible changes. ```php // ✅ GOOD: Generate migrations for review // See the Migrations documentation for details // ❌ AVOID: Direct schema saves in production // $schema->save(); // Skip in production, use migrations ``` -------------------------------- ### BelongsTo Key Behavior and Examples Source: https://cycle-orm.dev/docs/relation-belongs-to/current/en Illustrates how Cycle ORM generates foreign keys for BelongsTo relations by default and how to customize them, along with examples of creating relations, handling nullable relations, and using composite keys. ```APIDOC ## Key Behavior and Usage Examples ### Description This section explains the default foreign key generation for `#[BelongsTo]` relations and provides practical examples for creating relations, managing nullability, and implementing composite keys. ### Method N/A (Configuration and Usage) ### Endpoint N/A ### Parameters N/A ### Request Example ```php #[Entity] class Post { // Creates column: author_id (references user.id) #[BelongsTo(target: User::class)] private User $author; } ``` ```php #[Entity] class Post { // Uses existing column: user_id #[BelongsTo(target: User::class, innerKey: 'user_id')] private User $author; } ``` ### Response N/A #### Success Response (200) N/A #### Response Example ```php // Creating a relation $user = new User("John Doe"); $post = new Post("My First Post", $user); $manager = new \Cycle\ORM\EntityManager($orm); $manager->persist($post); $manager->run(); // Parent (User) is saved first, then child (Post) with foreign key ``` ```php // Nullable relation #[Entity] class Post { #[BelongsTo(target: User::class, nullable: true)] private ?User $author = null; public function removeAuthor(): void { $this->author = null; } } // Usage: $post = $orm->getRepository(Post::class)->findByPK(1); $post->removeAuthor(); $manager = new \Cycle\ORM\EntityManager($orm); $manager->persist($post); $manager->run(); // Sets author_id to NULL ``` ```php // Composite Keys #[Entity] class OrderItem { #[BelongsTo( target: Order::class, innerKey: ['order_id', 'order_date'], outerKey: ['id', 'created_date'] )] private Order $order; } ``` ``` -------------------------------- ### Sync Tables Across Multiple Databases with Reflector (PHP) Source: https://cycle-orm.dev/docs/database-declaration/current/en This example demonstrates how to use Cycle ORM's Reflector to synchronize schema changes across tables residing in different databases. It shows how to obtain database instances, add schemas from each database to the Reflector, and then run the reflector. The Reflector handles transactional execution across multiple databases, ensuring consistency. Dependencies include the database manager and the Reflector class. ```php $dbPrimary = $dbal->database('primary'); $dbSecondary = $dbal->database('secondary'); $reflector = new Reflector(); // Add tables from different databases $reflector->addTable($dbPrimary->table('users')->getSchema()); $reflector->addTable($dbPrimary->table('posts')->getSchema()); $reflector->addTable($dbSecondary->table('logs')->getSchema()); // Reflector handles multiple database transactions $reflector->run(); ``` -------------------------------- ### Find Entities with Nullable Column - PHP Source: https://cycle-orm.dev/docs/intro-quick-start/1.x/en Finds all entities where a specific nullable column has no value assigned. This is useful after schema modifications to identify records needing updates. ```php $users = $orm->getRepository(\Example\User::class)->findAll(['age' => null]); print_r($users); ``` -------------------------------- ### Update Entity in Database - PHP Source: https://cycle-orm.dev/docs/intro-quick-start/1.x/en Updates an existing entity's data by modifying its properties and then persisting the changes within a transaction. The changes are reflected on each script iteration. ```php $u = $orm->getRepository(\Example\User::class)->findByPK(1); $u->setName("New " . mt_rand(0, 1000)); (new \Cycle\ORM\Transaction($orm))->persist($u)->run(); ``` -------------------------------- ### Configure MySQL/MariaDB Database Connections in PHP Source: https://cycle-orm.dev/docs/database-connect/current/en Provides examples for configuring MySQL and MariaDB connections using TCP, DSN, and socket methods. It shows how to set up `ConfigMySQLDriverConfig` with relevant connection parameters. ```php 'mysql' => new Config\MySQLDriverConfig( connection: new Config\MySQL\TcpConnectionConfig( database: 'spiral', host: '127.0.0.1', port: 3306, user:'spiral', password: '', ), queryCache: true ), 'mysql_dsn' => new Config\MySQLDriverConfig( connection: new Config\MySQL\DsnConnectionConfig( dsn: 'mysql:host=127.0.0.1;port=3306;dbname=spiral', user:'spiral', password: '', ), queryCache: true ), 'mysql_socket' => new Config\MySQLDriverConfig( connection: new Config\MySQL\SocketConnectionConfig( database: 'spiral', socket: '/tmp/mysql.sock', dsn: 'mysql:host=127.0.0.1;port=3306;dbname=spiral', user: 'spiral', password: '', ), queryCache: true ), ``` -------------------------------- ### Select Entity by Primary Key - PHP Source: https://cycle-orm.dev/docs/intro-quick-start/1.x/en Retrieves an entity from the database using its primary key and the associated repository. Ensure code is not removed to avoid fetching from memory. ```php $u = $orm->getRepository(\Example\User::class)->findByPK(1); ``` -------------------------------- ### Pagination with Limit and Offset in Cycle ORM Source: https://cycle-orm.dev/docs/database-query-builders/current/en Demonstrates how to implement pagination in Cycle ORM queries using the `limit` and `offset` methods. Includes an example of iterating through paginated results. ```php $select = $db->table('test') ->select(['id', 'name', 'status']) ->limit(10) ->offset(1); foreach ($select as $row) { print_r($row); } ``` -------------------------------- ### Get Tables in Dependency Order with Reflector (PHP) Source: https://cycle-orm.dev/docs/database-declaration/current/en This PHP snippet shows how to retrieve tables in their dependency order using Cycle ORM's Reflector. After adding tables to the reflector, you can call `sortedTables()` to get an array of schema objects ordered according to their foreign key relationships. This is useful for custom processing or logging the order in which tables will be created or modified. It requires the Reflector class and schema objects. ```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"; } ``` -------------------------------- ### Chain Custom Commands with Context Forwarding Source: https://cycle-orm.dev/docs/advanced-custom-mapper/1.x/en This example shows how to link custom commands to be executed sequentially after a primary command, particularly useful for complex operations. It utilizes `ContextSequence` to manage the command chain. For `queueCreate`, it demonstrates forwarding the insert ID from the primary command to a custom command using `forward` and `waitContext` to handle cases where the primary key is not immediately available. ```php use Cycle\ORM\Command; use Cycle\ORM\Heap; public function queueCreate($entity, Heap\Node $node, Heap\State $state): Command\ContextCarrierInterface { $cmd = parent::queueCreate($entity, $node, $state); $cs = new Command\Branch\ContextSequence(); $cs->addPrimary($cmd); $cs->addCommand(new OurCommand()); return $cs; } ``` ```php use Cycle\ORM\Command; use Cycle\ORM\Heap; use Cycle\ORM\Command\Database\Insert; public function queueCreate($entity, Heap\Node $node, Heap\State $state): Command\ContextCarrierInterface { $cmd = parent::queueCreate($entity, $node, $state); $our = new OurCommand(); // wait for cmd_id value or fail $our->waitContext('cmd_id', true); // send lastID value as cmd_id to $our command $cmd->forward(Insert::INSERT_ID, $our, 'cmd_id'); $cs = new Command\Branch\ContextSequence(); $cs->addPrimary($cmd); $cs->addCommand($our); return $cs; } ``` -------------------------------- ### Register Entity Namespace in Composer Source: https://cycle-orm.dev/docs/intro-quick-start/1.x/en Configures the Composer autoloader to recognize a new namespace (e.g., 'Example\') and map it to a directory (e.g., 'src/'). This is necessary for PSR-4 autoloading of your entities. ```json { "autoload": { "psr-4": { "Example\": "src/" } } } ``` -------------------------------- ### Create Personalized Entity-Specific Query Class (PHP) Source: https://cycle-orm.dev/docs/active-record-active-query/current/en This example shows how to create a `UserQuery` class that extends a common query class (`CommonQuery`) and adds entity-specific methods like `emailVerified` and `subscribtionLevel`. ```php /** * @extends CommonQuery */ class UserQuery extends CommonQuery { public function __construct() { parent::__construct(User::class); } public function emailVerified(bool $state = true): static { return $this->where(['email_verified' => $state]); } public function subscribtionLevel(Subsctiption $level): static { return $this->where('subscriptionLevel', '>=' , $level->alue); } } ``` -------------------------------- ### Database-Specific Considerations for Foreign Keys in PHP Source: https://cycle-orm.dev/docs/database-declaration/current/en This example highlights database-specific limitations, such as SQL Server's restrictions on circular CASCADE actions for foreign keys. It serves as a reminder to plan schema designs considering these constraints. ```php // Some databases (SQL Server) restrict CASCADE actions // to avoid circular references. Plan your schema accordingly. // Example: Cannot have mutual CASCADE relationships // Table A -> CASCADE -> Table B // Table B -> CASCADE -> Table A // May be rejected ``` -------------------------------- ### Declare SQLite Database Connection Source: https://cycle-orm.dev/docs/database-configuration/current/en Demonstrates how to declare a new database connection using SQLite. It configures the connection details, including the database file path, and enables query caching. ```php [ 'default' => [ 'driver' => 'runtime' ], ], 'connections' => [ 'runtime' => new Config\SQLiteDriverConfig( connection: new Config\SQLite\FileConnectionConfig( database: __DIR__.'./runtime/database.sqlite' ), queryCache: true, ), ], ])); ``` -------------------------------- ### Accessing Cycle ORM Query Builder Source: https://cycle-orm.dev/docs/query-builder-basic/1.x/en Demonstrates how to obtain an instance of the query builder. This can be done by directly instantiating the `Select` object or by using the `select()` method from a repository. The recommended approach involves defining select statements within an entity's repository for better organization. ```php use Cycle\ORM\Select; // Accessing directly from repository $select = $orm->getRepository(User::class)->select(); // Recommended: Declaring within a repository class UserRepository extends Select\Repository { public function findActive(): Select { return $this->select()->where('status', 'active'); } } ``` -------------------------------- ### Persist Related Entities with Cascade (PHP) Source: https://cycle-orm.dev/docs/basic-crud/current/en Demonstrates how to persist a user entity with a related address entity. By default, related entities are persisted automatically. This example shows the initial setup and the result of persisting. ```php $user = new User(); $user->setAddress(new Address()); $user->getAddress()->setCountry("USA"); $manager = new \Cycle\ORM\EntityManager($orm); $manager->persist($user); $manager->run(); print_r($user->getAddress()->getID()); ``` -------------------------------- ### Apply Compiled Schema to ORM Instance (PHP) Source: https://cycle-orm.dev/docs/intro-quick-start/1.x/en Applies the compiled schema generated by the schema builder pipeline to the ORM instance. This makes the ORM aware of the entity configurations and relationships defined in the schema. ```php $orm = $orm->withSchema(new \Cycle\ORM\Schema($schema)); ``` -------------------------------- ### Fluent Insert Syntax - PHP Source: https://cycle-orm.dev/docs/query-builder-extended/1.x/en Provides an example of using fluent syntax for inserting data, chaining methods for a more concise code structure. ```php $database->insert('table')->values(...)->run(); ``` -------------------------------- ### Configure Schema Compiler Pipeline with New Generators Source: https://cycle-orm.dev/docs/intro-upgrade/current/en To leverage new features in `cycle/schema-builder` v2.0, such as STI/JTI and schema modifiers, add the corresponding generators to the schema compiler pipeline. This example shows the recommended order for generators. ```php [ new Schema\Generator\ResetTables(), new Annotated\Embeddings($classLocator), new Annotated\Entities($classLocator), new Annotated\TableInheritance(), // <------ register STI/JTI new Annotated\MergeColumns(), new Schema\Generator\GenerateRelations(), new Schema\Generator\GenerateModifiers(), // <----- generate changes from schema modifiers new Schema\Generator\ValidateEntities(), new Schema\Generator\RenderTables(), new Schema\Generator\RenderRelations() new Schema\Generator\RenderModifiers(), // <----- render all schema modifiers new Schema\Generator\ForeignKeys(), // Since cycle/schema-builder v2.6.0. Define foreign key constraints new Annotated\MergeIndexes(), new Schema\Generator\SyncTables(), // Not for production new Schema\Generator\GenerateTypecast(), ] ``` -------------------------------- ### Implement LogRunner for EntityManager Commands in PHP Source: https://cycle-orm.dev/docs/advanced-entity-manager/current/en Provides an example implementation of a `LogRunner` that wraps the default `Cycle\ORM\Transaction\Runner`. This custom runner logs the order of executed commands before passing them to the original runner. ```php use Cycle\ORM\Command\CommandInterface; class LogRunner implements RunnerInterface { private RunnerInterface $runner; public function __construct( private LoggerInterface $logger ) { $this->runner = new \Cycle\ORM\Transaction\Runner(); } public function run(CommandInterface $command): void { $this->logger->debug($command); $this->runner->run($command); } public function complete(): void { $this->runner->complete(); } public function rollback(): void { $this->runner->rollback(); } } ``` -------------------------------- ### Initialize ClassLocator for Entity Discovery (PHP) Source: https://cycle-orm.dev/docs/intro-install/current/en Initializes the SpiralTokenizerClassLocator to automatically discover and index entities within a specified directory. This is a prerequisite for schema compilation. It uses Symfony Finder to locate files. ```php //... $finder = (new \Symfony\Component\Finder\Finder())->files()->in([__DIR__]); // __DIR__ here is folder with entities $classLocator = new \Spiral\Tokenizer\ClassLocator($finder); ``` -------------------------------- ### Handling All Entity Events with QueueCommand (PHP) Source: https://cycle-orm.dev/docs/entity-behaviors-events/current/en Demonstrates how to use the #[Listen(QueueCommand::class)] attribute to create a single handler for all entity lifecycle events (OnCreate, OnUpdate, OnDelete) using type checking. ```php id; } public function getName(): string { return $this->name; } public function setName(string $name): void { $this->name = $name; } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.