Anorm Another ORM logo Anorm Another ORM

Anorm is yet Another ORM for PHP from SayGoWeb.

Check it out on GitHub.

Connecting

$anorm = Anorm::connect('mydata', 'mysql:host=localhost;dbname=some_db', 'user', 'password');

then having connected you can fetch a reference to the connection with use.

$anorm = Anorm::use('mydata');

Create and Update

Step 1. Define a model class

use Anorm\DataMapper;
use Anorm\Model;

class SomeTableModel extends Model {
    public function __construct(Anorm $anorm)
    {
        parent::__construct($anorm->pdo, DataMapper::createByClass($anorm->pdo, $this));
        // Development only: lets Anorm create and alter tables to match the model.
        // Types are inferred from values and are a best guess — dump and correct the
        // schema, then remove this line, before production. See 'Schema modes'.
        $this->mapper()->mode = DataMapper::MODE_DYNAMIC;
    }

    /** @var integer The primary key */
    public $id;

    /** @var string Useful documentation about 'name' for intellisense */
    public $name;

}

Step 2. Use it to create a record in the database.

$model = new SomeTableModel(Anorm::use('mydata'));
$model->name = 'bob';
$model->write();

Find Many

$anorm = Anorm::use('mydata');
$data = DataMapper::find('SomeTableModel', $anorm->pdo)
    ->orderBy("name")
    ->limit(3)
    ->some();
foreach ($data as $model) {
    // ...
}

Find One

$anorm = Anorm::use('mydata');
$model = DataMapper::find('SomeTableModel', $anorm->pdo)
    ->where("`name`='Name 1'")
    ->one();

Delete

$id = 3; // Likely passed on via GET or POST
$model = new SomeTableModel(Anorm::use('mydata'));
$model->id = $id;
$model->delete();

deleteOrThrow() is the same thing but throws when no row matched.