PHPackages                             pivotphp/cycle-orm - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. pivotphp/cycle-orm

ActiveLibrary[Database &amp; ORM](/categories/database)

pivotphp/cycle-orm
==================

Robust and well-tested Cycle ORM integration for PivotPHP microframework with type safety and comprehensive testing

v1.0.1(1y ago)05MITPHPPHP ^8.1CI passing

Since Jul 7Pushed 1mo agoCompare

[ Source](https://github.com/PivotPHP/pivotphp-cycle-orm)[ Packagist](https://packagist.org/packages/pivotphp/cycle-orm)[ RSS](/packages/pivotphp-cycle-orm/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (2)Dependencies (10)Versions (3)Used By (0)

PivotPHP Cycle ORM
==================

[](#pivotphp-cycle-orm)

[![PHP Version](https://camo.githubusercontent.com/7663c9d53dc13cedaf0660a8745a7e77d2dd711257f36aa86ebce12a0600ef42/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344382e312d626c75652e737667)](https://www.php.net/)[![License](https://camo.githubusercontent.com/8bb50fd2278f18fc326bf71f6e88ca8f884f72f179d3e555e20ed30157190d0d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e2e737667)](LICENSE)[![Latest Stable Version](https://camo.githubusercontent.com/7351e430b9334d62486fed10fef78c61bf6dbe29ee5cf95342ebf0c223623c19/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f76657273696f6e2d312e302e312d627269676874677265656e2e737667)](https://github.com/PivotPHP/pivotphp-cycle-orm/releases)[![PHPStan](https://camo.githubusercontent.com/14889c37b8235258c5726f27e4d123de5f5f2cd9598e76313e88a78e856d3816/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d4c6576656c253230392d737563636573732e737667)](https://phpstan.org/)[![Tests](https://camo.githubusercontent.com/b7ac78515ab1d91de73a0e69cfbe09b376ac17f62dfb0bdbe6be58f59fbe23e2/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f74657374732d36372532307061737365642d737563636573732e737667)](https://github.com/PivotPHP/pivotphp-cycle-orm/actions)

Robust and well-tested Cycle ORM integration for PivotPHP microframework

🚀 Features
----------

[](#-features)

- **Seamless Integration**: Deep integration with PivotPHP Core
- **Type Safety**: Full type safety with PHPStan Level 9
- **Repository Pattern**: Built-in repository pattern support
- **Performance Monitoring**: Query logging and performance profiling
- **Middleware Support**: Transaction and validation middleware
- **Health Checks**: Database health monitoring
- **Zero Configuration**: Works out of the box with sensible defaults

📦 Installation
--------------

[](#-installation)

```
composer require pivotphp/cycle-orm
```

### Development Setup

[](#development-setup)

When developing locally with both pivotphp-core and pivotphp-cycle-orm:

1. Clone both repositories in the same parent directory:

```
git clone https://github.com/PivotPHP/pivotphp-core.git
git clone https://github.com/PivotPHP/pivotphp-cycle-orm.git
```

2. Install dependencies:

```
cd pivotphp-cycle-orm
composer install
```

**Note**: `composer.json` does not currently declare a local `repositories` path to a sibling `pivotphp-core` checkout — it resolves `pivotphp/core` from Packagist like any other dependency, both locally and in CI. If you need to develop against an unreleased `pivotphp-core` change, add a local path repository yourself.

🔧 Quick Start
-------------

[](#-quick-start)

### 1. Register the Service Provider

[](#1-register-the-service-provider)

```
use PivotPHP\Core\Core\Application;
use PivotPHP\CycleORM\CycleServiceProvider;

$app = new Application();
$app->register(new CycleServiceProvider($app));
```

### 2. Configure Database

[](#2-configure-database)

```
// config/cycle.php
return [
    'database' => [
        'default' => 'default',
        'databases' => [
            'default' => ['connection' => 'sqlite']
        ],
        'connections' => [
            'sqlite' => [
                'driver' => \Cycle\Database\Driver\SQLite\SQLiteDriver::class,
                'options' => [
                    'connection' => 'sqlite:database.db',
                ]
            ]
        ]
    ]
];
```

### 3. Define Entities

[](#3-define-entities)

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

#[Entity(repository: UserRepository::class)]
class User
{
    #[Column(type: 'primary')]
    private int $id;

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

    #[Column(type: 'string', unique: true)]
    private string $email;

    // Getters and setters...
}
```

### 4. Use in Routes

[](#4-use-in-routes)

```
$app->get('/users', function (CycleRequest $request) {
    $users = $request->getRepository(User::class)->findAll();

    return $request->response()->json($users);
});

$app->post('/users', function (CycleRequest $request) {
    $user = new User();
    $user->setName($request->input('name'));
    $user->setEmail($request->input('email'));

    $request->persist($user);

    return $request->response()->json($user, 201);
});
```

🎯 Core Features
---------------

[](#-core-features)

### Repository Pattern

[](#repository-pattern)

```
// Custom repository
class UserRepository extends Repository
{
    public function findByEmail(string $email): ?User
    {
        return $this->findOne(['email' => $email]);
    }

    public function findActive(): array
    {
        return $this->select()
            ->where('active', true)
            ->orderBy('created_at', 'DESC')
            ->fetchAll();
    }
}
```

### Transaction Middleware

[](#transaction-middleware)

```
use PivotPHP\CycleORM\Middleware\TransactionMiddleware;

// Automatic transaction handling
$app->post('/api/orders',
    new TransactionMiddleware($app),
    function (CycleRequest $request) {
        // All database operations are wrapped in a transaction
        $order = new Order();
        $request->persist($order);

        // If an exception occurs, transaction is rolled back
        foreach ($request->input('items') as $item) {
            $orderItem = new OrderItem();
            $request->persist($orderItem);
        }

        return $request->response()->json($order);
    }
);
```

### Query Monitoring

[](#query-monitoring)

```
use PivotPHP\CycleORM\Monitoring\QueryLogger;

// Enable query logging
$logger = $app->get(QueryLogger::class);
$logger->enable();

// Get query statistics
$stats = $logger->getStatistics();
// [
//     'total_queries' => 42,
//     'total_time' => 0.123,
//     'queries' => [...]
// ]
```

### Health Checks

[](#health-checks)

```
use PivotPHP\CycleORM\Health\CycleHealthCheck;

$app->get('/health', function () use ($app) {
    $health = $app->get(CycleHealthCheck::class);
    $status = $health->check();

    return [
        'status' => $status->isHealthy() ? 'healthy' : 'unhealthy',
        'database' => $status->getData()
    ];
});
```

🛠️ Advanced Usage
-----------------

[](#️-advanced-usage)

### Entity Validation Middleware

[](#entity-validation-middleware)

`EntityValidationMiddleware` takes no constructor arguments and does not support Laravel-style rule strings (`'required|string|min:3'`). It wraps the request in a `CycleRequest` and exposes `validateEntity(object $entity): array{valid: bool, errors: array}`, a basic reflection-based check (required non-nullable properties, `string`/`int` type mismatches) that you call yourself inside your handler:

```
use PivotPHP\CycleORM\Middleware\EntityValidationMiddleware;

$validation = new EntityValidationMiddleware();

$app->post('/users',
    $validation,
    function (CycleRequest $request, $res) use ($validation) {
        $user = new User();
        // ...populate $user from $request...

        $result = $validation->validateEntity($user);
        if (!$result['valid']) {
            return $res->status(422)->json(['errors' => $result['errors']]);
        }

        // persist $user...
    }
);
```

### Performance Profiling

[](#performance-profiling)

```
use PivotPHP\CycleORM\Monitoring\PerformanceProfiler;

$profiler = $app->get(PerformanceProfiler::class);
$profiler->startProfiling();

// Your database operations...

$profile = $profiler->stopProfiling();
// [
//     'duration' => 0.456,
//     'memory_peak' => 2097152,
//     'queries_count' => 15
// ]
```

### Custom Commands

[](#custom-commands)

This package does **not** ship a `bin/console` executable or a `vendor/bin/pivotphp`binary. `Commands\SchemaCommand`, `MigrateCommand`, `EntityCommand`, and `StatusCommand`are plain PHP classes with a `handle(): int` method — instantiate them yourself (typically from a small console script your own project provides):

```
use PivotPHP\CycleORM\Commands\{SchemaCommand, MigrateCommand, EntityCommand, StatusCommand};

(new EntityCommand(['name' => 'User'], $container))->handle();   // create entity
(new MigrateCommand([], $container))->handle();                  // run migrations
(new SchemaCommand(['--sync' => true], $container))->handle();   // sync schema
(new StatusCommand([], $container))->handle();                   // check status
```

See [Configurar Console](docs/integration-guide.md#-comandos-cli) for a complete example `bin/console` script that wires these into runnable CLI commands.

🧪 Testing
---------

[](#-testing)

```
# Run all tests
composer test

# Run specific test suite
composer test:unit
composer test:feature
composer test:integration

# Run with coverage (cross-platform)
composer test-coverage

# Platform-specific alternatives:
# Unix/Linux/macOS
./scripts/test-coverage.sh
# Windows CMD
scripts\test-coverage.bat
# PowerShell
scripts\test-coverage.ps1
```

### Cross-Platform Compatibility

[](#cross-platform-compatibility)

The project includes cross-platform scripts for coverage testing:

- **Primary method**: `composer test-coverage` (works on all platforms)
- **Alternative scripts**: Platform-specific scripts in `scripts/` directory
- **Windows support**: Both CMD and PowerShell scripts included

📚 Documentation
---------------

[](#-documentation)

- [Integration Guide](docs/integration-guide.md)
- [Complete Guide](docs/guia-completo.md)
- [API Reference](docs/quick-reference.md)
- [Examples](examples/)

🤝 Contributing
--------------

[](#-contributing)

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

📄 License
---------

[](#-license)

PivotPHP Cycle ORM is open-sourced software licensed under the [MIT license](LICENSE).

🙏 Credits
---------

[](#-credits)

- Created by [Caio Alberto Fernandes](https://github.com/CAFernandes)
- Built on top of [Cycle ORM](https://cycle-orm.dev/)
- Part of the [PivotPHP](https://github.com/PivotPHP) ecosystem

---

 Built with PivotPHP - The modern PHP microframework

###  Health Score

35

—

LowBetter than 77% of packages

Maintenance73

Regular maintenance activity

Popularity4

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 50.3% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~1 days

Total

2

Last Release

405d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/acac781b459ef1f37c5f01f4b1caf52d05870d64a63ccd87b39f294da98e6def?d=identicon)[CAFernandes](/maintainers/CAFernandes)

---

Top Contributors

[![code-cfernandes](https://avatars.githubusercontent.com/u/34290014?v=4)](https://github.com/code-cfernandes "code-cfernandes (72 commits)")[![CAFernandes](https://avatars.githubusercontent.com/u/34290014?v=4)](https://github.com/CAFernandes "CAFernandes (71 commits)")

---

Tags

cycle-ormdatabasehelixphpintegrationmariadbmysqlormperformancephppostgresqltype-safezero-configmiddlewarePHPStanmonitoringdatabaseormmicroframeworkrepository patterntype-safecycle-ormpivotphp

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/pivotphp-cycle-orm/health.svg)

```
[![Health](https://phpackages.com/badges/pivotphp-cycle-orm/health.svg)](https://phpackages.com/packages/pivotphp-cycle-orm)
```

###  Alternatives

[wayofdev/laravel-cycle-orm-adapter

🔥 A Laravel adapter for CycleORM, providing seamless integration of the Cycle DataMapper ORM for advanced database handling and object mapping in PHP applications.

3542.5k3](/packages/wayofdev-laravel-cycle-orm-adapter)[cycle/annotated

Cycle ORM Annotated Entities generator

29817.4k61](/packages/cycle-annotated)[cycle/active-record

Provides a simple way to work with your database using Active Record pattern and Cycle ORM

672.0k5](/packages/cycle-active-record)[tommyknocker/pdo-database-class

Framework-agnostic PHP database library with unified API for MySQL, MariaDB, PostgreSQL, SQLite, MSSQL, and Oracle. Query Builder, caching, sharding, window functions, CTEs, JSON, migrations, ActiveRecord, CLI tools, AI-powered analysis. Zero external dependencies.

856.1k](/packages/tommyknocker-pdo-database-class)[friendsofsymfony1/doctrine1

PHP Database ORM for Symfony1. Do NOT use for new projects: please move to a newest Symfony release and Doctrine2

40726.6k](/packages/friendsofsymfony1-doctrine1)[spiral/cycle-bridge

Cycle ORM integration package

19146.2k10](/packages/spiral-cycle-bridge)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
