ZF-Console: PHP microframework for console applications

As you may know, folks from ZF2/Apigility projects keep bringing interesting utility modules, enriching ZF2 ecosystem. Today I discovered small framework/helper for writing console applications: ZF-Console. And, to my surprise, it was based on my own pull request from last year! I was really proud to see that I brought something useful to the community.

Creating console application

At the bare minimum you will need single file defining console routes and actions to be executed. If you are familiar with Silex or other PHP microframeworks, you'll feel like home. Here's an example application that will print "Hello, World!" message, allowing optional parameter to be passed and printed instead of "World":

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

$application = new Application(
"ZF-Console Skeleton",     // Application name
"1.0",                     // Application version
[                          // Route definition
    [   // First route
    // Example usage: $ php app.php hello Mat
    'name' => 'hello [<name>]',
    'description' => 'Show welcome message',
    'short_description' => 'Show welcome message',
    'defaults' => [
        'name' => 'World',
    ],
    'handler' => function(Route $route, AdapterInterface $console) {
        $name = $route->getMatchedParam('name');
        $console->write("Hello, ");
        $console->write("$name", ColorInterface::LIGHT_GREEN);
        $console->writeLine("!");
    },
    ]
],
Console::getInstance()
);

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

Try to run it by typping in console:

$ php app.php

By default ZF-Console will print usage information, and provide a few handy commands:

ZF-Console Skeleton, version 1.0

Available commands:

autocomplete   Command autocompletion setup
hello [<name>] Show welcome message
help           Get help for individual commands
version        Display the version of the script
Now try using "hello" command:
$ php app.php hello Mat
Hello, Mat!
Cool, isn't it?

ZF-Console Skeleton Application

While putting everything in single file is nice if you want to quickly prototype something, it will quickly become one big mess in real life application. In order to clean it up (and make it testable), we'll split it into more files.

handler parameter from route definition can be anything callable, which allows you to put controller code in a separate class.

I suggest the following structure:

bin/app.php - entry point / "front controller":

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

chdir(dirname(__DIR__));

include 'vendor/autoload.php';

$application = new Application(
	"ZF-Console Skeleton",
	"1.0",
	include 'config/routes.php',
	Console::getInstance()
);

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

config/routes.php - route definition:

return [
  [
  'name' => 'hello [<name>]',
  'description' => 'Show welcome message',
  'short_description' => 'Show welcome message',
  'defaults' => [
      'name' => 'World',
  ],
  'handler' => 'Application\Command\Hello',
  ]
];

src/Application/Command/Hello.php - controller:

namespace Application\Command;

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

class Hello
{
	public function __invoke(Route $route, AdapterInterface $console)
	{
	    $name = $route->getMatchedParam('name');
	    $console->write("Hello, ");
	    $console->write("$name", ColorInterface::LIGHT_GREEN);
	    $console->writeLine("!");
	}
}

As you see, ZF-Console is easy to use and still allows you to unleash full power of ZF2 console routes. Besides what was mentioned here, it supports filters and validators, provides easy way to enable shell autocompletion, handles exceptions, and more. This makes it a good alternative for Symfony's Console, that better integrates with ZF2 ecosystem.

Example on Github

I prepared simple skeleton that may be used as a base for ZF-Console applications. You can find it on Github - just click here.

See also:

Read more 

Testing ZF2 module services

There's an important question often rising when working on Zend Framework 2 module: should I test service factories? After all, they are usually trivial, they create some object and inject it with dependencies from ServiceManager. Having one test per factory seems to be an overkill.

Better to go one step back, and ask yourself a question: what exactly do you want to test?

Read more 

MtMail: e-mail module for ZF2

I'm happy to present a ZF2 module that handles composing and sending e-mail messages.

Why another module? There are a few of them already available on ZF modules website. However, when I was looking for solution to use in my application, I quickly realized that most of them are either outdated, or they miss features I needed. That's why I decided to write my own.

My intention was to create something powerful, but still simple to use. You an customize e-mail headers, add layout, automatically generate plaintext version of HTML e-mail, and so on. But you can also start composing and sending e-emails from your controllers with just a few lines of code.

Read more 

Using standalone Zend\View

Zend\View is pretty advanced rendering engine, with multiple useful features. It is working nicely within ZF2's MVC stack, where it is automatically configured for you. But how to use it without full MVC?

This can be useful in some situations: when building Your Own Microframework™, when creating an application based on ZF2 components, or (in my case) when working on module that is supposed to render something outside MVC flow. All of this projects can benefit from nested templates, multiple rendering engines, or pluggable architecture of Zend\View.

So, how to do that?

Read more 

Extracting single table from huge MySQL dump

During last few weeks I had to work with relatively big MySQL dumps. I had to find interesting rows in about 400 files, each of them taking 40 minutes to import. In order to speed things up, I found simple tool that allowed me to extract only interesting tables.

The tool is actually single Perl script, named extract_sql.pl (available on Github). It allows extracting tables with simple command:

mat@server:~$ extract_sql.pl -t TABLE_NAME -r DUMP_FILE.sql

This command will print dump to console output, so you may want to redirect it to some file:

mat@server:~$ extract_sql.pl -t TABLE_NAME -r DUMP_FILE.sql > table_name.sql

Finally, extract_sql.pl is able to read input from stdin, so it is easy to extract and import single table from compressed dump file:

mat@server:~$ zcat DUMP_FILE.sql | extract_sql.pl -t TABLE_NAME \
| mysql dest_database -u username -p
Read more 

Automated MySQL backup on dedicated server or VPS

I just moved all my small projects to new dedicated server. I have to admit, until now I wasn't paying attention to regular backups. I simply ran mysqldump and copied everything to my laptop every few months. I didn't have any problems with that, as my data was not very critical. But, this time I decided to build something better - I wanted database backups to be generated automatically, at regular intervals.

I knew more or less what to do, I just had to put all pieces together. This tutorial shows necessary steps to build similar solution on your server.

Read more 

About me
Mateusz Tymek

After compiling my very first lines of code at the age of 12, I became passionate about computer science and technology. Now I'm a PHP developer, enjoying my work as a member of Cleeng team.
Doing some sports in my spare time.

Github activity