Ankit Singh
Ankit Singh

Reputation: 922

Zend Framework 1.12 Console commands

I'm using Zend Framework 1.12. I know it's too old and that's why not finding much support so putting this question here.

I have CronController and I'm calling it through curl request and its not a good approach. As the name specifies, I want to call its functions through the command-line. Please suggest how can I achieve this.

I have tried implementing https://docs.zendframework.com/zend-console/intro/ but it didn't help much.

Thanks in advance.

Upvotes: 2

Views: 775

Answers (1)

Daniel Gadawski
Daniel Gadawski

Reputation: 1923

I assume that CronController is class extending Zend_Controller_Action like this:

class CronController extends Zend_Controller_Action
{
    public function processAction()
    {
        // some very important logic
    }
}

If so, don't use this in your CLI calls. Zend_Controller_Action should be used rather with HTTP requests, not CLI calls.

Move your business logic from this controller to separate classes, i.e.:

class My_Logic
{
    public function process($options)
    {
        // some very important logic
    }
}

Then, following DRY principle, create instance of this class in your controller:

class CronController extends Zend_Controller_Action
{
    public function processAction()
    {
        $logic = new My_Logic();
        $logic->process();
    }
}

Now, create bin directory in root path of your project and put there your CLI script (i.e. cron.php):

defined('APPLICATION_PATH')
        || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));

// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
        realpath(APPLICATION_PATH . '/../library'),
        get_include_path(),
)));

require_once 'Zend/Loader/Autoloader.php';
Zend_Loader_Autoloader::getInstance();

$optsConfig = array(
    'app_env=s' => 'Application environment name',
);

$opts = new Zend_Console_Getopt($optsConfig);
$opts->setOptions(
    array(
        'ignoreCase' => true,
        'dashDash'   => false,
    )
);
$opts->parse();

defined('APPLICATION_ENV')  || define('APPLICATION_ENV', $opts->app_env);

/** Zend_Application */
require_once 'Zend/Application.php';

// Create application, bootstrap, and run
$application = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . '/configs/application.ini'
);

$application->getBootstrap()->bootstrap();

class CronCli
{
    public function doProcessing()
    {
        $logic = new My_Logic();

        // here's your logic, the same as in controller
        $logic->process();
    }
}

$cmd = new CronCli($opts);
$cmd->doProcessing();

Now, you can call this script in your project's main directory:

php bin/cron.php --app_env production

production is your APP_ENV value name from application/configs/application.ini

Upvotes: 2

Related Questions