PHPackages                             ayela-emmanuel/ayela-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. ayela-emmanuel/ayela-orm

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

ayela-emmanuel/ayela-orm
========================

This packge Is a Minimal ORM Setup for interacting with your SQL Database using PDO but abstracts the Database to a more OOP Approch

1.0.1(1y ago)3421AGPL-3.0-or-laterPHPPHP &gt;=8.0

Since Sep 17Pushed 1y ago1 watchersCompare

[ Source](https://github.com/ayela-emmanuel/Ayela-PHP-ORM)[ Packagist](https://packagist.org/packages/ayela-emmanuel/ayela-orm)[ RSS](/packages/ayela-emmanuel-ayela-orm/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (2)DependenciesVersions (3)Used By (1)

AyelaORM - PHP ORM Package
==========================

[](#ayelaorm---php-orm-package)

**AyelaORM** is a lightweight PHP Object-Relational Mapping (ORM) package designed to simplify database interactions using PHP's PDO extension. It provides an easy-to-use interface for managing database schemas and objects, dynamically handles table creation and updates, and supports relationships between models, reducing the need for manual schema management and complex SQL queries.

Table of Contents
-----------------

[](#table-of-contents)

1. [Installation](#installation)
2. [Usage](#usage)
    - [Database Setup](#database-setup)
    - [Creating Models](#creating-models)
    - [Saving Data](#saving-data)
    - [Retrieving Data](#retrieving-data)
    - [Updating Data](#updating-data)
    - [Deleting Data](#deleting-data)
3. [Advanced Querying](#advanced-querying)
    - [Simple Conditions](#simple-conditions)
    - [Advanced Conditions](#advanced-conditions)
    - [Relationships (Joins)](#relationships-joins)
    - [One-to-Many and Many-to-Many Relationships](#one-to-many-and-many-to-many-relationships)
4. [Schema Management](#schema-management)
    - [Automatic Schema Updates](#automatic-schema-updates)
    - [Custom SQL Types](#custom-sql-types)
    - [Ignoring Properties](#ignoring-properties)
5. [Data Types and Serialization](#data-types-and-serialization)
6. [Error Handling](#error-handling)
7. [License](#license)

Installation
------------

[](#installation)

Install the package using Composer:

```
composer require ayela-emmanuel/ayela-orm
```

Ensure that the `PDO` extension is enabled for your PHP installation (MySQL is the default). Add the necessary namespace `AyelaORM` to your project.

Usage
-----

[](#usage)

### Database Setup

[](#database-setup)

Before using AyelaORM, you must set up the database connection:

```
use AyelaORM\Database;

Database::setup('localhost', 'database_name', 'username', 'password', false);
```

- **host**: Database server host (e.g., `localhost`).
- **db**: Database name.
- **username**: Database username.
- **password**: Database password.
- **frozen**: If `true`, the database schema will not be checked or updated automatically.

### Creating Models

[](#creating-models)

To create a model that interacts with the database, extend the `DatabaseObject` class:

```
namespace Models;

use AyelaORM\DatabaseObject;
use AyelaORM\SQLType;
use AyelaORM\SQLIgnore;

class User extends DatabaseObject
{
    public string $db_username;
    public string $db_email;
    public int $db_age;
    public \DateTime $db_created_at;

    #[SQLIgnore]
    public string $password; // Will not be stored in the database

    public function __construct()
    {
        parent::__construct();
        $this->db_created_at = new \DateTime();
    }
}
```

**Notes:**

- **Property Naming**: Properties intended for database storage should be prefixed with `db_`. The prefix is removed when mapping to the database column.
- **Type Handling**: The class infers SQL data types from PHP property types.
- **Attributes**:
    - Use `#[SQLType("...")]` to specify a custom SQL type for a property.
    - Use `#[SQLIgnore]` to exclude properties from the database schema.

Register your model on startup to ensure the schema is up to date:

```
Models\User::register();
```

### Saving Data

[](#saving-data)

To save a new object to the database:

```
$user = new Models\User();
$user->db_username = 'john_doe';
$user->db_email = 'john@example.com';
$user->db_age = 30;
$user->password = 'securepassword'; // Will not be saved to the database
$user->save();
```

After saving, the `db_id` property will be populated with the primary key value from the database.

### Retrieving Data

[](#retrieving-data)

You can retrieve records using several built-in methods.

#### Get All Records

[](#get-all-records)

```
$users = Models\User::list(1, 10); // Retrieve the first 10 users (page 1).
```

#### Get a Record by ID

[](#get-a-record-by-id)

```
$user = Models\User::getById(1);
```

#### Get the First Record

[](#get-the-first-record)

```
$user = Models\User::first();
```

### Updating Data

[](#updating-data)

Update a field of a record by ID:

```
Models\User::update(1, 'email', 'newemail@example.com');
```

### Deleting Data

[](#deleting-data)

#### Delete a Single Record

[](#delete-a-single-record)

```
Models\User::delete(1);
```

#### Delete Multiple Records

[](#delete-multiple-records)

```
$ids = [2, 3, 4];
Models\User::deleteGroup($ids);
```

Advanced Querying
-----------------

[](#advanced-querying)

AyelaORM provides advanced querying capabilities without the need to write raw SQL. The `findWhere` and `firstWhere` methods allow you to retrieve records based on conditions.

### Simple Conditions

[](#simple-conditions)

Provide an associative array where keys are field names and values are the values to match.

```
$users = Models\User::findWhere(['username' => 'john_doe']);
```

Retrieve the first matching record:

```
$user = Models\User::firstWhere(['email' => 'john@example.com']);
```

### Advanced Conditions

[](#advanced-conditions)

Provide an array of condition arrays, each containing a field, operator, and value.

```
$users = Models\User::findWhere([
    ['age', '>', 25],
    ['status', '=', 'active']
]);
```

Supported operators: `=`, `>`, `=`, `db_name = 'Jane Doe';
$author->db_email = 'jane@example.com';
$author->save();

$book = new Models\Book();
$book->db_title = 'Learning AyelaORM';
$book->db_author = $author; // Set the Author object
$book->save();
```

#### Retrieving Data with Relationships

[](#retrieving-data-with-relationships)

```
$book = Models\Book::getById(1);
echo $book->db_title; // Outputs: Learning AyelaORM
echo $book->db_author->db_name; // Outputs: Jane Doe
```

### One-to-Many and Many-to-Many Relationships

[](#one-to-many-and-many-to-many-relationships)

#### One-to-Many Example

[](#one-to-many-example)

In the `Author` class, add a method to retrieve related `Book` objects:

```
class Author extends DatabaseObject
{
    // ...

    public function getBooks(): array
    {
        return Models\Book::findWhere([['author', '=', $this->db_id]]);
    }
}

// Usage
$author = Models\Author::getById(1);
$books = $author->getBooks();
```

#### Many-to-Many Example

[](#many-to-many-example)

Create a join table model:

```
class Student extends DatabaseObject
{
    public string $db_name;

    public function enrollInCourse(Course $course)
    {
        $enrollment = new StudentCourse();
        $enrollment->db_student = $this;
        $enrollment->db_course = $course;
        $enrollment->save();
    }

    public function getCourses(): array
    {
        $enrollments = StudentCourse::findWhere([['student', '=', $this->db_id]]);
        return array_map(fn($enrollment) => $enrollment->db_course, $enrollments);
    }
}

class Course extends DatabaseObject
{
    public string $db_title;

    public function getStudents(): array
    {
        $enrollments = StudentCourse::findWhere([['course', '=', $this->db_id]]);
        return array_map(fn($enrollment) => $enrollment->db_student, $enrollments);
    }
}

class StudentCourse extends DatabaseObject
{
    public Student $db_student;
    public Course $db_course;
}
```

Schema Management
-----------------

[](#schema-management)

AyelaORM automatically manages database schema changes. Whenever you define or modify properties in your models, AyelaORM checks and updates the table structure accordingly.

### Automatic Schema Updates

[](#automatic-schema-updates)

If you set `frozen` to `false` during the database setup, the schema will be checked and updated on each model instantiation. Tables will be created if they do not exist, and columns will be added or modified when changes are detected.

```
Database::setup('localhost', 'database_name', 'username', 'password', false);
```

### Custom SQL Types

[](#custom-sql-types)

You can specify custom SQL types for your model properties using the `#[SQLType("...")]` attribute.

```
class Article extends DatabaseObject
{
    #[SQLType("TEXT")]
    public string $db_content;

    #[SQLType("VARCHAR(100) UNIQUE")]
    public string $db_slug;
}
```

### Ignoring Properties

[](#ignoring-properties)

To exclude a property from the database schema, use the `#[SQLIgnore]` attribute.

```
class User extends DatabaseObject
{
    #[SQLIgnore]
    public string $password; // Will not be stored in the database
}
```

Data Types and Serialization
----------------------------

[](#data-types-and-serialization)

AyelaORM handles various data types, including:

- **Scalar Types**: `int`, `float`, `string`, `bool`
- **DateTime**: Automatically converted to and from database date-time format
- **DatabaseObject Subclasses**: Stored as foreign keys (relationships)
- **Arrays and Serializable Objects**: Serialized to JSON before storing and deserialized when retrieving

### Example of Serializable Object

[](#example-of-serializable-object)

```
class UserProfile
{
    public string $bio;
    public array $interests;
}

class User extends DatabaseObject
{
    public string $db_username;
    public UserProfile $db_profile; // Serializable object
}

// Saving
$profile = new UserProfile();
$profile->bio = 'Developer';
$profile->interests = ['coding', 'music'];

$user = new User();
$user->db_username = 'johndoe';
$user->db_profile = $profile;
$user->save();

// Retrieving
$user = User::getById(1);
echo $user->db_profile->bio; // Outputs: Developer
```

Error Handling
--------------

[](#error-handling)

If an error occurs during database operations, it is stored in the `$last_error` property of the object.

```
$user = new Models\User();
$user->db_username = 'john_doe';

// Intentionally cause an error (e.g., missing required field)
if (!$user->save()) {
    echo "Error: " . $user->last_error->getMessage();
}
```

---

Feel free to reach out or open an issue if you encounter any problems or have suggestions for improvements!

---

**Note**: This documentation covers the latest features and provides examples to help you get started with AyelaORM. The package is designed to simplify your database interactions and manage relationships efficiently, allowing you to focus on building your application.

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance40

Moderate activity, may be stable

Popularity11

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~90 days

Total

2

Last Release

509d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/c1dcf19fa079571e9c621563fd8ff9945a25a732dfbe188493183873dd7534e6?d=identicon)[ayela-emmanuel](/maintainers/ayela-emmanuel)

---

Top Contributors

[![ayela-emmanuel](https://avatars.githubusercontent.com/u/62917075?v=4)](https://github.com/ayela-emmanuel "ayela-emmanuel (24 commits)")

### Embed Badge

![Health badge](/badges/ayela-emmanuel-ayela-orm/health.svg)

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

###  Alternatives

[doctrine/orm

Object-Relational-Mapper for PHP

10.2k285.3M6.2k](/packages/doctrine-orm)[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k115.1M102](/packages/jdorn-sql-formatter)[illuminate/database

The Illuminate Database package.

2.8k52.4M9.3k](/packages/illuminate-database)[mongodb/mongodb

MongoDB driver library

1.6k64.0M545](/packages/mongodb-mongodb)[ramsey/uuid-doctrine

Use ramsey/uuid as a Doctrine field type.

90340.3M211](/packages/ramsey-uuid-doctrine)[reliese/laravel

Reliese Components for Laravel Framework code generation.

1.7k3.4M16](/packages/reliese-laravel)

PHPackages © 2026

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