ristocloud-group/php-activerecord

php-activerecord is an open source ORM library based on the ActiveRecord pattern.

Maintainers

Package info

github.com/ristocloud-group/php-activerecord

pkg:composer/ristocloud-group/php-activerecord

Transparency log

Statistics

Installs: 2

Dependents: 0

Suggesters: 0

Stars: 0

2.0.0 2026-07-31 14:31 UTC

README

CI

This is a fork maintained by Ristocloud Group S.r.l.

It is based on zamzar/php-activerecord (itself a fork of the original jpfuentes2/php-activerecord). We vendor it into our own applications and maintain it — fixing bugs and keeping it running on modern PHP and database versions. It is not affiliated with, nor endorsed by, the original authors.

Originally created by:

Upstream documentation: http://www.phpactiverecord.org/

Introduction

A brief summarization of what ActiveRecord is:

Active record is an approach to access data in a database. A database table or view is wrapped into a class, thus an object instance is tied to a single row in the table. After creation of an object, a new row is added to the table upon save. Any object loaded gets its information from the database; when an object is updated, the corresponding row in the table is also updated. The wrapper class implements accessor methods or properties for each column in the table or view.

More details can be found here.

This implementation is inspired and thus borrows heavily from Ruby on Rails' ActiveRecord. We have tried to maintain their conventions while deviating mainly because of convenience or necessity. Of course, there are some differences which will be obvious to the user if they are familiar with rails.

Minimum Requirements

  • PHP 8.3+ (tested on PHP 8.3, 8.4 and 8.5)
  • PDO driver for your respective database

Supported Databases

  • MySQL — the primary production target. Supported minimum: MySQL 8+.
  • MariaDB — supported minimum: MariaDB 10.11+.
  • PostgreSQL
  • SQLite

These are policy minimums; composer.json carries no database-version constraint. Continuous integration runs the full test suite across PHP 8.3, 8.4 and 8.5 against MySQL 9.7, MariaDB 11.4, PostgreSQL 18 and SQLite. The Oracle (oci) adapter was removed in v1.8.0.

Features

  • Finder methods
  • Dynamic finder methods
  • Writer methods
  • Relationships
  • Validations
  • Callbacks
  • Serializations (json/xml)
  • Transactions
  • Support for multiple adapters
  • Miscellaneous options such as: aliased/protected/accessible attributes

Installation

This fork is not published on Packagist. Install it with Composer from its Git repository — add a VCS repository to your composer.json and require the package by its name (ristocloud-group/php-activerecord):

{
    "repositories": [
        { "type": "vcs", "url": "https://github.com/ristocloud-group/php-activerecord" }
    ],
    "require": {
        "ristocloud-group/php-activerecord": "dev-master"
    }
}

Setup is very easy and straight-forward. There are essentially only two configuration points you must concern yourself with:

  1. Configuring your database connections.
  2. Setting the database connection to use for your environment.

Example:

ActiveRecord\Config::initialize(function (ActiveRecord\Config $cfg) {
    $cfg->set_connections([
        'development' => 'mysql://username:password@localhost/development_database_name',
        'test' => 'mysql://username:password@localhost/test_database_name',
        'production' => 'mysql://username:password@localhost/production_database_name',
    ]);
});

Alternatively (without a closure):

$cfg = ActiveRecord\Config::instance();
$cfg->set_connections([
    'development' => 'mysql://username:password@localhost/development_database_name',
    'test' => 'mysql://username:password@localhost/test_database_name',
    'production' => 'mysql://username:password@localhost/production_database_name',
]);

MariaDB uses the same mysql:// connection scheme (and the MySQL adapter) as MySQL.

PHP ActiveRecord will default to use your development database. For testing or production, you simply set the default connection according to your current environment ('test' or 'production'):

ActiveRecord\Config::initialize(function (ActiveRecord\Config $cfg) {
    $cfg->set_default_connection('production'); // 'development', 'test', or 'production'
});

Once you have configured these settings you are done. ActiveRecord takes care of the rest for you. It does not require that you map your table schema to yaml/xml files. It will query the database for this information and cache it so that it does not make multiple calls to the database for a single schema.

Optional: caching the schema

php-activerecord introspects each table's schema (columns, types, primary key) from the database. Within a single request this is kept in memory, but PHP's shared-nothing model means it is re-introspected on every request. To persist it across requests, configure an external cache. Three backends are bundled:

Memcached — requires the memcached PHP extension:

$cfg->set_cache('memcache://localhost:11211', ['expire' => 120, 'namespace' => 'my_app']);

File — a filesystem cache (added by this fork for hosts without memcached); no extension required:

$cfg->set_cache('file:///var/tmp/php-activerecord-cache');

The file backend stores one serialized file per cache key inside the directory you pass (creating the directory if it does not exist), and reads it back with unserialize().

The file backend also honors the expire option: each entry stores an expiry timestamp and is treated as a miss once it lapses (deleted lazily on the next read). Writes are atomic (temp file + rename). Behavior change: because the default expire is 30 seconds, file entries that previously persisted forever now expire after 30s by default — pass ['expire' => 0] to keep entries until you flush() them. Files written by older versions are treated as a miss and regenerated, so no manual purge is needed when upgrading.

Redis — requires the predis/predis Composer package (composer require predis/predis); no PHP extension needed:

$cfg->set_cache('redis://localhost:6379/0', ['expire' => 120, 'namespace' => 'my_app']);

Connection parameters are taken from the DSN, including its query string, so any Predis connection parameter is reachable — e.g. TLS and tuning:

$cfg->set_cache('redis://user:secret@redis.example.com:6379/0?read_write_timeout=2', [
    'namespace' => 'my_app',
]);

The same redis:// DSN targets Redis 6/7/8 and Valkey 7/8/9 interchangeably; the adapter is exercised against all six in CI. Values are serialized on write and unserialized on read. ActiveRecord\Cache::flush() deletes only the keys under the configured namespace (via SCAN/DEL); with no namespace it falls back to FLUSHDB, which clears the whole selected Redis database — set a namespace when the Redis instance is shared. Do not pass a Predis prefix client option for key isolation: Predis does not apply prefix to the plain SCAN command that namespace-scoped flush() relies on, so keys end up stored under prefix + key while flush() only matches namespace::*, silently deleting nothing — use the namespace option instead, which flush() already understands.

ActiveRecord\Cache::flush() invalidates the cache for any backend (for the file cache it deletes the cached files) — for example after running a schema migration. All backends accept a namespace option that prefixes every cache key, useful when several applications share one cache store.

The cache is lock-free: at each expiry, concurrent requests all recompute the cached value once (a brief stampede). For very hot deployments raise expire (or set it to 0). Prefer a local filesystem for the file backend — TTLs rely on the host clock, so shared storage (NFS) across clock-skewed hosts can expire entries early or late.

Backend Requirement TTL (expire) Persistence Namespace / flush Concurrency Best for
Memcached memcached PHP extension Yes (server-side) In-memory, evictable namespace prefix; flush() clears the whole server Atomic server-side TTL Existing memcached infra
File none Yes (since this fork) On disk until expiry/flush namespace prefix; flush() deletes files Lock-free; atomic writes, lazy GC, local-FS assumption Single host, no extra services
Redis / Valkey predis/predis package Yes (server-side) In-memory (optionally persisted by the server) namespace-scoped SCAN/DEL, else FLUSHDB Atomic server-side TTL Shared/networked cache, HA

Basic CRUD

Retrieve

These are your basic methods to find and retrieve records from your database. See the Finders section for more details.

$post = Post::find(1);
echo $post->title; # 'My first blog post!!'
echo $post->author_id; # 5

# also the same since it is the first record in the db
$post = Post::first();

# finding using dynamic finders
$post = Post::find_by_name('The Decider');
$post = Post::find_by_name_and_id('The Bridge Builder',100);
$post = Post::find_by_name_or_id('The Bridge Builder',100);

# finding using a conditions array
$posts = Post::find('all', ['conditions' => ['name=? or id > ?', 'The Bridge Builder', 100]]);

Create

Here we create a new post by instantiating a new object and then invoking the save() method.

$post = new Post();
$post->title = 'My first blog post!!';
$post->author_id = 5;
$post->save();
# INSERT INTO `posts` (title,author_id) VALUES('My first blog post!!', 5)

Update

To update you would just need to find a record first and then change one of its attributes. It keeps an array of attributes that are "dirty" (that have been modified) and so our sql will only update the fields modified.

$post = Post::find(1);
echo $post->title; # 'My first blog post!!'
$post->title = 'Some real title';
$post->save();
# UPDATE `posts` SET title='Some real title' WHERE id=1

$post->title = 'New real title';
$post->author_id = 1;
$post->save();
# UPDATE `posts` SET title='New real title', author_id=1 WHERE id=1

Delete

Deleting a record will not destroy the object. This means that it will call sql to delete the record in your database but you can still use the object if you need to.

$post = Post::find(1);
$post->delete();
# DELETE FROM `posts` WHERE id=1
echo $post->title; # 'New real title'

Upsert

Model::upsert() inserts or updates many rows in one atomic, bulk operation (modeled on Laravel Eloquent). It bypasses validations, callbacks and dirty-tracking. The second argument names the column(s) that identify a record; the optional third argument lists the columns to overwrite on conflict (all inserted columns except created_at when omitted). created_at/updated_at are managed automatically when those columns exist; if the table has updated_at, it is appended to the update list automatically whenever an update happens, even if you didn't list it in the third argument.

Flight::upsert([
    ['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99],
    ['departure' => 'Chicago', 'destination' => 'New York', 'price' => 150],
], unique_by: ['departure', 'destination'], update: ['price']);
# The `flights` table has an `updated_at` column, so it is appended to the
# update list automatically even though only `price` was requested:
# MySQL/MariaDB: INSERT ... VALUES (...),(...) ON DUPLICATE KEY UPDATE `price` = VALUES(`price`), `updated_at` = VALUES(`updated_at`)
# Postgres:      INSERT ... VALUES (...),(...) ON CONFLICT ("departure", "destination") DO UPDATE SET "price" = EXCLUDED."price", "updated_at" = EXCLUDED."updated_at"
# SQLite uses the same ON CONFLICT ... EXCLUDED form as Postgres, with identifiers quoted in backticks.

On MySQL/MariaDB the unique_by columns are ignored and the table's PRIMARY/UNIQUE indexes are used. Large batches are chunked automatically and run inside a transaction. A full runnable example lives in examples/upsert/.

Contributing

Please refer to CONTRIBUTING.md for information on how to contribute to this fork.

License

MIT — see LICENSE.