MVC on command line

PHP

If you work with Zend Framework, you likely tried ZF Console (Zend_Tool on command line). But have you tried to extend it? Why? To have common interface for all your Cli-scripts related to ZF-base project. How do you find the idea to program Cli-scripts in MVC? Zend Framework provides us with the tool to do it.

First, you have to make ZF shell script zf.sh and assisting zf.php globally accessible. Wherever you have located them, just make a symlink on zf.sh like

ln -s zf.sh /usr/local/bin/zf

You can also just move them into the folder with your PHP binary, though.

If you don’t have ZF library inside your include_path, you should let ZF Console to know where the library located and where to search for providers. Providers here are almost the same as controllers for the traditional MVC.

ZF recommends to use environment variables to specify the path. However, it didn’t happen to me to pass the path via the variables. So instead, I’ve created the configuration file for the console in home directory (path to the configuration file can be set up manually through ZF_CONFIG_FILE environment variable).

php.include_path = "/home/sheiko/projectX/trunk/lib/"
basicloader.classes.1 = " Console_Providers_HelloProvider"

You see here are the library path and list of declared providers. Let’s now create the simple provider, we have pointed in configuration.

<?php
  class Console_Providers_HelloProvider
      implements Zend_Tool_Framework_Provider_Interface
  {
    public function say()
    {
        echo 'Hello from my provider!';
    }
      
  }
Sample of Zend_Tool provider

After that, we can check if the providers and the action are available within the console.

zf --help
Console screenshot

If everything is ok, we can run the example:

zf say hello

What about interactive input in the console? Let’s add this action.

public function ask()
{
          $nameResponse = $this->_registry
                               ->getClient()
                               ->promptInteractiveInput("What is the meaning of life?");
          $name = $nameResponse->getContent();

          echo 'The answer is ' . ($name == "42" ? "correct" : "incorrect");
 }

Now, you can categorize you scripts by providers and access them in this unified interface. The architecture can be the very similar to that you are used to have for your web applications