Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

The fastest pure PHP database framework with a powerful static code generator, supports horizontal scale up, designed for PHP7

License

NotificationsYou must be signed in to change notification settings

maghead/maghead

Repository files navigation

Build StatusCoverage StatusLatest Stable VersionTotal DownloadsMonthly DownloadsDaily DownloadsLatest Unstable VersionLicenseJoin the chat at https://gitter.im/maghead/magheadWorks On My MachineMade in Taiwan

4.0.x IS CURRENTLY UNDER HEAVY DEVELOPMENT, API IS NOT STABLE

Maghead is an open-source Object-Relational Mapping (ORM) designed for PHP7.

Maghead uses static code generator to generate static classes that maps to the database records and methods, which reduces runtimecosts, therefore it's pretty lightweight and extremely fast.

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

How fast is it? Currently it's the fastest ORM written in pure PHP.See the benchmark for more details.

Automatic Migration Demonstration

Feature

  • Fast & 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 & Downgrade of course.
    • Automatic Migration: generate migration SQL automatically based on the schema diff.
  • Schema/Database diff

Design Concept

  • Function calls in PHP are very slow, so the model schema datawill be built statically, Maghead converts all definitions (default value, validator, filter, validvalue builder) into classes and static PHP array, this keeps these modelclasses very lightweight and fast.

  • In the runtime, all the same model objects use the sameschema 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 fromdatabase, these model objects can be created with zero effort.

Getting Started

Please see the details onWiki

Schema

Defining Schema Class

Simply extend class fromMaghead\Schema\DeclareSchema, and define your model columnsin theschema method, e.g.,

<?phpnamespaceTestApp;useMaghead\Schema\DeclareSchema;class BookSchemaextends DeclareSchema{publicfunctionschema()    {$this->column('title')            ->unique()            ->varchar(128);$this->column('subtitle')            ->varchar(256);$this->column('isbn')            ->varchar(128)            ->immutable();$this->column('description')            ->text();$this->column('view')            ->default(0)            ->integer();$this->column('publisher_id')            ->isa('int')            ->integer();$this->column('published_at')            ->isa('DateTime')            ->timestamp();$this->column('created_by')            ->integer()            ->refer('TestApp\UserSchema');// Defining trait for model class$this->addModelTrait('Uploader');$this->addModelTrait('Downloader')            ->useInsteadOf('Downloader::a','Uploader');$this->belongsTo('created_by','TestApp\UserSchema','id','created_by');/**         * column: author => Author class         *         * $book->publisher->name;         *         **/$this->belongsTo('publisher','\TestApp\PublisherSchema','id','publisher_id');/**         * accessor , mapping self.id => BookAuthors.book_id         *         * link book => author_books         */$this->many('book_authors','\TestApp\AuthorBookSchema','book_id','id');/**         * get BookAuthor.author         */$this->manyToMany('authors','book_authors','author' )            ->filter(function($collection) {return$collection; });    }}

Defining Column Types

$this->column('foo')->integer();$this->column('foo')->float();$this->column('foo')->varchar(24);$this->column('foo')->text();$this->column('foo')->binary();

Text:

$this->column('name')->text();

Boolean:

$this->column('name') ->boolean();

Integer:

$this->column('name')->integer();

Timestamp:

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

Datetime:

$this->column('name')->datetime();

Defining Mixin Method

namespaceMaghead\Schema\Mixin;useMaghead\Schema\MixinDeclareSchema;class MetadataMixinSchemaextends MixinDeclareSchema{publicfunctionschema()    {// ... define your schema here    }publicfunctionfooMethod($record,$arg1,$arg2,$arg3,$arg4)    {// ...return...;    }}

Then you can use thefooMethod on your model object:

$result =$record->fooMethod(1,2,3,4);

Using Multiple Data Source

You can define specific data source for different model in the model schema:

useMaghead\Schema\DeclareSchema;class UserSchemaextends DeclareSchema {publicfunctionschema() {$this->writeTo('master');$this->readFrom('slave');    }}

Or you can specify for both (read and write):

useMaghead\Schema\DeclareSchema;class UserSchemaextends DeclareSchema {publicfunctionschema() {$this->using('master');    }}

Migration

If you need to modify schema code, like adding new columns to a table, youcan use the amazing migration feature to migrate your database to the latestchange without pain.

Once you modified the schema code, you can executelazy diff command to comparecurrent exisiting database table:

$ maghead diff+ table 'authors'            tests/tests/Author.php+ table 'addresses'          tests/tests/Address.php+ table 'author_books'       tests/tests/AuthorBook.php+ table 'books'              tests/tests/Book.php+ table 'users'              tests/tests/User.php+ table 'publishers'         tests/tests/Publisher.php+ table 'names'              tests/tests/Name.php+ table 'wines'              tests/tests/Wine.php

As you can see, we added a lot of new tables (schemas), and Maghead parsesthe database tables to show you the difference to let you know currentstatus.

Currently Maghead supports SQLite, PostgreSQL, MySQL table parsing.

now you can generate the migration script or upgrade database schema directly.

to upgrade database schema directly, you can simply run:

$ maghead migrate auto

to upgrade database schema through a customizable migration script, you cangenerate a new migration script like:

$ maghead migrate diff AddUserRoleColumnLoading schema objects...Creating migration script from diffFound 10 schemas to compare.    Found schema 'TestApp\AuthorSchema' to be imported to 'authors'    Found schema 'TestApp\AddressSchema' to be imported to 'addresses'    Found schema 'TestApp\AuthorBookSchema' to be imported to 'author_books'    Found schema 'TestApp\BookSchema' to be imported to 'books'    Found schema 'TestApp\UserSchema' to be imported to 'users'    Found schema 'TestApp\PublisherSchema' to be imported to 'publishers'    Found schema 'TestApp\NameSchema' to be imported to 'names'    Found schema 'TestApp\Wine' to be imported to 'wines'Migration script is generated: db/migrations/20120912_AddUserRoleColumn.php

now you can edit your migration script, which is auto-generated:

vim db/migrations/20120912_AddUserRoleColumn.php

the migration script looks like:

class AddUserColumn_1347451491extends \Maghead\Migration\Migration {publicfunctionupgrade() {$this->importSchema(newTestApp\AuthorSchema);$this->importSchema(newTestApp\AddressSchema);// To upgrade with new schema:$this->importSchema(newTestApp\AuthorBookSchema);// To create index:$this->createIndex($table,$indexName,$columnNames);// To drop index:$this->dropIndex($table,$indexName);// To add a foreign key:$this->addForeignKey($table,$columnName,$referenceTable,$referenceColumn =null)// To drop table:$this->dropTable('authors');    }publicfunctiondowngrade() {$this->dropTable('authors');$this->dropTable('addresses');            }}

The built-in migration generator not only generates the upgrade script,but also generates the downgrade script, you can modify it to anything as youwant.

After the migration script is generated, you can check the status ofcurrent database and waiting migration scripts:

$ maghead migrate statusFound 1 migration script to be executed.- AddUserColumn_1347451491

now you can run upgrade command toupgrade database schema through the migration script:

$ maghead migrate up

If you regret, you can run downgrade migrations through the command:

$ maghead migrate down

But please note that SQLite doesn't support column renaming and columndropping.

To see what migration script could do, please check the documentation ofMagsql package.

A More Advanced Model Schema

useMaghead\Schema\DeclareSchema;class AuthorSchemaextends DeclareSchema{functionschema()    {$this->column('id')            ->integer()            ->primary()            ->autoIncrement();$this->column('name')            ->varchar(128)            ->validator(function($val) {.... })            ->filter(function($val) {returnpreg_replace('#word#','zz',$val);              })            ->inflator(function($val) {returnunserialize($val);            })            ->deflator(function($val) {returnserialize($val);            })            ->validValues(1,2,3,4,5 )            ->default(function() {returndate('c');            })            ;$this->column('email')            ->required()            ->varchar(128);$this->column('confirmed')            ->default(false)            ->boolean();$this->seeds('User\\Seed')    }}

LICENSE

MIT License

About

The fastest pure PHP database framework with a powerful static code generator, supports horizontal scale up, designed for PHP7

Topics

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Languages


[8]ページ先頭

©2009-2025 Movatter.jp