PHPackages                             imsamurai/active-record-for-cakephp - 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. imsamurai/active-record-for-cakephp

ActiveCakephp-plugin[Database &amp; ORM](/categories/database)

imsamurai/active-record-for-cakephp
===================================

Implementation of active record for CakePHP

1.3.1(11y ago)2231[5 issues](https://github.com/imsamurai/active-record-for-cakephp/issues)MITPHP

Since Jan 23Pushed 10y ago3 watchersCompare

[ Source](https://github.com/imsamurai/active-record-for-cakephp)[ Packagist](https://packagist.org/packages/imsamurai/active-record-for-cakephp)[ Docs](http://github.com/imsamurai/active-record-for-cakephp)[ RSS](/packages/imsamurai-active-record-for-cakephp/feed)WikiDiscussions master Synced 2mo ago

READMEChangelogDependencies (1)Versions (20)Used By (0)

Active Record for CakePHP
=========================

[](#active-record-for-cakephp)

[![Build Status](https://camo.githubusercontent.com/54abaf53c3ad95ed299914502cb9ec6ec621c9a144d485ab2f10944dd8343efd/68747470733a2f2f7472617669732d63692e6f72672f696d73616d757261692f6163746976652d7265636f72642d666f722d63616b657068702e706e67)](https://travis-ci.org/imsamurai/active-record-for-cakephp) [![Coverage Status](https://camo.githubusercontent.com/11a98e65fa75d5ba453456c3a56c058a8253e92e88827f4d250f803d21b94d12/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f696d73616d757261692f6163746976652d7265636f72642d666f722d63616b657068702f62616467652e706e673f6272616e63683d6d6173746572)](https://coveralls.io/r/imsamurai/active-record-for-cakephp?branch=master) [![Latest Stable Version](https://camo.githubusercontent.com/3201952506b9028360dc8b642c7daff9582a8d5387e92aa3274a3512aa84a7b1/68747470733a2f2f706f7365722e707567782e6f72672f696d73616d757261692f6163746976652d7265636f72642d666f722d63616b657068702f762f737461626c652e706e67)](https://packagist.org/packages/imsamurai/active-record-for-cakephp) [![Total Downloads](https://camo.githubusercontent.com/8a8aac87134342ff2dca3a82aea3c1bcbd387433967969bb6bba37ef072712dc/68747470733a2f2f706f7365722e707567782e6f72672f696d73616d757261692f6163746976652d7265636f72642d666f722d63616b657068702f646f776e6c6f6164732e706e67)](https://packagist.org/packages/imsamurai/active-record-for-cakephp) [![Latest Unstable Version](https://camo.githubusercontent.com/fcdc404eff5bbb698d3e40b76171017342a1a626d64ef54056645c1dad47ef4b/68747470733a2f2f706f7365722e707567782e6f72672f696d73616d757261692f6163746976652d7265636f72642d666f722d63616b657068702f762f756e737461626c652e706e67)](https://packagist.org/packages/imsamurai/active-record-for-cakephp) [![License](https://camo.githubusercontent.com/d49b8e0082ff9aa0cae234f7dfe07bfcaf2aa880a25119bcdffbaed6765b9f6a/68747470733a2f2f706f7365722e707567782e6f72672f696d73616d757261692f6163746976652d7265636f72642d666f722d63616b657068702f6c6963656e73652e706e67)](https://packagist.org/packages/imsamurai/active-record-for-cakephp)

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

[](#installation)

I wanted to build a state engine with CakePHP, and I realize that I needed a kind of Active Record pattern. So I first built a behavior that allows me to retrieve objects in place of associative arrays.

I have tested this only with cakePHP 2.3.x, 2.4.x

Composer (for ex. version 1.0.0):

```
{
	"require": {
		"imsamurai/active-record-for-cakephp": "1.0.0"
	}
}
```

it installs in `Plugin` directory (in same level with composer.json) so you may want to add `Plugin/Task` into ignore file.

or clone:

```
cd my_cake_app/app
git clone git://github.com/imsamurai/active-record-for-cakephp.git Plugin/ActiveRecord

```

or if you use git add as submodule:

```
cd my_cake_app
git submodule add "git://github.com/imsamurai/active-record-for-cakephp.git" "app/Plugin/ActiveRecord"

```

then add plugin loading in Config/bootstrap.php

```
CakePlugin::load('ActiveRecord', array('bootstrap' => true, 'routes' => false));

```

To use it:

- Tell your model to use it: $actsAs = array('ActiveRecord' =&gt; array())
- When you use a find('all') or find('first) function, add the option 'activeRecord' =&gt; true

I chose this way, because I did not want to retrieve always objects when a find function was called. But it is possible to use it in another way: add in the constructor of the behavior the option 'allFind' =&gt; true, and if you do not want an object after a find add 'activeRecord' =&gt; false (this possibility was not yet thouroughly tested: i'm afraid that cake generates sometimes a 'find' call that needs associative arrays).

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

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

When you retrieve an object record, you can use it in this way: assume that you have the following models:

- Post (title, message) belongsTo Writer, hasMany Comments, hasAndBelongsToMany Tags
- Writer (name) hasMany Posts, belongsTo WriterGroup
- WriterGroup (name) hasMany Writers
- Comment (message) belongsTo Post
- Tag (name) hasAndBelongsToMany Posts

Call find('first') of find('all') to retrieve the posts and with one post you can do the following:

- $message = $post-&gt;message : this retrieves the message of the post
- $post-&gt;message = 'Hallo' : this updates the message of the post
- $writer = $post-&gt;Writer : this retrieves the writer ActiveRecord object
- $comments = $post-&gt;Comments : this retrieves the ActiveRecordAssociation object

The Behavior makes a difference between belongsTo/hasOne associations and hasMany/hasAndBelongsToMany associations:

- with belongsTo and hasOne associations, the ActiveRecord object pointed by the association is retrieved, and you can use it directly: e.g. $post-&gt;Writer-&gt;WriterGroup-&gt;name
- with hasMany and hasAndBelongsToMany associations, the ActiveRecordAssociation object is retrieved. The class of this object implements the IteratorAggregate, Countable and ArrayAccess interfaces so that you can use it as an array:

    - foreach ($post-&gt;Comments as $comment) {}
    - count($post-&gt;Comments);
    - $comments = $post-&gt;Comments; $first\_comment = $comments\[0\];

But also, the ActiveRecordAssociation class has 3 functions:

- $comments-&gt;add($new\_comment);
- $comments-&gt;remove($first\_comment);
- $comments-&gt;replace($first\_comment, $new\_comment);

In order for the developer to clearly see the difference beween the 2 kinds of associations, I advice to use a plural name for hasMany and hasAndBelongsToMany associations, and singular name for hasOne and belongsTo associations.

Extend ActiveRecord class
-------------------------

[](#extend-activerecord-class)

Per default, the object you retrieve is of the class ActiveRecord. But you can of course extend this class for one model. Per default, the behavior will look for a class in the subfolder Model/ActiveRecord with name 'AR', e.g.: ARPost or ARComment (the prefix 'AR' and the subfolder name can be changed in the bahavior constructor options). In the file ARPost.php:

```

```

If you need to use the constructor:

```
public function __construct(array $record, array $options = array()) {
   parent::__construct($record, $options);
   ...
}

```

Then you can use $post-&gt;var and $post-&gt;func() in your code. You can also create new object:

```
$post = new ARPost(array(
   'title' => 'My title',
   'message' => 'OK',
   'Writer' => $writer));

```

Here it becomes to be quite nice: in place of telling that the writer\_id of the post should be `$writer->id`, you can directly say `'Writer' => $writer`You can also do:

```
$post->Comments = array($comment);

```

This will set automatically the `$comment->post_id` to the right one.

Useful functions
----------------

[](#useful-functions)

I realize that when using hasMany (or hasOne association), when you do

```
$post->Comments->remove($comment);

```

or

```
$post->Comments = null;

```

You want not only to remove the $comment from $post, but most of the time you want to delete $comment. I thought it would be quite handy if this is done automatically. For this, if you set in the association definition 'deleteWhenNotAssociated' to true, the behavior will automatically delete all records that are removed from the association.

The behavior offers also the possibility to delete, refresh and undo an ActiveRecord:

```
$post->delete(); // delete this post record
$post->refresh(); // query the values of post in the database.
$post->undo(); // undo all modification done in the $post record.

```

The modifications done in the active records are not sent to the database. This is done only when calling the save() method. But $post-&gt;save() will only save the modification in the post record, not in its associated records. To save all modifications you made (explicitely and implicitely), use $post-&gt;saveAll() or ActiveRecord::saveAll() method Morevover saveAll() takes care that the records are saved in the right order. For example:

```
$comment = new ARComment(array('message' => 'New message'));
$post = new ARPost(array('title' => 'New title', 'message' => 'New Message', 'Writer' => $writer));
$post->Comment = array($comment);
ActiveRecord::saveAll();

```

Then saveAll() takes care that $post is created first so that its id can be set to $comment-&gt;post\_id.

What is really nice with this Active Record pattern, is that you don't need anymore to bother about the keys and how you should construct the associated arrays to be sure that cakePHP will save correctly your data (especially with hasAndBelongsToMany associations!)

Extending even more
-------------------

[](#extending-even-more)

I needed also a possiblility to have subclasses of ActiveRecord. For example I had an Action model, but I needed to define subclasses for each kind of action. A subclass action may use a (sub) model or not. For this I told the behavior to check whether the Model has the function getActiveRecordProperties(), and if yes it calls it before it builds a new ActiveRecord. This function tells the behavior what is the real ActiveAction name it must call, with which model and with which data. Here an example:

My model Action has a column type. This column will determine which kind of ActiveRecord class it must call. Then in the Action model, I have added this function:

```
public function getActiveRecordProperties(&$record) {
  $type = $record[$this->alias]['type'];
  $name = 'AR' . $type . 'Action';
  $model = $this;
  App::import('Model'.DS.'ActiveRecord', $name);
  return array('name' => $name, 'Record' => $record, 'Model' => $model);
}

```

My ARAction looks like this:

```
abstract class ARAction extends AppActiveRecord {
    abstract public function execute(ARUserState $user_state, $parameter);
}

```

The SendEmail subaction looks like that:

```
class ARSendEmailAction extends ARAction {
   public function execute(ARUserState $user_state, $parameter) {
       ....
   }
}

```

Then if I have a record in my Action table with type 'SendEmail', Action-&gt;find() returns an object of Class ARSendEmailAction. When calling execute(), it will call the right one that will send an email. Here the ARSendEmailAction uses the same model as ARAction, but if needed I could have set it to another one.

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance0

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity72

Established project with proven stability

 Bus Factor1

Top contributor holds 70.4% 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 ~9 days

Recently: every ~3 days

Total

19

Last Release

4322d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/ab9b1bb43e8563f1ff3fd78cb0bf0b28b55026a9f792f2b26aefae882e1512d2?d=identicon)[imsamurai](/maintainers/imsamurai)

---

Top Contributors

[![imsamurai](https://avatars.githubusercontent.com/u/843002?v=4)](https://github.com/imsamurai "imsamurai (95 commits)")[![boutinb](https://avatars.githubusercontent.com/u/503332?v=4)](https://github.com/boutinb "boutinb (34 commits)")[![skalmi](https://avatars.githubusercontent.com/u/752442?v=4)](https://github.com/skalmi "skalmi (6 commits)")

---

Tags

plugindatabasecakephpactive-record

### Embed Badge

![Health badge](/badges/imsamurai-active-record-for-cakephp/health.svg)

```
[![Health](https://phpackages.com/badges/imsamurai-active-record-for-cakephp/health.svg)](https://phpackages.com/packages/imsamurai-active-record-for-cakephp)
```

###  Alternatives

[dereuromark/cakephp-databaselog

A CakePHP plugin for storing and viewing application logs in the database

44165.0k2](/packages/dereuromark-cakephp-databaselog)[pixelstudio/wp-sync-db

WordPress plugin to sync database between different installs

472.5k1](/packages/pixelstudio-wp-sync-db)[imsamurai/cakephp-serializable-behaviour

Behavior for saving and reading serialized data from/into database

147.7k3](/packages/imsamurai-cakephp-serializable-behaviour)[flightphp/active-record

Micro Active Record library in PHP, support chain calls, events, and relations.

163.0k](/packages/flightphp-active-record)

PHPackages © 2026

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