Following on from my previous posts announcing CakePHP 1.2 compatible versions of Migrations and Fixtures, below you will find another bake2 task that can very quickly generate your models, controllers, migrations and fixtures.
To generate a model called "User" in your "app" application, simply run:
php bake2.php generate app model User
Use the exact same syntax to generate controllers and migrations.
If you run "php bake2.php generate app fixtures", a fixture will be created for every table in your database, unless of course fixtures already exists.
/**
* The GenerateTask generates various files as specified.
*
* PHP versions 4 and 5
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2006-2007, Joel Moss
* @link http://joelmoss.info
* @package cake
* @subpackage cake.cake.scripts.bake
* @since CakePHP(tm) v 1.2
* @version $Version: 1.0 $
* @modifiedby $LastChangedBy: joelmoss $
* @lastmodified $Date: 2007-02-16 09:09:45 +0000 (Fri, 16 Feb 2007) $
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
uses('file', 'folder', 'inflector');
class GenerateTask extends BakeTask
{
function execute($params)
{
$this->welcome();
if ($params[0] == 'help')
{
$this->help();
exit;
}
$this->initDatabase();
$this->initApp();
define('FIXTURES_PATH', APP_PATH .'config' .DS. 'fixtures');
define('MIGRATIONS_PATH', APP_PATH .'config' .DS. 'migrations');
if (count($params) > 0)
{
if ($params[0] == 'fixtures')
{
$this->fixtures();
exit;
}
elseif ($params[0] == 'migration')
{
$this->migration($params[1]);
exit;
}
elseif ($params[0] == 'model')
{
$this->model($params[1]);
exit;
}
elseif ($params[0] == 'controller')
{
$this->controller($params[1]);
exit;
}
}
$this->help();
}
function controller($name)
{
if (empty($name)) $this->err('Controller name not specified.');
if (!preg_match("/^[a-zA-Z]+$/", $name))
$this->err('Controller name ('.$name.') is invalid. It must be CamelCased');
$filename = Inflector::underscore($name) . '_controller.php';
if (file_exists(CONTROLLERS . $filename)) $this->err('Controller ('.$name.') already exists.');
$data = "";
$file = new File(CONTROLLERS . $filename, true);
$file->write($data);
$this->out('');
$this->out('Generation of controller: ''.$name.'' completed.');
$this->out('Please edit ''.CONTROLLERS . $filename . '' to customise your controller.');
if (!file_exists(VIEWS.Inflector::underscore($name)))
new Folder(VIEWS.Inflector::underscore($name), true, 0777);
$this->hr();
exit;
}
function model($name)
{
if (empty($name)) $this->err('Model name not specified.');
if (!preg_match("/^[a-zA-Z]+$/", $name))
$this->err('Model name ('.$name.') is invalid. It must be CamelCased');
$filename = Inflector::underscore($name) . '.php';
if (file_exists(MODELS . $filename)) $this->err('Model ('.$name.') already exists.');
$data = "";
$file = new File(MODELS . $filename, true);
$file->write($data);
$this->out('');
$this->out('Generation of model: ''.$name.'' completed.');
$this->out('Please edit ''.MODELS . $filename . '' to customise your model.');
$this->migration('create_'.Inflector::tableize($name));
exit;
}
function migration($name)
{
if (empty($name)) $this->err('Migration name not specified.');
if (!preg_match("/^([a-z0-9]+|_)+$/", $name)) $this->err('Migration name ('.$name.') is invalid');
$this->getMigrations();
$new_migration_count = $this->migration_count+1;
$data = "#n# migration YAML filen#nUP: nullnDOWN: null";
$file = new File(MIGRATIONS_PATH . DS .$new_migration_count . '_' . $name . '.yml', true);
$file->write($data);
$this->out('');
$this->out('Generation of migration file: ''.$name.'' completed.');
$this->out('Please edit ''.MIGRATIONS_PATH . DS .$new_migration_count . '_' . $name . '.yml' to customise your migration.');
$this->hr();
exit;
}
function getMigrations()
{
$folder = new Folder(MIGRATIONS_PATH, true, 0777);
$this->migrations = $folder->find("[0-9]+_.+.yml");
usort($this->migrations, array('GenerateTask', '_upMigrations'));
$this->migration_count = count($this->migrations);
}
function _upMigrations($a, $b)
{
list($aStr) = explode('_', $a);
list($bStr) = explode('_', $b);
$aNum = (int)$aStr;
$bNum = (int)$bStr;
if ($aNum == $bNum) {
return 0;
}
return ($aNum > $bNum) ? 1 : -1;
}
function fixtures()
{
$folder = new Folder(FIXTURES_PATH, true, 0777);
$tables = $this->_db->listTables();
if (!count($tables))
$this->err('Database contains no tables. Please generate and run your migrations before your fixtures.');
$this->out();
$data = "#n# Fixture YAML filen#n#n# Example:-n# -n# first_name: Bobn# last_name: Bonesn#n";
foreach ($tables as $i=>$t)
{
if (!file_exists(FIXTURES_PATH .DS. $t . '.yml'))
{
$file = new File(FIXTURES_PATH .DS. $t . '.yml', true);
$file->write($data);
$this->out(' Generating fixture for '.$t.' ... DONE!');
}
}
$this->out('Generating complete!');
$this->hr();
}
function initApp()
{
$this->out("Application: '".APP_DIR."' (".APP_PATH.")");
$this->hr();
}
function initDatabase()
{
if (!@include_once('MDB2.php'))
{
$this->err('Task Error: Unable to include PEAR.php and MDB2.php');
}
if(!file_exists(APP_PATH.'config'.DS.'database.php'))
{
$this->out('** Checking for database configuration ... NOT FOUND! **');
$this->out();
$this->out('IMPORTANT!');
$this->out('Your database configuration ('.APP_PATH.'config'.DS.'database.php) was not found. Please');
$this->out('take a moment to create one by running the 'dbconfig' task:');
$this->out('');
$this->out(' php bake2.php dbconfig [...]');
$this->hr();
exit;
}
require_once (APP_PATH . 'config' .DS. 'database.php');
$ds = new DATABASE_CONFIG();
$config = $ds->default;
$dsn = array(
'phptype' => $config['driver'],
'username' => $config['login'],
'password' => $config['password'],
'hostspec' => $config['host'],
'database' => $config['database']
);
$options = array(
'debug' => DEBUG,
'portability' => DB_PORTABILITY_ALL
);
$this->_db = &MDB2::connect($dsn, $options);
if (PEAR::isError($this->_db)) $this->err($this->_db->getDebugInfo());
$this->_db->setFetchMode(MDB2_FETCHMODE_ASSOC);
$this->_db->loadModule('Manager');
$this->_db->loadModule('Extended');
$this->_db->loadModule('Reverse');
}
function help()
{
echo "This task generates database migration and fixture files.n";
echo "Usage: bake2 generate app_alias fixtures|migration [migration_name]n";
}
function out($str='', $newline=true)
{
$nl = $newline ? "n" : "";
echo " $str$nl";
}
function hr()
{
echo "n ----------------------------------------------------------------------------n";
}
function err($str)
{
$this->out('');
$this->out(' ** '.$str.' **');
$this->hr();
exit;
}
function welcome()
{
$this->out('');
$this->hr();
$this->out(' __ __ _ _ __ __ _ _ __ __ __ __ __ __ ___ __ __ ');
$this->out('| |__| |_/ |__ |__] |__| |__] | _ |__ | | |__ |__] |__| | | | |__]');
$this->out('|__ | | | _ |__ | | | | |__| |__ | | |__ | | | | |__| | ');
$this->hr();
$this->out('');
}
}
Its a great way to easily complete a few mudane tasks.