Phalcon and cli applications

avasin picture avasin · Feb 11, 2013 · Viewed 7.4k times · Source

Is it possible to use phalcon in cli applications to handle requests with argv parameters? I want to use argv parameters to understand command that should be executed, e.g. ./script.php robot/create --color=red --feature=weapon

and to get this inside my application with controllers, actions, etc in this way:

controller: robot action: create GET params: color=red,feature=weapon

Is it possible using CLI classes like

  1. Phalcon\ClI\Dispatcher http://docs.phalconphp.com/en/latest/api/Phalcon_CLI_Dispatcher.html

  2. Phalcon\CLI\Console http://docs.phalconphp.com/en/latest/api/Phalcon_CLI_Console.html

  3. Phalcon\CLI\Task http://docs.phalconphp.com/en/latest/api/Phalcon_CLI_Task.html

and other similar?

There are no docs and how-to manuals... Perhaps somebody has experience or just an idea. I understand that we have to define DI and initialize application, but how to make this in a more native way I just don't have any ideas.

Also, one more question: can phalcon handle argv parameters automatically?

As I understand, we should start Phalcon\CLI\Console object as application and pass to it DI. But the whole process/scenario... I just can't get it :)

Answer

avasin picture avasin · Feb 11, 2013

So, i have following folders structure:

~/www
~/www/app
~/www/app/models
~/www/app/controllers - controllers for web
~/www/app/tasks - task for cli
~/www/public/app.php - web application
~/www/cli/app.php - console application

In cli/app.php i have following code:

#!/usr/bin/php
<?php

/**
 * This makes our life easier when dealing with paths. 
 * Everything is relative to the application root now.
 */ 
chdir(dirname(__DIR__));

/**
 * Init loader
 */
$loader = new \Phalcon\Loader();
$loader->registerDirs(['app/tasks/'])
       ->register(); 

/**
 * Setup dependency injection      
 */       
$di = new Phalcon\DI();

// Router
$di->setShared('router', function() {
    return new Phalcon\CLI\Router();
});

// Dispatcher
$di->setShared('dispatcher', function() {
    return new Phalcon\CLI\Dispatcher();
});

/**
 * Run application
 */
$app = new Phalcon\CLI\Console();
$app->setDI($di);
$app->handle($argv);

then i put my tasks classes in app/tasks folder.. and it just works. perhaps this will help somebody ;)