Skip to content

Instantly share code, notes, and snippets.

@joeytrapp
Last active December 27, 2015 10:39
Show Gist options
  • Save joeytrapp/7312311 to your computer and use it in GitHub Desktop.
Save joeytrapp/7312311 to your computer and use it in GitHub Desktop.
Very basic SeedShell, with default and dev files along with ability to specify file manually. Also has a firstOrCreate helper to make creating seed records idempotent.
<?php
$User = ClassRegistry::init('User');
$this->firstOrCreate(
$User,
array('email' => 'admin@example.com'),
array('first_name' => 'Admin', 'last_name' => 'Admin')
);
<?php
$User = ClassRegistry::init('User');
$user = $User->find('first');
$Post = ClassRegistry::init('Post');
$this->firstOrCreate(
$Post,
array('title' => 'Example Title 1'),
array('body' => 'Lorem ipsum', 'user_id' => $user['User']['id'])
);
<?php
class SeedShell extends AppShell {
public $seedFile = 'seed.php';
public $seedDevFile = 'seed_dev.php';
public function main() {
$this->includeFile($this->absolutePath($this->getFile()));
}
public function init() {
$this->existsOrCreate($this->absolutePath($this->getFile()));
}
public function getOptionParser() {
$parser = parent::getOptionParser();
$parser->addOption('dev', array(
'boolean' => true,
'help' => 'Use the default dev file instead of the default'
));
$parser->addOption('file', array(
'help' => 'Manually specify the file that should be used'
));
return $parser;
}
public function firstOrCreate($Model, $conditions, $data = array()) {
$record = $Model->find('first', array('conditions' => $conditions));
if (!empty($record)) {
$Model->create($data + $conditions);
if ($Model->save()) {
$record = $Model->read();
} else {
$cond = var_export($conditions);
$this->out("Failed to create {$Model} record for conditions:\n\n{$cond}");
exit();
}
}
return $record;
}
private function getFile() {
$file = $this->seedFile;
if (isset($this->params['file']) && !empty($this->params['file'])) {
$file = $this->params['file'];
} else if ($this->params['dev']) {
$file = $this->seedDevFile;
}
return $file;
}
private function includeFile($file) {
include $file;
}
private function existsOrCreate($file) {
if (!file_exists($file)) {
file_put_contents($file, "<?php\n\n");
}
}
private function absolutePath($file) {
return APP . DS . 'Config' . DS . $file;
}
}
@ricog
Copy link

ricog commented Nov 5, 2013

👍

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