Skip to content

Instantly share code, notes, and snippets.

@fillup
Last active August 29, 2015 14:02
Show Gist options
  • Save fillup/f6c88127bdc7c18004d6 to your computer and use it in GitHub Desktop.
Save fillup/f6c88127bdc7c18004d6 to your computer and use it in GitHub Desktop.
Proposal for Yii2 database migration script to automatically regenerate model classes

Yii has some great features for simplifying and automating portions of development. Two key areas are...

  • Gii generating model classes based on table schemas
  • Using the yiic migrate command to manage schema changes

I am proposing two enhancements to these areas. For Gii model generation, I suggest that it create separate Base and extending classes (https://gist.github.com/fillup/5cdba5990c6576bbbfb0). In this Gist I propose that the migration support is enhanced to add a parameter for automatically regenerating the base classes for affected (or all) tables.

My ideal workflow would be:

  1. ./yiic migrate create create_table_user // migration for creating a table named 'user'
  2. Edit the migration file to define the schema for the 'user' table
  3. Execute the migration: ./yiic migrate --gii-create-classes
  4. With the flag --gii-create-classes provided, migrate would work with Gii to generate two class files: UserBase and User. UserBase would match the file that Gii currently generates and User would be an empty class that extends UserBase.
  5. ./yiic migrate create alter_user_table // create migration to modify the table named 'user'
  6. Edit the migration file to alter the table
  7. Execute the migration: ./yiic migrate --gii-create-classes
  8. With the flag --gii-create-classes provided, gii sees that the extending class already exists so it only recreates the Base class

With this flow I'm able to focus on my database schemas/migrations and Yii/Gii takes care of model class file (re)generation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment