Romanovich095

CakePHP 3.x Migrations example

Aug 10th, 2016
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.13 KB | None | 0 0
  1. <?php
  2. use Migrations\AbstractMigration;
  3. use Cake\Log\Log;
  4.  
  5. /**
  6.  * Class AdministratorsTableMigration
  7.  */
  8. class AdministratorsTableMigration extends AbstractMigration
  9. {
  10.  
  11.     /**
  12.      * @var string
  13.      */
  14.     private $_tableName;
  15.  
  16.     /**
  17.      * @var string
  18.      */
  19.     private $_tablePrefix;
  20.  
  21.     public function init()
  22.     {
  23.         $this->_tableName = '"Administrators"';
  24.         $this->_tablePrefix = 'administrators';
  25.     }
  26.  
  27.     public function up()
  28.     {
  29.         Log::info("Trying to create {$this->_tableName} table");
  30.  
  31.         $administratorsTable = $this->table($this->_tablePrefix);
  32.  
  33.         if ($administratorsTable->exists()) {
  34.             return Log::warning("Table {$this->_tableName} already exists");
  35.         }
  36.  
  37.         $administratorsTable
  38.             ->addPrimaryKey('id')
  39.             ->addColumn('username', 'char', [
  40.                 'length' => 25,
  41.                 'null' => false
  42.             ])
  43.             ->addColumn('password', 'char', [
  44.                 'length' => 255,
  45.                 'null' => false
  46.             ])
  47.             ->addColumn('email', 'char', [
  48.                 'length' => 50,
  49.                 'null' => false
  50.             ])
  51.             ->addColumn('first_name', 'char', [
  52.                 'length' => 50,
  53.                 'null' => false
  54.             ])
  55.             ->addColumn('last_name', 'char', [
  56.                 'length' => 50,
  57.                 'null' => false
  58.             ])
  59.             ->addColumn('avatar', 'char', [
  60.                 'length' => 255,
  61.                 'default' => '/img/no-avatar.png'
  62.             ])
  63.             ->addColumn('active', 'boolean', [
  64.                 'default' => 0
  65.             ])
  66.             ->addTimestamps()
  67.             ->create();
  68.  
  69.         return Log::notice("Table {$this->_tableName} has been created");
  70.     }
  71.  
  72.     public function down()
  73.     {
  74.         if ($this->table($this->_tablePrefix)->exists()) {
  75.             $this->table($this->_tablePrefix)->drop();
  76.             return Log::info("Table {$this->_tableName} has been dropped");
  77.         }
  78.  
  79.         return Log::warning("Table {$this->_tableName} does not exists");
  80.     }
  81.  
  82. }
Advertisement
Add Comment
Please, Sign In to add comment