Skip to content
Yo-An Lin edited this page Apr 26, 2017 · 3 revisions

If your database loader runs smoothly, you may now create your own model schema file:

$ vim src/MyApp/Model/BookSchema.php

Put the content below to the file:

<?php
namespace MyApp\Model;
use Maghead\DeclareSchema;

class BookSchema extends DeclareSchema
{
    public function schema()
    {
        $this->column('title')
            ->varchar(80)
            ->label('Book Title')
            ;

        $this->column('author')
            ->varchar(20)
            ->label('Book Author')
            ;

        $this->column('price')
            ->integer()
            ->label('Book Price')
            ->default(299)
            ;
    }
}

Then you may run schema command to compile the schema into static class files:

$ maghead schema build
Found schema classes
Checking MyApp\Model\BookSchema...
Done

To see the generated files, you may run tree to see the directory structure:

$ tree src
src
└── MyApp
    └── Model
        ├── Book.php
        ├── BookBase.php
        ├── BookCollection.php
        ├── BookCollectionBase.php
        ├── BookSchema.php
        └── BookSchemaProxy.php

And your config file structure should be like this:

$ tree db
db
└── config
    ├── database.php
    └── database.yml

To load these classes in your application, you need to define autoload rules in your composer.json, for example, I have an application with MyApp namespace located in src/MyApp/ directory:

{
    "require": {
       "maghead/maghead": "*"
    },
    "autoload": {
        "psr-4": {
            "MyApp\\": "src/MyApp/"
        }
    }
}

Building Database Tables

Now, we want to convert our model schema into SQL statements.

To convert your schema into SQL and import to your database, you may run:

$ maghead sql
Building Table SQL for MyApp\Model\BookSchema
Building Index SQL for MyApp\Model\BookSchema
Building Foreign Key SQL for MyApp\Model\BookSchema
Setting migration timestamp to 1399712909
Done. 1 schema tables were generated into data source 'default'.

Rebuilding Database Tables

If you want to rebuild the tables to your database, you may specify --rebuild option to the end of command:

$ maghead sql --rebuild
Building Table SQL for MyApp\Model\BookSchema
Building Index SQL for MyApp\Model\BookSchema
Building Foreign Key SQL for MyApp\Model\BookSchema
Setting migration timestamp to 1399712996
Done. 1 schema tables were generated into data source 'default'.

Cleaning Up Model Schema Files

If you want to clean up all auto-generated files, you may run:

$ maghead schema clean

The command above will delete all auto-generated class files, but keep the schema, model, collection classes.

Clone this wiki locally