php - Console command for creating dummy data to DB in the mature Yii1 project

one text

Solution:

For using the fixtures you can do the following:

Create a new command called:

protected\commands\FixtureCommand.php

With the following contents:

<?php

Yii::import('system.test.CDbFixtureManager');

class FixtureCommand extends CConsoleCommand {

  public function actionIndex() {
    
    /* @var $fixtureManager CDbFixtureManager */
    $fixtureManager=new CDbFixtureManager();
    $fixtureManager->basePath=Yii::getPathOfAlias('application.my_fixtures');
    $fixtureManager->init();

    // Just print some info about the tables
    foreach ($fixtureManager->getFixtures() as $name => $path) {
      echo "Loaded {$name} table from {$path}\n";
    }
    
  }

}

Now create a directory protected/my_fixtures.

And create some fixtures:

protected\my_fixtures\project.php

<?php

return array(
    array(
        'name' => 'Red project',
        'company' => 'Red Ltd',
        'open' => 1,
    ),
    array(
        'name' => 'Blue project',
        'company' => 'Blue Ltd',
        'open' => 1,
    ),
    array(
        'name' => 'Green project',
        'company' => 'Green Ltd',
        'open' => 0,
    ),
);

protected\my_fixtures\task.php

<?php

return array(
    array(
        'project_id' => '1',
        'description' => 'Get the milk',
        'completed' => 1,
    ),
    array(
        'project_id' => '1',
        'description' => 'Get the eggs',
        'completed' => 1,
    ),
    array(
        'project_id' => '1',
        'description' => 'Walk the dog',
        'completed' => 0,
    ),
);

Finally, go to the terminal and run the command:

C:\Projects\fixtureapp\protected>c:\xampp\php56\php.exe yiic.php fixture
Loaded project table from C:\Projects\fixtureapp\protected\my_fixtures\project.php
Loaded task table from C:\Projects\fixtureapp\protected\my_fixtures\task.php

You can find the full example project here on Github:

https://github.com/atrandafir/yii-1-fixtures

Other tips:

  • I hope that you do use database migrations in order to keep your schema structure the same between develop and production instances.
  • I really recommend reading the API, the documentation of Yii classes, and have "the courage" to use them and customize them, feel free to open the clases files and look at what is it exactly they do
  • If the current fixtures manager class doesn't do what you want, you could also extend and override its methods, or even write a new one based on the origial

Source