As you may have noticed, last weekend all command line related files in CakePHP 1.2 have been moved from /cake/scripts to /cake/console. Coupled with this move was a change in the way you use the command line scripts. Instead of

php bake.php -app /path_to_app_dir

you now have to use

./cake bake -app /path_to_app_dir

to run the bake script. The ACL script can be used in a similar way.

This switch to the new console is probably the end of bake2, as it doesn’t (yet) work with the console, and the console provides a similar functionality as bake2, i.e. the console allows you to execute your own command line scripts. In the meantime the bake2 script has been removed from the repository. (Update 2007-05-15: The bake2 script has been removed from the repository)

Writing such a command line script (or shell scripts as they are called in CakePHP) is easy, so let us write a simple script which creates a file specified by the user. The custom scripts are placed in /app/vendors/shells, if they are specific to an application, or in /vendors/shells, if they are generic.

In our case it doesn’t matter where we place the file as it is only an example, so we put it to /vendors/shells. A shell class has to extend the class “Shell” and the class name has to end with “Shell”. All public functions of a shell class are treated as “commands”, i.e. they can be called directly via command line. What the “index” function is for controllers, is the “main” function for shell scripts. It is automatically called if you don’t specify a different command.

In our case we also have to override the “initialize” function, as we don’t have a database.php file in app/config (else we would get an error). The code for our shell script is straight-forward and should be self-explanatory:

// vendors/shells/demo.php
class DemoShell extends Shell {

    function initialize() {
        // empty
    }

    function main() {
        $this->out('Demo Script');
        $this->hr();

        if (count($this->args) === 0) {
            $filename = $this->in('Please enter the filename:');
        } else {
            $filename = $this->args[0];
        }
        $this->createFile(TMP.$filename, ‘Test content’);
    }

    function help() {
        $this->out(’Here comes the help message’);
    }
}

This script can now be executed in one of the following ways:

./cake demo  // asks the user for a file name
./cake demo test.txt   // uses the specified file name
./cake demo help   // shows the help message

Happy baking :)

Update (2007-05-13): Adapted to the latest changes in the code (CakeScript has been renamed to Shell)