Skip to content

Commit 29ef930

Browse files
committed
feat: Add Cycle ORM extension for Express-PHP microframework
- Created composer.json for package management. - Added configuration file for Cycle ORM settings. - Implemented commands for entity generation, migration, and schema management. - Developed middleware for automatic ORM injection, transaction management, and entity validation. - Created repository factory for managing entity repositories. - Added helper functions for pagination and dynamic filtering. - Established a service provider to register and boot Cycle ORM services. - Included tests for service provider and various components. - Added documentation for installation, configuration, and usage examples.
0 parents  commit 29ef930

34 files changed

Lines changed: 1484 additions & 0 deletions

.env.example

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Exemplo de configuração .env para express-php/cycle-orm-extension
2+
3+
# Banco de Dados
4+
DB_CONNECTION=mysql
5+
DB_HOST=localhost
6+
DB_PORT=3306
7+
DB_DATABASE=express_api
8+
DB_USERNAME=root
9+
DB_PASSWORD=
10+
11+
# Configurações do Cycle ORM
12+
CYCLE_SCHEMA_CACHE=true
13+
CYCLE_AUTO_SYNC=false
14+
CYCLE_SCHEMA_STRICT=false
15+
16+
# Outras opções
17+
APP_ENV=local
18+
APP_DEBUG=true
19+
APP_URL=http://localhost

CHANGELOG.md

Whitespace-only changes.

LINCENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2025 Express PHP Framework
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

Lines changed: 190 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,190 @@
1+
# Express-PHP Cycle ORM Extension
2+
3+
Integração completa do Cycle ORM com o microframework Express-PHP, mantendo a filosofia ultraleve e performance excepcional.
4+
5+
## ⚡ Características
6+
7+
- **Auto-Discovery**: Registra automaticamente via Service Provider
8+
- **Middleware Integration**: Injeção automática de ORM, EntityManager e helpers
9+
- **Transaction Management**: Transações automáticas com middleware
10+
- **CLI Commands**: Comandos para schema, migrações e geração de entidades
11+
- **Zero Configuration**: Funciona out-of-the-box com configurações sensatas
12+
- **High Performance**: Otimizado para microframework ultraleve
13+
14+
## 🚀 Instalação
15+
16+
```bash
17+
composer require express-php/cycle-orm-extension
18+
```
19+
20+
O Service Provider é registrado automaticamente via auto-discovery.
21+
22+
## ⚙️ Configuração
23+
24+
Publique o arquivo de configuração (opcional):
25+
26+
```bash
27+
php express vendor:publish --provider="ExpressPHP\CycleORM\CycleServiceProvider"
28+
```
29+
30+
Configure suas variáveis de ambiente:
31+
32+
```env
33+
DB_CONNECTION=mysql
34+
DB_HOST=localhost
35+
DB_DATABASE=express_db
36+
DB_USERNAME=root
37+
DB_PASSWORD=
38+
```
39+
40+
## 📖 Uso Básico
41+
42+
### Criando uma Entidade
43+
44+
```bash
45+
php express make:entity User
46+
```
47+
48+
```php
49+
<?php
50+
51+
namespace App\Models;
52+
53+
use Cycle\Annotated\Annotation\Entity;
54+
use Cycle\Annotated\Annotation\Column;
55+
56+
#[Entity(table: 'users')]
57+
class User
58+
{
59+
#[Column(type: 'primary')]
60+
public int $id;
61+
62+
#[Column(type: 'string')]
63+
public string $name;
64+
65+
#[Column(type: 'string')]
66+
public string $email;
67+
}
68+
```
69+
70+
### Usando nas Rotas
71+
72+
```php
73+
$app->get('/api/users', function($req, $res) {
74+
// Repository injetado automaticamente
75+
$users = $req->repository(User::class)->findAll();
76+
$res->json(['users' => $users]);
77+
});
78+
79+
$app->post('/api/users', function($req, $res) {
80+
// Entity helper
81+
$user = $req->entity(User::class, $req->body);
82+
83+
// EntityManager injetado
84+
$req->em->persist($user);
85+
// Auto-commit via TransactionMiddleware
86+
87+
$res->status(201)->json(['user' => $user]);
88+
});
89+
```
90+
91+
### Comandos CLI
92+
93+
```bash
94+
# Sincronizar schema
95+
php express cycle:schema --sync
96+
97+
# Executar migrações
98+
php express cycle:migrate
99+
100+
# Gerar entidade
101+
php express make:entity Post
102+
```
103+
104+
## 🛠️ Middlewares Disponíveis
105+
106+
### CycleMiddleware
107+
Injeta automaticamente ORM, EntityManager e helpers no request.
108+
109+
### TransactionMiddleware
110+
Gerencia transações automaticamente:
111+
112+
```php
113+
$app->post('/api/users', function($req, $res) {
114+
// Transação iniciada automaticamente
115+
$user = new User($req->body);
116+
$req->em->persist($user);
117+
// Auto-commit ao final (ou rollback em caso de erro)
118+
});
119+
```
120+
121+
## 🎯 Recursos Avançados
122+
123+
### Paginação e Filtros
124+
125+
```php
126+
use ExpressPHP\CycleORM\Helpers\CycleHelpers;
127+
128+
$app->get('/api/users', function($req, $res) {
129+
$query = $req->repository(User::class)->select();
130+
131+
// Filtros dinâmicos
132+
$filters = $req->query['filters'] ?? [];
133+
$query = CycleHelpers::applyFilters($query, $filters);
134+
135+
// Ordenação
136+
$query = CycleHelpers::applySorting($query, 'createdAt', 'desc');
137+
138+
// Paginação
139+
$result = CycleHelpers::paginate($query, $req->query['page'] ?? 1);
140+
141+
$res->json($result);
142+
});
143+
```
144+
145+
### Relacionamentos Complexos
146+
147+
```php
148+
$app->get('/api/users/:id', function($req, $res) {
149+
$user = $req->repository(User::class)
150+
->select()
151+
->load('posts', [
152+
'method' => \Cycle\ORM\Select::SINGLE_QUERY
153+
])
154+
->where('id', $req->params['id'])
155+
->fetchOne();
156+
157+
$res->json(['user' => $user]);
158+
});
159+
```
160+
161+
## 🧪 Testing
162+
163+
```bash
164+
composer test
165+
composer test-coverage
166+
composer phpstan
167+
```
168+
169+
## 📊 Performance
170+
171+
- **Zero Overhead**: Registra serviços apenas quando necessário
172+
- **Lazy Loading**: Repositories e connections são lazy-loaded
173+
- **Optimized Queries**: Helpers otimizados para queries comuns
174+
- **Transaction Efficiency**: Transações automáticas evitam commits desnecessários
175+
176+
## 📚 Documentação Completa
177+
178+
Veja a documentação completa em: [docs/cycle-orm-extension.md](docs/cycle-orm-extension.md)
179+
180+
## 🤝 Contribuindo
181+
182+
1. Fork o projeto
183+
2. Crie uma branch para sua feature
184+
3. Commit suas mudanças
185+
4. Push para a branch
186+
5. Abra um Pull Request
187+
188+
## 📄 Licença
189+
190+
MIT License - veja [LICENSE](LICENSE) para detalhes.

composer.json

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
{
2+
"name": "express-php/cycle-orm-extension",
3+
"description": "Cycle ORM integration for Express-PHP microframework",
4+
"keywords": ["express-php", "cycle-orm", "database", "orm", "microframework"],
5+
"type": "library",
6+
"license": "MIT",
7+
"authors": [
8+
{
9+
"name": "Caio Alberto Fernandes",
10+
"email": "caio.fernandes@example.com"
11+
}
12+
],
13+
"require": {
14+
"php": "^8.1",
15+
"cafernandes/express-php": "^2.1",
16+
"cycle/orm": "^2.0",
17+
"cycle/annotated": "^3.0",
18+
"cycle/migrations": "^3.0",
19+
"cycle/schema-builder": "^2.0"
20+
},
21+
"require-dev": {
22+
"phpunit/phpunit": "^10.0",
23+
"phpstan/phpstan": "^1.0",
24+
"squizlabs/php_codesniffer": "^3.0"
25+
},
26+
"autoload": {
27+
"psr-4": {
28+
"ExpressPHP\\CycleORM\\": "src/"
29+
}
30+
},
31+
"autoload-dev": {
32+
"psr-4": {
33+
"ExpressPHP\\CycleORM\\Tests\\": "tests/"
34+
}
35+
},
36+
"extra": {
37+
"express-php": {
38+
"providers": [
39+
"ExpressPHP\\CycleORM\\CycleServiceProvider"
40+
]
41+
}
42+
},
43+
"scripts": {
44+
"test": "phpunit",
45+
"test-coverage": "phpunit --coverage-html coverage",
46+
"phpstan": "phpstan analyse src --level=9",
47+
"cs-check": "phpcs src --standard=PSR12",
48+
"cs-fix": "phpcbf src --standard=PSR12"
49+
}
50+
}

config/cycle.php

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
<?php
2+
3+
return [
4+
// Database configuration
5+
'database' => [
6+
'default' => env('DB_CONNECTION', 'mysql'),
7+
'databases' => [
8+
'default' => ['connection' => env('DB_CONNECTION', 'mysql')]
9+
],
10+
'connections' => [
11+
'mysql' => [
12+
'driver' => 'mysql',
13+
'host' => env('DB_HOST', 'localhost'),
14+
'port' => env('DB_PORT', 3306),
15+
'database' => env('DB_DATABASE', 'express_db'),
16+
'username' => env('DB_USERNAME', 'root'),
17+
'password' => env('DB_PASSWORD', ''),
18+
'charset' => 'utf8mb4',
19+
'collation' => 'utf8mb4_unicode_ci',
20+
'options' => [
21+
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
22+
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
23+
PDO::ATTR_EMULATE_PREPARES => false,
24+
]
25+
],
26+
'sqlite' => [
27+
'driver' => 'sqlite',
28+
'database' => env('DB_DATABASE', 'database/database.sqlite'),
29+
'options' => [
30+
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
31+
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
32+
]
33+
]
34+
]
35+
],
36+
37+
// Entity configuration
38+
'entities' => [
39+
'directories' => ['app/Models'],
40+
'namespace' => 'App\\Models'
41+
],
42+
43+
// Schema configuration
44+
'schema' => [
45+
'cache' => env('CYCLE_SCHEMA_CACHE', true),
46+
'auto_sync' => env('CYCLE_AUTO_SYNC', false),
47+
'strict' => env('CYCLE_SCHEMA_STRICT', false)
48+
],
49+
50+
// Migration configuration
51+
'migrations' => [
52+
'directory' => 'database/migrations',
53+
'table' => 'migrations',
54+
'safe' => env('CYCLE_SAFE_MIGRATIONS', true)
55+
],
56+
57+
// Repository configuration
58+
'repositories' => [
59+
'default' => \Cycle\ORM\Select\Repository::class
60+
]
61+
];

database/migrations/.gitkeep

Whitespace-only changes.

database/seeds/.gitkeep

Whitespace-only changes.

docs/advanced.md

Whitespace-only changes.

docs/configuration.md

Whitespace-only changes.

0 commit comments

Comments
 (0)