Oneupweb : CakePHP—Writing a Custom Shell for the Bake Console
Anyone who has used CakePHP knows that the Cake console is pretty boss sauce. You can use this handy little tool to accomplish awesome things like:
cake bake all
This handy tool looks at your schema and generates all the models,views and controllers your neat little MVC app requires.
But what if we need some other handy utility that the Cake console does not ship with? I am going to show you how to make a cake shell program that creates restful JSON views to aid with making your app a RESTful powerhouse.
Directory Structure Matters
Since CakePHP is a convention over configuration framework, where we put our files, and what we name them matters.
We are going to call our custom shell program json_views.
/* /app/vendors/shells/json_views.php */ app/ -- vendors/ ---- shells/ ------ json_view.php
Class Name Matters
Our program is json_views, and true to the Cake way, underscore means camel case. Open up your json_views.php
file and create the following class structure:
<?php class JsonViewsShell extends Shell { } ?>
Notice the word shell at the end of our JsonViews bit. Also make sure to extend the cake native Shel class.
The only method your shell program needs to have is the main() method. It is that simple. Take a look at the main() method of the json_views shell program:
<?php class JsonViewsShell extends Shell { function main() { App::import('Inflector'); $model = $this->args[0]; $models = strtolower(Inflector::pluralize($this->args[0])); $directory = VIEWS . DS . $models; if ( is_dir($directory) ) { $json_dir = $directory . DS . 'json'; if (! is_dir($json_dir) ) { mkdir($json_dir); $views = array( 'add.ctp' => '<?php echo json_encode($' . $model . '); ?>', 'edit.ctp' => '<?php echo json_encode($' . $model . '); ?>', 'view.ctp' => '<?php echo json_encode($' . $model . '); ?>', 'index.ctp' => '<?php echo json_encode($' . $models . '); ?>' ); foreach ( $views as $file => $contents ) { $path = $json_dir . DS . $file; file_put_contents($path,$contents); } $this->out('Json views for ' . $model . ' have been created. Make sure the default.ctp layout for json has been created as well.'); } else { $this->out('Json directory for ' . $model . ' already exists'); } } else { $this->out('Model ' . $model . ' does not exist'); } } } ?>
Note the use of $this->args. This is an array with the arguments passed to your shell program. Please be aware if you are using any one of Cakes built in classes, you must import it using the App:import convention.
Using Your Custom Cake Shell
Fire up your console app (terminal, or windows cmd) and navigate your way to the app folder, within the shell:
/* /cakeapp/app/ */ cake json_views book
It’s that easy. The above would create a json folder in /app/views/books and fill it with view file for the standard CRUD actions.
This opens a ton of possibilities for stream lining your application development process!