Skip to content

Instantly share code, notes, and snippets.

@davidyell
Last active February 25, 2016 10:14
Show Gist options
  • Save davidyell/e784e70eb06903a790de to your computer and use it in GitHub Desktop.
Save davidyell/e784e70eb06903a790de to your computer and use it in GitHub Desktop.
Creating a CakePHP 3 migration using Faker to input data.
<?php
use Phinx\Migration\AbstractMigration;
use Faker\Factory as Faker;
use Faker\ORM\CakePHP\Populator;
class Seed extends AbstractMigration
{
public function up() {
$faker = Faker::create();
$populator = new Populator($faker);
$populator->addGuesser('\Faker\Guesser\Name');
$created = $modified = function () use ($faker) {
static $beacon;
$ret = $beacon;
if (empty($ret)) {
return $beacon = $faker->dateTimeThisDecade();
}
$beacon = null;
return $ret;
};
$timestamp = compact('created', 'modified');
$name = $faker->realText(25, 2);
$populator->addEntity('Contents', 10, [
'name' => function () use ($name) { return $name; },
'slug' => function () use ($name) { return \Cake\Utility\Inflector::slug($name); },
'content_type_id' => function () use ($faker) { return $faker->numberBetween(1, 2); },
'content' => function () use ($faker) { return $faker->text(); },
'provider_id' => function () { return array_rand([1, 2, 3, 4, 5, 6, null]); },
'status_id' => function () use ($faker) { return $faker->numberBetween(1, 4); }
] + $timestamp);
$populator->execute(['validate' => false]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment