Skip to content

Advanced Model Schema

Yo-An Lin edited this page Oct 13, 2015 · 4 revisions

The example below is an overview of schema features:

use LazyRecord\Schema;

class AuthorSchema extends Schema
{
    function schema()
    {
        $this->column('id')
            ->integer()
            ->primary()
            ->autoIncrement();

        $this->column('name')
            ->varchar(128)
            ->validator(function($val) { .... })
            ->filter( function($val) {  
                        return preg_replace('#word#','zz',$val);  
            })
            ->inflator(function($val) {
                return unserialize($val);
            })
            ->deflator(function($val) {
                return serialize($val);
            })
            ->validValues( 1,2,3,4,5 )
            ->default(function() { 
                return date('c');
            })
            ;

        $this->column('email')
            ->required()
            ->varchar(128);

        $this->column('confirmed')
            ->default(false)
            ->boolean();

        $this->seeds('User\\Seed'); // User\Seed
    }
}

Using Validator

Write your validator as a closure, here comes the simplest sample code:

$this->column('name')
    ->varchar(128)
    ->validator(function($val) {
        if ( in_array($val,'foo','bar')) {
            return array(true, "OK");
        }
        return array(false,"Not a valid value.");
    });

If you need, you may also get the arguments and the current record object:

$this->column('name')
    ->varchar(128)
    ->validator(function($val, $args, $record) {
        if ( in_array($val,'foo','bar')) {
            return array(true, "OK");
        }
        return array(false,"Not a valid value.");
    });

If you are using ValidationKit, we can pass the validator class name:

$this->column('id_number')
    ->varchar(10)
    ->validator('TW\\IDNumberValidator');

Defining Inflator And Deflator

Inflator and Deflator are used in some situation like "read a timestamp and construct a DateTime object with the raw value", Or "convert a DateTime object into a string that is acceptable for database"

LazyRecord provides some built-in inflators and deflators, e.g., timestamp columns:

$this->column('created_on')
    ->timestamp();

So that when you are retrieving "created_on" from record object, you get a DateTime object.

You can also define your own deflator or inflator, for example:

$this->column('serialized_content')
    ->varchar(128)
    ->inflator(function($val) {
        return unserialize($val);
    })
    ->deflator(function($val) {
        return serialize($val);
    });

The above code does unserialize/serialize automatically when you're trying to update/create the record object.

Defining Default Value

$this->column('foo')
    ->default('Default')
    ->default( array('current_timestamp') ) // raw sql string
    ->default(function() { 
            return date('c');
    });

Defining Required Column

$this->column('email')
    ->required()
    ->varchar(128);

Defining ValidValues

$this->column('role')
    ->required()
    ->validValues(array('user','admin','guest'));

Generating find methods

LazyRecord provides find method generator to improve the query performance, the find methods are much faster than the generic load method. To use it, simply add findable() on your columns:

$this->column('title')
    ->varchar(80)
    ->label('Book Title')
    ->findable()
    ;

This will generates findByTitle method in your base model class, so you can do:

$ret = $book->findByTitle('Somehow');

Please note that the generated findByTitle method doesn't support value deflating, so you have to type cast the value by yourself.

Defining ValidValues with label

$this->column('bar')
    ->required()
    ->validValues( array( 'label' => 'value'  ) );

Defining Filter

$this->column('content')
    ->required()
    ->filter( function($val) {  
        return preg_replace('#word#','zz',$val);  
    });

Using Mixin Schemas

Simply define mixin in your model schema method:

$this->mixin('tests\\MetadataMixinSchema');

The Mixin Schema Class, e.g., MetadataSchema:

namespace LazyRecord\Schema\Mixin;
use LazyRecord\Schema\MixinSchemaDeclare;

class MetadataSchema extends MixinSchemaDeclare
{
    public function schema()
    {
        $this->column('updated_on')
            ->isa('DateTime')
            ->default(function() { 
                return date('c'); 
            })
            ->timestamp();

        $this->column('created_on')
            ->isa('DateTime')
            ->default(function() { 
                return date('c'); 
            })
            ->timestamp();
    }
}

Clone this wiki locally