If there is one thing I love in web development, it is finding tools that simplify life without compromising performance. ORMs like Doctrine are powerful, but they often come with complex configurations and a steep learning curve. Recently, I came across Composite DB, a minimalist ORM you can get up and running in under 5 minutes. Looking for a lightweight, fast alternative for your PHP 8.1+ projects? Keep reading!
What Is Composite DB?
Composite DB is an ultra-lightweight ORM designed for PHP 8.1+. Its philosophy is simple: less configuration, more action. It leverages modern PHP features to deliver clean code and snappy performance, making it ideal for projects where speed and simplicity are top priorities.
The Best of PHP 8.1+ in Your Hands
Composite DB takes full advantage of recent PHP features. Take a look at this entity example:
<?php
// src/Entity/User.php
namespace App\Entity;
use Composite\DB\Attributes\{Table, PrimaryKey};
use Composite\Entity\AbstractEntity;
use App\Enums\Status;
#[Table(connection: 'sqlite', name: 'Users')]
class User extends AbstractEntity
{
#[PrimaryKey(autoIncrement: true)]
public readonly int $id;
public function __construct(
public string $email,
public ?string $name = null,
public bool $is_test = false,
public Status $status = Status::ACTIVE,
public readonly \DateTimeImmutable $created_at = new \DateTimeImmutable(),
) {}
}
- Native Enums: Use
Statusto cleanly define states likeACTIVEorBLOCKED. - Immutable properties:
idandcreated_atarereadonly, ensuring data consistency. - PHP Attributes: Map your entity to database tables effortlessly using
#[Table]and#[PrimaryKey].
When Does Composite DB Shine?
This ORM is ideal for scenarios where you need to move fast:
- RESTful APIs: Build mobile app endpoints in minutes.
- Rapid prototyping: Validate ideas without wasting time on boilerplate configuration.
- IoT projects: Handle sensor data with minimal overhead.
Practical Tutorial: API with Composite DB and Slim Framework
We are going to build a simple API using Composite DB and Slim, with SQLite as the database. Follow these steps and you will have a working solution in no time!
1. Install dependencies
Create a new project and install the required dependencies with Composer:
mkdir CompositeDB-Slim
cd CompositeDB-Slim
composer init --name="tu-nombre/composite-db-slim" --require="php:^8.1"
composer require slim/slim:^4.0 slim/psr7 composite/db vlucas/phpdotenv
2. Configure the database connection
Composite DB requires a configuration file for the connection. Create src/Config/ConnectionManager.php:
[
'driver' => 'pdo_sqlite',
'path' => DB_PATH, //SQLite creará este archivo si no existe
],
];
Next, configure the CONNECTIONS_CONFIG_FILE environment variable using phpdotenv. Create a .env file in the project root:
CONNECTIONS_CONFIG_FILE=../src/Config/ConnectionManager.php
Tip: The path ../src/Config/ConnectionManager.php is relative to the public/ directory, where index.php runs. This ensures Composite DB resolves the file correctly.
3. Define the model and table
Create the Status enum in src/Enums/Status.php:
<?php
namespace App\Enums;
enum Status: string
{
case ACTIVE = 'ACTIVE';
case BLOCKED = 'BLOCKED';
}
Use the User entity shown earlier (src/Model/User.php).
Now, define the table class in src/Model/UsersTable.php:
<?php
namespace App\Table;
use Composite\DB\AbstractTable;
use App\Entity\User;
class UsersTable extends \Composite\DB\AbstractTable
{
protected function getConfig(): \Composite\DB\TableConfig
{
return \Composite\DB\TableConfig::fromEntitySchema(User::schema());
}
/**
* @return User[]
*/
public function findAllActive(): array
{
return $this->_findAll(['status' => \App\Enums\Status::ACTIVE]);
}
public function init(): void
{
$this->getConnection()->executeStatement("
CREATE TABLE IF NOT EXISTS Users
(
`id` INTEGER
CONSTRAINT Users_pk PRIMARY KEY AUTOINCREMENT,
`email` VARCHAR(255) NOT NULL,
`name` VARCHAR(255) DEFAULT NULL,
`is_test` INT DEFAULT 0 NOT NULL,
`status` TEXT DEFAULT 'ACTIVE' NOT NULL,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
CHECK (status IN ('ACTIVE', 'BLOCKED'))
);
");
}
}
Note: Call init() once to create the table schema. You can run this manually or during initial bootstrapping (we will see this shortly).
4. Configure Slim and routes
Create public/index.php with the API logic:
<?php
declare(strict_types=1);
use App\Controllers\RootController;
use App\Controllers\UserController;
use DI\ContainerBuilder;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
use Dotenv\Dotenv;
require __DIR__ . '/../vendor/autoload.php';
// Cargar variables de entorno
$dotenv = Dotenv::createImmutable(__DIR__ . '/../');
$dotenv->load();
// Configurar PHP-DI
$containerBuilder = new ContainerBuilder();
$containerBuilder->addDefinitions([
\App\Table\UsersTable::class => \DI\create(\App\Table\UsersTable::class)
]);
// Construir el contenedor
$container = $containerBuilder->build();
// Configurar Slim con el contenedor
AppFactory::setContainer($container);
$app = AppFactory::create();
$app->addRoutingMiddleware();
// Inicializar la base de datos (descomentar solo la primera vez)
// $container->get(App\Table\UsersTable::class)->init();
// Rutas
$app->get('/', [RootController::class, 'index']);
$app->get('/users', [UserController::class, 'list']);
$app->post('/users', [UserController::class, 'create']);
$app->run();
5. Test the API
Create the database/ directory in the project root:
mkdir database
Note: The repository includes an SQLite database with sample data, but if you want to start from scratch, this is how you initialize it.
Start the built-in development server:
php -S localhost:8000 -t public
Test the endpoints:
- List active users:
curl http://localhost:8000/
Expected response:
{
"data": [],
"message": "Usuarios activos obtenidos correctamente"
}
- Show active users:
curl -X GET http://localhost:8000/users
Expected response:
{
"status": "success",
"data": [
{
"id": 1,
"email": "[email protected]",
"name": "John",
"is_test": false,
"status": "ACTIVE",
"created_at": "2025-04-10 22:24:20.128227"
},
{
"id": 2,
"email": "[email protected]",
"name": "Martie",
"is_test": false,
"status": "ACTIVE",
"created_at": "2025-04-10 22:56:49.105486"
}
],
"message": "Usuarios activos obtenidos correctamente"
}
- Create a user:
curl -X POST http://localhost:8000/users -H "Content-Type: application/json" -d '{"email":"[email protected]","name":"Test User"}'
Expected response:
{
"data": {
"id": 1,
"email": "[email protected]",
"name": "Test User",
"is_test": false,
"status": "ACTIVE",
"created_at": "2025-04-10T20:00:00+00:00"
},
"message": "Usuario creado correctamente"
}
Limitations and How to Make the Most of It
Composite DB is not designed for complex relational mapping (such as automatic joins), but that is not a blocker if you know how to adapt:
- Manual SQL queries: Use
$usersTable->getConnection()->executeQuery()for custom queries. - Optional caching: While not used here, Composite DB supports lightweight caching to speed up recurring queries.
- Simplicity as a strength: Its minimalist design keeps overhead low and your codebase maintainable.
For example, to run a manual join:
/**
* @return User[]
*/
public function findAllActiveAdults(): array
{
return $this->_findAll(
new Where(
'age > :age AND status = :status',
['age' => 18, 'status' => Status::ACTIVE->name],
)
);
}
Lessons Learned from the Documentation
The documentation for Composite DB can be somewhat ambiguous in certain areas:
- Relative paths: It is not always obvious how to set
CONNECTIONS_CONFIG_FILE. Usingphpdotenvwith a path relative topublic/(such as../src/Config/ConnectionManager.php) solves the issue. - Initial configuration: I had to experiment to understand how the ORM loads the connection configuration. My advice: double-check that paths match your folder structure.
We recommend using phpdotenv for cleaner configuration management and ensuring the connection file path resolves properly within your project layout.
Who Is Using Composite DB?
This ORM is gaining traction among:
- Startups: Perfect for getting MVPs shipped fast.
- DevOps: Easy to integrate alongside monitoring tools like Prometheus or Grafana.
Is Composite DB Right for You?
If you value:
- Extreme simplicity: Minimal setup, instant results.
- Agile performance: Near-zero overhead, perfect for lightweight services.
- Modern PHP: Built around enums, readonly properties, and attributes.
…Then this tool is definitely worth considering! If your project demands complex migrations or advanced transactions, mature alternatives like Doctrine might be a better fit.
Composite DB is a hidden gem for small projects, prototypes, or any use case where speed and simplicity are essential. You can inspect the complete source code in this repository. Ready to give it a try in your next project?