PHPackages                             corneltek/lazyrecord - 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. corneltek/lazyrecord

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

corneltek/lazyrecord
====================

The Fast PHP ORM

3.4.2(9y ago)93.6k2MITPHPPHP &gt;=5.4.0

Since Aug 29Pushed 9y agoCompare

[ Source](https://github.com/corneltek/LazyRecord)[ Packagist](https://packagist.org/packages/corneltek/lazyrecord)[ Docs](https://github.com/c9s/LazyRecord)[ RSS](/packages/corneltek-lazyrecord/feed)WikiDiscussions master Synced 3w ago

READMEChangelogDependencies (13)Versions (94)Used By (2)

LazyRecord
==========

[](#lazyrecord)

[![](https://camo.githubusercontent.com/a897726d48dd3bc4f72ae309d315a6a232a4be721051f35b2db8b81e0f899318/68747470733a2f2f7261772e6769746875622e636f6d2f636f726e656c74656b2f4c617a795265636f72642f6d61737465722f6173736574732f696d616765732f6c6f676f2e706e67)](https://camo.githubusercontent.com/a897726d48dd3bc4f72ae309d315a6a232a4be721051f35b2db8b81e0f899318/68747470733a2f2f7261772e6769746875622e636f6d2f636f726e656c74656b2f4c617a795265636f72642f6d61737465722f6173736574732f696d616765732f6c6f676f2e706e67)

[![works badge](https://camo.githubusercontent.com/71c24a0850c0404418232a97a1a7e217d4d6377b7de352c76edb8e88458b7878/68747470733a2f2f63646e2e7261776769742e636f6d2f6e696b6b752f776f726b732d6f6e2d6d792d6d616368696e652f76302e322e302f62616467652e737667)](https://github.com/nikku/works-on-my-machine)[![Build Status](https://camo.githubusercontent.com/2425e66c9a85a07fae19a1c6f2fe7cb36fd951e84fd2f03f55d7b1eaec7ea986/68747470733a2f2f7472617669732d63692e6f72672f636f726e656c74656b2f4c617a795265636f72642e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/corneltek/LazyRecord)[![Coverage Status](https://camo.githubusercontent.com/f86f21b6734857309499064e5991864824c5f867209ada7d20aa9e37dc50a657/68747470733a2f2f696d672e736869656c64732e696f2f636f766572616c6c732f636f726e656c74656b2f4c617a795265636f72642e737667)](https://coveralls.io/r/corneltek/LazyRecord)[![Latest Stable Version](https://camo.githubusercontent.com/dfd0abe7bec93907c0c0aecd88550fbca950440386f9b4b877e2ea1d91034294/68747470733a2f2f706f7365722e707567782e6f72672f636f726e656c74656b2f6c617a797265636f72642f762f737461626c652e737667)](https://packagist.org/packages/corneltek/lazyrecord)[![Total Downloads](https://camo.githubusercontent.com/82e5ff3bc0f8d3a8e4294d7ab23a89f6e829d03c64a87c39f338f257c2f0088b/68747470733a2f2f706f7365722e707567782e6f72672f636f726e656c74656b2f6c617a797265636f72642f646f776e6c6f6164732e737667)](https://packagist.org/packages/corneltek/lazyrecord)[![Monthly Downloads](https://camo.githubusercontent.com/f508fc18b6558bebe128516635736d12a3f37c840c167141ca345f964741f328/68747470733a2f2f706f7365722e707567782e6f72672f636f726e656c74656b2f6c617a797265636f72642f642f6d6f6e74686c79)](https://packagist.org/packages/corneltek/lazyrecord)[![Daily Downloads](https://camo.githubusercontent.com/bca45e57855665ed4f66301b13976d2b19f17437889cabd9eefd5ceda9ab9692/68747470733a2f2f706f7365722e707567782e6f72672f636f726e656c74656b2f6c617a797265636f72642f642f6461696c79)](https://packagist.org/packages/corneltek/lazyrecord)[![Latest Unstable Version](https://camo.githubusercontent.com/c8ca52d8cf793fdee709cc584bca2603c99c406067e60acd3fd5889b670dcad8/68747470733a2f2f706f7365722e707567782e6f72672f636f726e656c74656b2f6c617a797265636f72642f762f756e737461626c652e737667)](https://packagist.org/packages/corneltek/lazyrecord)[![License](https://camo.githubusercontent.com/330cac45c1dde9366a93784eb1aa0cd7b7d2f063c8a5746c2491488ac13ad671/68747470733a2f2f706f7365722e707567782e6f72672f636f726e656c74656b2f6c617a797265636f72642f6c6963656e73652e737667)](https://packagist.org/packages/corneltek/lazyrecord)[![Join the chat at https://gitter.im/c9s/LazyRecord](https://camo.githubusercontent.com/c1a41cd6ff9531bd2b8c2feb41e4ccc444fece7bb7923420027041989289bef7/68747470733a2f2f6261646765732e6769747465722e696d2f6339732f4c617a795265636f72642e737667)](https://gitter.im/c9s/LazyRecord?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

LazyRecord is an open-source Object-Relational Mapping (ORM) for PHP5.

LazyRecord uses code generator to generate static code, which reduces runtime costs, therefore it's pretty lightweight and fast.

It allows you to access your database very easily by using ActiveRecord pattern API.

LazyRecord is not like PropelORM, it doesn't use ugly XML as its schema or config file, LazyRecord uses simpler YAML format config file and it compiles YAML to pure PHP code to improve the performance of config loading.

With the simple schema design, you can define your model schema very easily and you can even embed closure in your schema classes.

See also

**[LazyRecord: The Fast ORM for PHP](http://www.slideshare.net/c9s/lazyrecord-the-fast-orm-for-php "LazyRecord: The Fast ORM for PHP")** &lt;iframe src="[http://www.slideshare.net/slideshow/embed\_code/12638921](http://www.slideshare.net/slideshow/embed_code/12638921)" width="425" height="355" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"&gt;&lt;/iframe&gt;  View more [presentations](http://www.slideshare.net/) from [Yo-An Lin](http://www.slideshare.net/c9s)

Automatic Migration Demonstration
---------------------------------

[](#automatic-migration-demonstration)

[![](https://camo.githubusercontent.com/ec6cdaba45422f16284918943ad682299e7957ce01469ad97e7bb7af901b2600/68747470733a2f2f7261772e6769746875622e636f6d2f6339732f4c617a795265636f72642f6d61737465722f6173736574732f696d616765732f6d6967726174696f6e2e676966)](https://camo.githubusercontent.com/ec6cdaba45422f16284918943ad682299e7957ce01469ad97e7bb7af901b2600/68747470733a2f2f7261772e6769746875622e636f6d2f6339732f4c617a795265636f72642f6d61737465722f6173736574732f696d616765732f6d6967726174696f6e2e676966)

Feature
-------

[](#feature)

- Fast &amp; Simple
- Configuration based on YAML format and compiled into PHP
- PDO, MySQL, Pgsql, SQLite support.
- Multiple data sources.
- Mix-in model.
- Powerful Migration Generator
    - Upgrade &amp; Downgrade of course.
    - Automatic Migration: generate migration SQL automatically based on the schema diff.
- Schema/Database diff

Design Concept
--------------

[](#design-concept)

- Function calls in PHP are very slow, so the model schema data will be built statically, LazyRecord converts all definitions (default value, validator, filter, valid value builder) into classes and static PHP array, this keeps these model classes very lightweight and fast.
- In the runtime, all the same model objects use the same schema object, and we can reuse the prebuild data from the static schema class.
- We keep base model class constructor empty, so when you are querying data from database, these model objects can be created with zero effort.

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

[](#installation)

Please see the details on [Wiki](https://github.com/c9s/LazyRecord/wiki)

Getting Started
---------------

[](#getting-started)

### Configuring Database

[](#configuring-database)

Change directory to your project, run `init` command to initialize your database settings.

```
composer require corneltek/lazyrecord "^3"
```

If you prefer something new, you can require "dev-master"

```
composer require corneltek/lazyrecord "dev-master"
```

Then create your config file:

```
$ vim db/config/database.yml
```

Suppose your application code is located in `src/` directory, then you should provide your schema path in following format:

```
---
bootstrap:
- vendor/autoload.php   # load the classloader from composer.
schema:
  auto_id: 1
  paths:
    - src/    # where you store the schema class files.
data_sources:
  default: master
  nodes:
    master:
      dsn: 'sqlite:test'
```

In the above config file, the `auto_id` means an id column with auto-increment integer primary key is automatically inserted into every schema class, so you don't need to declare an primary key id column in your every schema file.

### Writing Model Schema

[](#writing-model-schema)

Next, write your model schema file:

```
$ vim src/YourApp/Model/UserSchema.php
```

Put the content into your file:

```
namespace YourApp\Model;
use LazyRecord\Schema;

class UserSchema extends Schema
{
    public function schema()
    {
        $this->column('account')
            ->varchar(16);
        $this->column('password')
            ->varchar(40)
            ->filter('sha1');
    }
}
```

### Building Static Schema Files

[](#building-static-schema-files)

Then run `build-schema` command to build static schema files:

```
$ vendor/bin/lazy lazy schema build
Finding schemas...
Found schema classes
Initializing schema generator...
    YourApp\Model\UserSchemaProxy    => src/YourApp/Model/UserSchemaProxy.php
    YourApp\Model\UserCollectionBase => src/YourApp/Model/UserCollectionBase.php
    YourApp\Model\UserCollection     => src/YourApp/Model/UserCollection.php
    YourApp\Model\UserBase           => src/YourApp/Model/UserBase.php
    YourApp\Model\User               => src/YourApp/Model/User.php
Done
```

### Creating Database

[](#creating-database)

If you are using postgresql or mysql, you can create your database with `create-db` command:

```
$ php vendor/bin/lazy db create
```

### Building SQL From Model Schemas

[](#building-sql-from-model-schemas)

Now you need to build SQL schema into your database, simply run `build-sql`, `-d` is for debug mode, which prints all generated SQL statements:

```
$ php vendor/bin/lazy sql
Finding schema classes...
Initialize schema builder...
Building SQL for YourApp\Model\UserSchema
DROP TABLE IF EXISTS users;
CREATE TABLE users (
  account varchar(16),
  password varchar(40)
);

Setting migration timestamp to 1347439779
Done. 1 schema tables were generated into data source 'default'.
```

### Writing Application Code

[](#writing-application-code)

Now you can write your application code, But first you need to write your lazyrecord config loader code:

```
$ vim app.php

```

```
require 'vendor/autoload.php';
$config = new LazyRecord\ConfigLoader;
$config->load( __DIR__ . '/db/config/database.yml');
$config->init();
```

The `init` method initializes data sources to ConnectionManager, but it won't create connection unless you need to operate your models.

### Sample Code Of Operating The User Model Object

[](#sample-code-of-operating-the-user-model-object)

Now append your application code to the end of `app.php` file:

```
$user = new YourApp\Model\User;
$ret = $user->create(array('account' => 'guest', 'password' => '123123' ));
if ($ret->error ) {
    echo $ret->message;  // get the error message
    if ($ret->exception) {
        echo $ret->exception;  // get the exception object
    }
    echo $ret; // __toString() is supported
}
```

Please check `doc/` directory for more details.

Basic Usage
-----------

[](#basic-usage)

### Model Accessor

[](#model-accessor)

LazyRecord's BaseModel class provides a simple way to retrieve result data from the `__get` magic method, by using the magic method, you can retrieve the column value and objects from relationship.

```
$record = new MyApp\Model\User( 1 );   // select * from users where id = 1;
$record->name;    // get "users.name" and inflate it.
```

The `__get` method is dispatching to `get` method, if you don't want to use the magic method,

```
$record->get('name');
```

The magic method calls value inflator, which can help you inflate values like DateTime objects, it might be slower, if you want performance, you can simply do:

```
$record->getValue('name');
```

BaseModel also supports iterating, so you can iterate the data values with foreach:

```
foreach( $record as $column => $rawValue ) {

}
```

### Model Operation

[](#model-operation)

To create a model record:

```
$author = new Author;
$ret = $author->create(array(
    'name' => 'Foo'
));
if ( $ret->success ) {
    echo 'created';
}
```

To find record:

```
$ret = $author->load(123);
$ret = $author->load(array( 'foo' => 'Name' ));
if ( $ret->success ) {

} else {
    // handle $ret->exception or $ret->message
}
```

To find record with (static):

```
$record = Author::load(array( 'name' => 'Foo' ));
```

To find record with primary key:

```
$record = Author::load( 1 );
```

To update record:

```
$author->update(array(
    'name' => 'Author',
));
```

To update record (static):

```
$ret = Author::update( array( 'name' => 'Author' ) )
    ->where()
        ->equal('id',3)
        ->execute();

if( $ret->success ) {
    echo $ret->message;
}
else {
    // pretty print error message, exception and validation errors for console
    echo $ret;

    $e = $ret->exception; // get exception
    $validations = $ret->validations; // get validation results
}
```

### Collection

[](#collection)

To create a collection object:

```
$authors = new AuthorCollection;
```

To make a query (the Query syntax is powered by SQLBuilder):

```
$authors->where()
    ->equal( 'id' , 'foo' )
    ->like( 'content' , '%foo%' );
```

Or you can do:

```
$authors->where(array(
    'name' => 'foo'
));
```

#### Iterating a Collection

[](#iterating-a-collection)

```
$authors = new AuthorCollection;
foreach( $authors as $author ) {
    echo $author->name;
}
```

Model Schema
------------

[](#model-schema)

### Defining Schema Class

[](#defining-schema-class)

Simply extend class from `LazyRecord\Schema`, and define your model columns in the `schema` method, e.g.,

```
