Skip to content

Instantly share code, notes, and snippets.

@JeffreyWay
Last active December 16, 2015 21:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JeffreyWay/9e9bdb1187dfe5229a49 to your computer and use it in GitHub Desktop.
Save JeffreyWay/9e9bdb1187dfe5229a49 to your computer and use it in GitHub Desktop.
Your Assignment: what could be improved in this class? Does it violate the SRP? Can we add additional generators easily? Provide your ideas below. Solution will be recorded/posted Friday, May 3rd.
<?php namespace Commands;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem as File;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class ModelGeneratorCommand extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'generate:model';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate an Eloquent model with boilerplate.';
/**
* The Filesystem instance
*
* @var Illuminate\Filesystem\Filesystem
*/
protected $file;
/**
* Create a new command instance.
*
* @return void
*/
public function __construct(File $file)
{
parent::__construct();
$this->file = $file;
}
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
// figure out what model to create
$modelName = ucwords($this->argument('name'));
$path = $this->option('path').'/'.$modelName.'.php';
$template = $this->getTemplate($modelName);
if ($this->createModel($path, $template))
{
return $this->info("Created: $path.");
}
$this->info("Could not create $path.");
}
protected function getPath()
{
return app_path().'/models';
}
protected function getTemplate($modelName)
{
$template = $this->file->get(__DIR__.'/templates/model.txt');
return str_replace('{{modelName}}', $modelName, $template);
}
protected function createModel($path, $data)
{
if ( ! $this->file->exists($path))
return $this->file->put($path, $data);
return false;
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array(
array('name', InputArgument::REQUIRED, 'The name of the model to generate.'),
);
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return array(
array('path', 'p', InputOption::VALUE_OPTIONAL, 'Path to where model should be created.', $this->getPath()),
);
}
}
@JeffreyWay
Copy link
Author

Hint: why is it the command's job to generate files?

@JeffreyWay
Copy link
Author

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