PHPackages                             rancoud/model - 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. [Testing &amp; Quality](/categories/testing)
4. /
5. rancoud/model

ActiveLibrary[Testing &amp; Quality](/categories/testing)

rancoud/model
=============

Model package

5.0.2(1mo ago)39.8k↓25%MITPHPPHP &gt;=8.4.0CI passing

Since Aug 13Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/rancoud/Model)[ Packagist](https://packagist.org/packages/rancoud/model)[ RSS](/packages/rancoud-model/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (6)Versions (30)Used By (0)

Model Package
=============

[](#model-package)

[![Packagist PHP Version Support](https://camo.githubusercontent.com/3b54bd85fac4217e57b91771c64d1d726d342c38b6ace8a237b1b07d1118ead7/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f72616e636f75642f6d6f64656c)](https://camo.githubusercontent.com/3b54bd85fac4217e57b91771c64d1d726d342c38b6ace8a237b1b07d1118ead7/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f72616e636f75642f6d6f64656c)[![Packagist Version](https://camo.githubusercontent.com/2d19c77569b92eb01f8ba86f965756446e984adb83de230fdf290ec2d1a13df3/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f72616e636f75642f6d6f64656c)](https://packagist.org/packages/rancoud/model)[![Packagist Downloads](https://camo.githubusercontent.com/4baf8a9247ec22e88fef1f452983f98f685b837ab60b208d92877ddeac9447f5/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f72616e636f75642f6d6f64656c)](https://packagist.org/packages/rancoud/model)[![Composer dependencies](https://camo.githubusercontent.com/e176e220268ba29b476d8db8874191c7519478a64fd9992bf9973015edcffcce/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f646570656e64656e636965732d312d627269676874677265656e)](https://github.com/rancoud/model/blob/master/composer.json)[![Test workflow](https://camo.githubusercontent.com/2ddd2a7703f792531fe4da7702f838a24c0bd5578da17a3965c42db4a21dfdc0/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f72616e636f75642f6d6f64656c2f746573742e796d6c3f6272616e63683d6d6173746572)](https://github.com/rancoud/model/actions/workflows/test.yml)[![Codecov](https://camo.githubusercontent.com/c6fae01bf5dac3f7ffd94df479780bd160bbdf441f61771ed38176608a58fdc0/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f72616e636f75642f6d6f64656c3f6c6f676f3d636f6465636f76)](https://codecov.io/gh/rancoud/model)

Abstract Model for better data manipulation between code and database.

Dependencies
------------

[](#dependencies)

Database package:

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

[](#installation)

```
composer require rancoud/model
```

How to use it?
--------------

[](#how-to-use-it)

Extends Rancoud\\Model\\Model to your class.
You have to implement two abstract methods setFields and setTable.

- setFields is for setting the fields in table
- setTable is for setting the table in database

```
class User extends Model
{
    protected function setFields(): void
    {
        $this->fields = [
            'id'       => new Field('int', ['not_null', 'unsigned', 'pk']),
            'nickname' => new Field('varchar', ['max:255', 'not_null'])
        ];
    }

    protected function setTable(): void
    {
        $this->table = 'user';
    }
}
```

### What is Field?

[](#what-is-field)

Field represent a field in the table.
It have 3 arguments:

1. field type
2. rules
3. default value

#### Field type

[](#field-type)

It support those field type

- int
- float
- char
- varchar
- text
- date
- datetime
- time
- timestamp
- year
- enum:x,y,z (x,y,z represent each possible value)

#### Rules

[](#rules)

- pk : primary key
- fk : foreign key
- unsigned : only positive value
- email : check if it is valid email
- not\_null : can't be null
- max:x : max size (x is size)
- min:x : min size (x is size)
- range:x,y : min size + max size (x is min size, y is max size)

#### Custom rule

[](#custom-rule)

```
class MyRule extends CustomRule
{
    public function applyRule($value)
    {
        if ($value === 'azerty') {
            throw new FieldException('invalid azerty value');
        }

        return $value;
    }
}
```

#### Default

[](#default)

When value is not setted it can be set with those argument

### Helpers

[](#helpers)

It have methods for pagination, create, read, update and delete.

```
// $database is an instance of Rancoud\Database\Database
$user = new User($database);

$newId = $user->create(['nickname' => 'rancoud']);

$row = $user->one($newId);
// you will have an array representing data in database with correct types
// here : ['id' => 1, 'nickname' => 'rancoud'];
$rows = $user->all();
// here it's all rows in table : [ ['id' => 1, 'nickname' => 'rancoud'] ]

$user->update(['nickname' => 'rancoud2'], $newId);

$user->delete($newId);
```

Model::all() accept an array with some keys that triggers specific actions

```
// $database is an instance of Rancoud\Database\Database
$user = new User($database);

// 50 rows using LIMIT 50 OFFSET 50
$rows = $user->all(['page' => 1]);
// 10 rows using LIMIT 10 OFFSET 10
$rows = $user->all(['count' => 10, 'page' => 1]);

// count rows in table
$count = $user->all(['rows_count' => 1]);

// return all rows with no limit
$count = $user->all(['no_limit' => 1]);

// change order by
$count = $user->all(['order' => 'nickname']);
// change order by and order
$count = $user->all(['order' => 'nickname|desc']);
// multiple change order by and order
$count = $user->all(['order' => 'nickname|desc,id|asc']);
```

You can change values output in Model::all() with override functions:

- getSqlAllSelectAndFillSqlParams(params: array)
- getSqlAllJoinAndFillSqlParams(params: array)
- getSqlAllWhereAndFillSqlParams(params: array)

Callbacks
---------

[](#callbacks)

You can add callback before and after create, update and delete.

```
$model->addBeforeCreate('a', function($sql, $params){
    // for modifying sql and params use this return otherwise don't
    return [$sql, $params];
});

$model->addAfterCreate('a', function($newId, $params){
    // for modifying params use this return otherwise don't
    return $params;
});

$model->addBeforeUpdate('a', function($sql, $params){
    // for modifying sql and params use this return otherwise don't
    return [$sql, $params];
});

$model->addAfterUpdate('a', function($params){
    // for modifying params use this return otherwise don't
    return $params;
});

$model->addBeforeDelete('a', function($sql, $params){
    // for modifying sql and params use this return otherwise don't
    return [$sql, $params];
});

$model->addAfterDelete('a', function($params){
    // for modifying params use this return otherwise don't
    return $params;
});
```

You can use JsonOutput trait for adding json format for the model.

Field Constructor
-----------------

[](#field-constructor)

### Settings

[](#settings)

#### Mandatory

[](#mandatory)

ParameterTypeDescriptiontypestringtype of field, values used : int | float | char | varchar | text | date | datetime | time | timestamp | year#### Optionnals

[](#optionnals)

ParameterTypeDefault valueDescriptionrulesarray\[\]rules for checking values, values used : pk | fk | unsigned | email | not\_null | max | min | range | Rancoud\\Model\\CustomRuledefaultmixedfalsedefault value when none givenField Methods
-------------

[](#field-methods)

- isPrimaryKey(): bool
- isForeignKey(): bool
- isNotNull(): bool
- getDefault(): mixed
- formatValue(value: mixed): ?mixed

Model Constructor
-----------------

[](#model-constructor)

### Settings

[](#settings-1)

#### Mandatory

[](#mandatory-1)

ParameterTypeDescription$database\\Rancoud\\Database\\DatabaseDatabase InstanceModel Methods
-------------

[](#model-methods)

### General Commands

[](#general-commands)

- all(params: array, \[validFields: array = \[\]\]): array|bool|int
- one(id: mixed, \[...ids: mixed = \[\]\]): array
- create(args: array): bool|int
- update(args: array, id: mixed, \[...ids: mixed = \[\]\]): void
- delete(id: mixed, \[...ids: mixed = \[\]\]): void
- getLastInsertId(): ?int

### Database error

[](#database-error)

- getDatabaseErrors(): ?array
- getDatabaseLastError(): ?array

### Callbacks

[](#callbacks-1)

#### Add

[](#add)

- addBeforeCreate(name: string, callback: mixed): void
- addAfterCreate(name: string, callback: mixed): void
- addBeforeUpdate(name: string, callback: mixed): void
- addAfterUpdate(name: string, callback: mixed): void
- addBeforeDelete(name: string, callback: mixed): void
- addAfterDelete(name: string, callback: mixed): void

#### Remove

[](#remove)

- removeBeforeCreate(name: string): void
- removeAfterCreate(name: string): void
- removeBeforeUpdate(name: string): void
- removeAfterUpdate(name: string): void
- removeBeforeDelete(name: string): void
- removeAfterDelete(name: string): void

Static Helper Methods
---------------------

[](#static-helper-methods)

- getCountPerPage(args: array): int
- getLimitOffsetCount(args: array): array
- getOrderByOrderField(args: array, \[validFields: array = \[\]\]): array
- getPageNumberForHuman(args: array): int
- getPageNumberForSql(args: array): int
- hasInvalidPrimaryKey(value: int): bool
- hasLimit(args: array): bool
- implodeOrder(orders: array): string
- isRowsCount(args: array): bool
- isValidFieldForOrderBy(field: string, \[validFields: array = \[\]\]): bool

How to Dev
----------

[](#how-to-dev)

`docker compose build && docker compose run lib composer ci` for launching tests

###  Health Score

59

—

FairBetter than 99% of packages

Maintenance90

Actively maintained with recent releases

Popularity28

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity90

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 78.8% 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 ~107 days

Recently: every ~119 days

Total

27

Last Release

51d ago

Major Versions

1.1.3 → 2.0.02019-02-02

2.0.1 → 3.0.02020-07-11

3.0.0 → 4.0.02020-07-25

4.3.0 → 5.0.02025-04-20

PHP version history (3 changes)1.0.0PHP &gt;=7.2.0

3.0.0PHP &gt;=7.4.0

5.0.0PHP &gt;=8.4.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/829a536bd4f71cadcd0266e272ccaf413e3fc9f2937248c9a2317ef0bf2d25ee?d=identicon)[rancoud](/maintainers/rancoud)

---

Top Contributors

[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (241 commits)")[![rancoud](https://avatars.githubusercontent.com/u/1884186?v=4)](https://github.com/rancoud "rancoud (65 commits)")

---

Tags

composercoveragedatabasemodelmodelspackagistpdophpphp7php8phpunitsql

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/rancoud-model/health.svg)

```
[![Health](https://phpackages.com/badges/rancoud-model/health.svg)](https://phpackages.com/packages/rancoud-model)
```

###  Alternatives

[phpspec/prophecy

Highly opinionated mocking framework for PHP 5.3+

8.5k551.7M682](/packages/phpspec-prophecy)[brianium/paratest

Parallel testing for PHP

2.5k118.8M754](/packages/brianium-paratest)[beberlei/assert

Thin assertion library for input validation in business models.

2.4k96.9M570](/packages/beberlei-assert)[mikey179/vfsstream

Virtual file system to mock the real file system in unit tests.

1.4k108.0M2.7k](/packages/mikey179-vfsstream)[orchestra/testbench

Laravel Testing Helper for Packages Development

2.2k39.1M32.1k](/packages/orchestra-testbench)[phpspec/phpspec

Specification-oriented BDD framework for PHP 7.1+

1.9k36.7M3.1k](/packages/phpspec-phpspec)

PHPackages © 2026

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