klobanov / webman-cycle-orm
Cycle ORM integration for webman: coroutine-safe Database/ORM, versioned migrations (cycle/migrations) and an extensible SOLID architecture
Requires
- php: >=8.4
- cycle/annotated: ^4.7
- cycle/database: ^2.24
- cycle/entity-behavior: ^1.8
- cycle/migrations: ^4.4
- cycle/orm: ^2.19
- cycle/schema-builder: ^2.13
- cycle/schema-migrations-generator: ^2.4
- cycle/schema-renderer: ^1.5
- psr/container: ^2.0
- psr/log: ^2.0 || ^3.0
- workerman/webman-framework: ^2.2
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.95
- overtrue/phplint: ^9.8
- phpstan/phpstan: ^2.3
- phpunit/phpunit: ^13.4
- symfony/console: ^8.0
Suggests
- ext-pdo_mysql: MySQL support
- ext-pdo_pgsql: PostgreSQL support
- ext-pdo_sqlite: SQLite support
- webman/console: Required to run the bundled cycle:* console commands
Provides
None
Conflicts
None
Replaces
None
README
Coroutine-safe Cycle ORM 2.x integration for webman — the ultra-fast Workerman-based PHP framework. Data-mapper and unit-of-work patterns, pluggable connection strategies, versioned migrations and a fully lazy, SOLID architecture.
The package has been ported and fully refactored for the Webman framework from hyperf-cycle.
Requirements:
- PHP >= 8.4
- Cycle ORM 2.x, Cycle Database 2.x
- Fully coroutine-safe: works with Workerman Fibers, Swoole and Swow runtimes (webman coroutine context isolation)
- Drivers: MySQL, PostgreSQL, SQLite, SQL Server (anything
cycle/databasesupports)
Features
- Coroutine-safe DatabaseManager — one
Databaseinstance per request/coroutine, the lease is released automatically when the request context ends. No connection leaks, no cross-request transactions. - Three pluggable connection strategies —
per-context,pooled(Workerman coroutine pool with heartbeat and idle timeouts),process-shared. Selected by a single config key. - Isolated ORM heaps — every request/coroutine receives an ORM clone with a fresh
Heap, so entity identity maps never leak between requests. - Two schema modes — annotated (PHP 8 attributes via
cycle/annotated) or plain array schema, with an optional on-disk schema cache for production deploys. - Versioned migrations — the full
cycle/migrationsworkflow: init, migrate, rollback, replay, status, generate (schema diff). - Schema tooling — sync the database with the ORM schema (
cycle:sync), compile the schema cache (cycle:schema:dump), render the schema as ER-diagrams (cycle:render). - Console commands for database introspection (
cycle:db:list,cycle:db:table). - Entity behaviors —
#[CreatedAt],#[UpdatedAt], etc. viacycle/entity-behavior. - Lazy by design — schema, ORM graph and migration objects are built on first use; worker boot never touches the database.
Installation
composer require klobanov/webman-cycle-orm
During composer install the plugin config is copied into your webman application
(config/plugin/klobanov/cycle-orm/ — app.php, bootstrap.php, command.php, config.php).
The plugin is enabled by default; Bootstrap builds the kernel per worker on start.
Console commands (
cycle:*) require the suggestedwebman/consolepackage in the host app.
Architecture
The package follows SOLID strictly. All cross-module dependencies go through the
contracts in src/Contract/, and KernelBuilder is the single composition root — it is
the only place that knows how the pieces fit together.
config (plugin config.php)
│
▼
KernelBuilder ── composition root, builds everything from SettingsInterface
│
├── ConnectionSourceInterface per-context | pooled | process-shared (strategy)
├── DatabaseManager context-scoped leases, auto-release on context destroy
├── SchemaFactoryInterface annotated | array (+ CachedSchemaFactory decorator)
├── OrmFactory lazy schema/ORM graph, fresh Heap per context
└── MigrationManager native cycle/migrations stack
│
▼
Kernel (immutable readonly handle, registered as a singleton in the webman container)
Key design points:
- Dependency inversion — application code should depend on the
Contract/interfaces (ConnectionSourceInterface,OrmFactoryInterface,DatabaseProviderInterface, …), not on concrete implementations. - Strategy pattern — connection policy and schema source are chosen by config
(
connection_source,orm.mode), never by code changes. - Context store — the request/coroutine state lives in
Support\WebmanContextStore, backed by webman'ssupport\Context(per-fiber isolation plusonDestroycallbacks). That is what makes the same code safe under Fibers, Swoole and Swow. - Lazy initialization — nothing connects to the database until it is actually used.
Configuration
The plugin config is published to config/plugin/klobanov/cycle-orm/config.php. All values
can be driven by DB_* environment variables.
<?php declare(strict_types=1); use Cycle\Database\Config\SQLite\FileConnectionConfig; use KLobanov\CycleOrm\Config\MySQLDriverConfig; use KLobanov\CycleOrm\Config\SQLiteDriverConfig; $env = static fn (string $key, mixed $default = null): mixed => getenv($key) !== false ? getenv($key) : $default; return [ // Connection strategy: per-context | pooled | process-shared (see the table below). 'connection_source' => $env('DB_CONNECTION_SOURCE', 'pooled'), // Pool options for the `pooled` source (can be overridden per connection). 'pool' => [ 'min_connections' => (int) $env('DB_MIN_CONNECTIONS', 1), 'max_connections' => (int) $env('DB_MAX_CONNECTIONS', 10), 'wait_timeout' => (float) $env('DB_WAIT_TIMEOUT', 3.0), 'idle_timeout' => (float) $env('DB_IDLE_TIMEOUT', 60.0), 'heartbeat_interval' => (float) $env('DB_HEARTBEAT_INTERVAL', 50.0), ], // Cycle DatabaseProvider configuration (native Cycle format). 'database' => [ 'default' => 'default', 'aliases' => [], 'databases' => [ 'default' => ['connection' => $env('DB_CONNECTION', 'sqlite')], ], 'connections' => [ 'sqlite' => new SQLiteDriverConfig( connection: new FileConnectionConfig(runtime_path('cycle-orm/database.sqlite')), queryCache: true, ), // 'mysql' => new MySQLDriverConfig( // connection: new \Cycle\Database\Config\MySQL\TcpConnectionConfig( // database: $env('DB_MYSQL_DATABASE', 'webman'), // host: $env('DB_MYSQL_HOST', '127.0.0.1'), // port: (int) $env('DB_MYSQL_PORT', 3306), // charset: $env('DB_MYSQL_CHARSET', 'utf8mb4'), // user: $env('DB_MYSQL_USER', 'root'), // password: $env('DB_MYSQL_PASSWORD', ''), // ), // reconnect: true, // queryCache: true, // poolOptions: ['max_connections' => 20], // per-connection pool override // ), ], ], // ORM configuration. 'orm' => [ // 'annotated' — scan `entities` directories for PHP attributes // 'array' — use the plain `schema` array below 'mode' => 'annotated', // Directories scanned for entities/embeddings (annotated mode). 'entities' => [ app_path('model'), ], 'exclude_entities' => [], // Plain Cycle schema (array mode). 'schema' => [], // Default schema fragments applied to every entity. 'default_schema_classes' => [], // Enable cycle/entity-behavior listeners (#[CreatedAt], #[UpdatedAt], …). 'behaviors' => true, // Compile the schema once at deploy time (`php webman cycle:schema:dump`). // Set to null to disable caching and always compile at worker start. 'schema_cache' => runtime_path('cycle-orm/schema.php'), ], // Versioned migrations (cycle/migrations). 'migrations' => [ // Where migration files are stored and generated. MUST be set. 'directory' => base_path('database/cycle-orm/migrations'), // Table tracking executed migrations. 'table' => 'cycle_orm_migrations', // Namespace of generated migration classes. 'namespace' => 'Database\CycleOrm\Migrations', // true -> run migrations without confirmation prompts. 'safe' => false, // Extra read-only migration directories (e.g. from vendor packages). 'vendor_directories' => [], ], // SQL query logging through webman's `support\Log`. 'logger' => [ 'enabled' => (bool) $env('DB_QUERY_LOG', false), 'channel' => 'default', 'level' => 'debug', ], ];
Connection strategies
The way a worker obtains database connections is controlled by the connection_source key.
The manager itself never holds connection state — connections are always acquired at call
time and released exactly once when the request/coroutine context ends.
| Mode | What it does | Use it when |
|---|---|---|
per-context |
A brand-new connection is opened for every request/coroutine and closed (released) when the request ends. The safest option: zero chance of state leaking between requests. | Development, debugging, low-traffic applications, or when you want guaranteed request isolation at the cost of connect/disconnect overhead. |
pooled |
Connections are reused from a per-database coroutine pool (Workerman Coroutine\Pool) with min/max size, wait_timeout, idle_timeout and heartbeat_interval (dead connections are detected and reconnected automatically). Recommended for production. |
Production under coroutines (Fibers / Swoole / Swow): high concurrency with bounded connection counts to MySQL/PostgreSQL. |
process-shared |
One connection per process, shared by all requests handled by that worker. The fastest mode (no acquire/release at all), but absolutely not safe with concurrent coroutines on the same process. | Only in classic blocking mode (no coroutines), or when the whole worker is effectively single-flow and you fully control concurrency. Never use together with coroutine drivers. |
The pool size can be tuned globally via the
poolsection and overridden per connection throughpoolOptionson the driver config (see the MySQL example above).
Runtime compatibility
The package relies on webman's support\Context for per-context isolation and on the
Workerman coroutine pool. It works out of the box with:
| Runtime | Notes |
|---|---|
| Workerman Fiber (default webman coroutine) | Full support: per-fiber Database/ORM instances, pooled connections, auto-release on context destroy. |
| Swoole | Supported through webman's Swoole integration (support\Context isolates each request/coroutine). |
| Swow | Supported through webman's Swow integration, same guarantees. |
Usage
Defining entities (annotated mode)
<?php declare(strict_types=1); namespace app\model; use Cycle\Annotated\Annotation\Column; use Cycle\Annotated\Annotation\Entity; #[Entity(table: 'users')] class User { #[Column(type: 'primary')] public int $id; #[Column(type: 'string')] public string $name; }
Recommended: constructor injection
Inject OrmFactoryInterface (or DatabaseProviderInterface) into your services.
The factory itself is safe to keep as a service property — it holds no connection state;
the ORM/database handles are resolved per request at call time.
<?php declare(strict_types=1); namespace app\service; use app\model\User; use KLobanov\CycleOrm\Contract\OrmFactoryInterface; final class UserService { public function __construct( private readonly OrmFactoryInterface $ormFactory, ) {} public function create(string $name): User { $user = new User(); $user->name = $name; $this->ormFactory->entityManager()->persist($user)->run(); return $user; } public function find(int $id): ?User { return $this->ormFactory->orm()->getRepository(User::class)->findByPK($id); } }
Quick access: the Cycle facade
For prototyping, views and legacy code there is a webman-style static locator
(akin to Db/Redis helpers):
use KLobanov\CycleOrm\Cycle; $orm = Cycle::orm(); // request-isolated ORM instance $em = Cycle::em(); // request-isolated EntityManager $db = Cycle::database(); // request-scoped database handle $db = Cycle::database('reporting'); // named database
Raw database queries
use KLobanov\CycleOrm\Cycle; $users = Cycle::database()->query('SELECT * FROM users WHERE active = ?', [1])->fetchAll();
Transactions
Prefer the native transaction() helper — it guarantees the commit/rollback pair even
when the callback throws, so a transaction can never be left dangling:
use KLobanov\CycleOrm\Cycle; Cycle::database()->transaction(static function ($db): void { $db->execute('UPDATE accounts SET balance = balance - 100 WHERE id = 1'); $db->execute('UPDATE accounts SET balance = balance + 100 WHERE id = 2'); // commit on success; any exception -> automatic rollback and rethrow });
Manual control works too — just always pair begin() with commit()/rollback():
$db = Cycle::database(); $db->begin(); try { $db->execute('UPDATE accounts SET balance = balance - 100 WHERE id = 1'); $db->commit(); } catch (\Throwable $e) { $db->rollback(); throw $e; }
If a transaction is nevertheless left open (an exception skipped the rollback), the plugin rolls it back when the request context ends — see Exceptions, transactions and connection safety.
Multiple databases
You can work with any number of named databases configured in database.databases,
and switch between them freely at call time — just pass the database name.
There is no global "current database" state: each request/coroutine gets an isolated
handle per database name (the context key is webman_cycle.database.<name>), so
switching is coroutine-safe.
// config: database.databases 'databases' => [ 'default' => ['connection' => 'mysql'], 'reporting' => ['connection' => 'mysql'], 'archive' => ['connection' => 'sqlite'], ],
use KLobanov\CycleOrm\Cycle; Cycle::database(); // the default database Cycle::database('reporting'); // another database Cycle::database('archive'); // and a third one
or through the injected provider:
$this->dbal->database('reporting')->query('SELECT ...');
Notes:
- In annotated mode, an entity can be bound to a specific database with
#[Entity(database: 'reporting')]— its repository then hits that database automatically. database.aliasesmaps extra names onto configured databases.- In
pooledmode every named database gets its own connection pool, so heavy traffic on one database does not starve the others. - New connections can not be added at runtime: the configuration is assembled
once at worker start (
KernelBuilder). Declare every database you plan to use in the config upfront.
Console commands
All commands are run as php webman <command> (requires webman/console in the host app).
Schema
| Command | Description |
|---|---|
cycle:sync [--force] [--dry-run] |
Create or alter database tables to match the Cycle ORM schema. Requires annotated mode. --dry-run only prints the detected changes. |
cycle:schema:dump |
Compile the ORM schema and write it to the file configured in orm.schema_cache. Run once at deploy time so workers boot without re-scanning entities. |
cycle:render [roles...] [--format=php|mermaid|color|plain] |
Render the ORM schema (as a PHP array, Mermaid ER diagram, color or plain text). |
Migrations
| Command | Description |
|---|---|
cycle:migrate:init |
Create the migrations tracking table (migrations.table) in every configured database if it does not exist. |
cycle:migrate [--one] |
Execute outstanding migrations (all, or only the first one with --one). |
cycle:migrate:rollback [--all] |
Roll back one (default) or all executed migrations. |
cycle:migrate:replay [--all] |
Replay (down, up) one (default) or all executed migrations. |
cycle:migrate:status |
List all available migrations and their statuses (executed / pending). |
cycle:migrate:generate [--split] [--run] |
Generate migrations as a schema diff of the ORM schema against the live database. --split writes one file per table; --run executes the generated migration immediately. |
Database introspection
| Command | Description |
|---|---|
cycle:db:list [db] |
List available databases with their tables and record counts. |
cycle:db:table <table> [--database=default] |
Describe the table schema (columns, types, indexes, foreign keys) of a specific database. |
Typical first-run sequence:
php webman cycle:migrate:init # create the tracking table (or use cycle:sync instead) php webman cycle:migrate # apply migrations php webman cycle:migrate:status # verify
⚠️ Correct and incorrect usage
Webman is a long-running process framework: workers live for a long time and serve many requests (often concurrently, in coroutines). Therefore never cache database connections or ORM instances in long-lived properties. Acquiring a connection once in a constructor and reusing it across requests leads to connection leaks, broken transactions (different parts of one request may end up on different connections) and cross-request state pollution.
❌ Wrong — persisting the connection/ORM in a property:
final class QuantityManager { private \Cycle\Database\DatabaseInterface $database; public function __construct(private \Cycle\Database\DatabaseProviderInterface $dbal) { // WRONG: the connection is captured once and reused across all requests. // It leaks (never released to the pool) and may belong to another // request's context by the time decrease() runs. $this->database = $this->dbal->database(); } public function decrease(int $productId, int $quantity): void { // Uses a stale connection — may be a DIFFERENT connection than the // repository uses, so wrapping code in a transaction silently fails. $this->database->execute( 'UPDATE products SET quantity = quantity - ? WHERE id = ? AND quantity >= ?', [$quantity, $productId, $quantity], ); } }
✅ Correct — acquire the handle at call time (injection of the factory is fine):
use Cycle\Database\DatabaseProviderInterface; final class QuantityManager { public function __construct( private readonly DatabaseProviderInterface $dbal, // holds NO connection state ) {} public function decrease(int $productId, int $quantity): void { // Fetched at call time: within one request/coroutine this returns the // SAME instance everywhere (so transactions work), and it is released // automatically when the request context ends. $affected = $this->dbal->database()->execute( 'UPDATE products SET quantity = quantity - ? WHERE id = ? AND quantity >= ?', [$quantity, $productId, $quantity], ); if ($affected === 0) { throw new \RuntimeException('Not enough items in stock'); } } }
Rules of thumb:
- Inject
OrmFactoryInterface/DatabaseProviderInterface(orDatabaseManager) into services and keep them in properties — they are stateless and coroutine-safe. - Call
->database(),->orm(),->entityManager()inside the method that uses them, never in constructors. - Don't cache
DatabaseInterface,ORMInterfaceorEntityManagerInterfacein statics, singletons' properties, or global state — the package already gives you per-request isolation for free.
Exceptions, transactions and connection safety
A frequent concern in a long-running framework: what happens to the database connection if my code throws an exception — especially in the middle of a transaction? The short answer: the connection is never leaked or left dirty, no matter how the request ends.
What happens on an exception
- webman always destroys the request context. The whole request cycle in webman is
wrapped in
try/catch (Throwable), and the response sender callsContext::destroy()on both the success path and the exception path. Cleanup does not depend on how the request ended. - Context destruction releases every database lease. When you first ask for a
database,
DatabaseManagerregisters anonDestroycallback for the lease in the request context. When the context is destroyed (normally or after an exception), every lease is released exactly once. - Release rolls back dangling transactions. Before the connection changes owner,
the plugin checks the transaction level: if a transaction is still open (you forgot
commit/rollback, or an exception skipped it), it is rolled back and a warning is logged: "Open transaction rolled back during connection release; did you forget to commit?". Watch your logs for this message — it points at a missing rollback in your code. - The connection then goes back to its owner, clean:
pooled— returned to the pool (if the pool refuses it, the connection is force-closed instead);per-context— disconnected;process-shared— kept by the process, but with no open transaction.
ORM transactions roll back even earlier
EntityManager::run() executes its commands through Cycle's Transaction\Runner:
if any command fails, the runner rolls back the database transaction itself and only
then rethrows the exception. So in the typical ORM flow the transaction is already
closed by the time the exception reaches your controller — the release-time rollback
described above is a safety net for manual $db->begin() without a matching
commit()/rollback().
The release itself is fault-tolerant
ConnectionLease::release()is idempotent — calling it twice is harmless.- A failure during the rollback is caught and logged as an error, never thrown.
- A failure while returning the connection to the pool is caught, and the connection is force-disconnected so a broken handle never re-enters the pool.
Caveats
-
Catching an exception and continuing in the same transaction is your responsibility. On PostgreSQL a failed statement puts the whole transaction into the aborted state — every subsequent query fails with "current transaction is aborted" until you
ROLLBACK. The plugin does not interfere inside a request. -
Non-HTTP contexts (Workerman custom processes, timers): webman does not call
Context::destroy()there automatically. End the context yourself at the end of every iteration —Cycle::destroyContext()releases all leases deterministically (without it they would be released only when the garbage collector reclaims the coroutine context):use KLobanov\CycleOrm\Cycle; use Workerman\Timer; Timer::add(60, static function (): void { try { // work with Cycle::database() / Cycle::orm() } finally { Cycle::destroyContext(); // deterministic lease release } });
Never call
destroyContext()in the middle of an HTTP request — it wipes the whole webman context, including the currentRequest. -
A "forgotten commit" does not corrupt anything (the plugin rolls the transaction back at release and logs a warning), but it silently discards your writes. The real fix is to not manage transactions by hand: use
$db->transaction(fn ($db) => …), which always pairs commit with rollback (see the Transactions section). Treat the rollback warning in the log as a bug signal, not as normal noise. -
MySQL:
getTransactionLevel()reconnects a disconnected driver. The Cycle MySQL driver implements it throughgetPDO(), so calling it on a disconnected driver silently opens a new connection (andisConnected()becomestrueagain). Keep this in mind when inspecting connection state in your own cleanup or diagnostic code.
Everything described above is covered by the test suite: functional tests exercise the
rollback-on-release path for all three connection strategies, and the same scenario is
verified against real MySQL/MariaDB/PostgreSQL servers in CI
(tests/Functional/Database/DsnConnectionTest.php).
Testing & development
make install # composer install inside the container make test # all suites: Unit + Functional + Integration make stan # phpstan level 8
License
MIT