Build your Zend Framework Console Application

21 May 2015 · Two minute read · on Gianluca's blog

News! Tech related notes are NOW published to ShippingBytes. See you there! I always felt this was not the right place for me to write consistently about tech and tools. So if you want to read more about that see you at the other side

I’m writing a skeleton app to build console/bash application in PHP. This project is very easy and it depends on ZF\Console a zfcampus project and Zend\Console builds by ZF community. I have a todo list for the future but for the time being it’s just a blog post about these two modules.

ZF\Console and other components

Tree

This is my folders structure proposal, there are three entrypoint in the bin directory, one for bash, one for php and a bat for Window. I use composer to manage my dependencies and I included .lock file because this project is an APPLICATION not a library.. /config directory contains only routing definitions but in the future we can add services and other configurations. src/Command/ contains my commands.

├── bin
│   └── console.php
├── composer.json
├── composer.lock
├── config
│   └── routes.php
├── src
│   └── Command
│       ├── Conf.php
│       ├── Database.php
│       └── Download.php
└── vendor
    └── ...

Bootstrap

The Application’s entrypoints are just example and they require few changes. First we have to change the version in the parameters.php configuration file and also change the application name 'app' to what fits. To load configurations from different sources I will use the well known Zend\Config component.

<?php
require __DIR__.'/../vendor/autoload.php';

use Zend\Console\Console;
use ZF\Console\Application;
use ZF\Console\Dispatcher;

$version = '0.0.1';

$application = new Application(
    'app',
    $version,
    include __DIR__ . '/../config/routes.php',
    Console::getInstance(),
    new Dispatcher()
);

$exit = $application->run();
exit($exit);

Routes

config/routes.php contains router configurations. This is just an example but you can see all options here.

<?php
return [
    [
        'name'  => 'hello',
        'route' => "--name=",
        'short_description' => "Good morning!! This is a beautiful day",
        "handler" => ['App\Command\Hello', 'run'],
    ],
];

Command

Basic command to wish you a good day! I decided that a command doesn’t extends any class because in my opinion is a good way to impart readability and simplicity.

<?php
namespace App\Command;

use ZF\Console\Route;
use Zend\Console\Adapter\AdapterInterface;

class Hello
{
    public static function run(Route $route, AdapterInterface $console)
    {
        $name = $route->getMatchedParam("name", "@gianarb");
        $console->writeLine("Hi {$name}, you have call me. Now this is an awesome day!");
    }
}

Troubleshooting and tricks




@__debo thanks for trying to fix my bad English
Something weird with this website? Let me know.