Running a Zend Framework action from command line

后端 未结 10 1308
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 17:01

I would like to run a Zend Framework action to generate some files, from command line. Is this possible and how much change would I need to make to my existing Web project t

相关标签:
10条回答
  • 2020-11-29 17:26

    UPDATE

    You can have all this code adapted for ZF 1.12 from https://github.com/akond/zf-cli if you like.

    While the solution #1 is ok, sometimes you want something more elaborate. Especially if you are expecting to have more than just one CLI script. If you allow me, I would propose another solution.

    First of all, have in your Bootstrap.php

    protected function _initRouter ()
    {
        if (PHP_SAPI == 'cli')
        {
            $this->bootstrap ('frontcontroller');
            $front = $this->getResource('frontcontroller');
            $front->setRouter (new Application_Router_Cli ());
            $front->setRequest (new Zend_Controller_Request_Simple ());
        }
    }
    

    This method will deprive dispatching control from default router in favour of our own router Application_Router_Cli.

    Incidentally, if you have defined your own routes in _initRoutes for your web interface, you would probably want to neutralize them when in command-line mode.

    protected function _initRoutes ()
    {
        $router = Zend_Controller_Front::getInstance ()->getRouter ();
        if ($router instanceof Zend_Controller_Router_Rewrite)
        {
            // put your web-interface routes here, so they do not interfere
        }
    }
    

    Class Application_Router_Cli (I assume you have autoload switched on for Application prefix) may look like:

    class Application_Router_Cli extends Zend_Controller_Router_Abstract
    {
        public function route (Zend_Controller_Request_Abstract $dispatcher)
        {
            $getopt = new Zend_Console_Getopt (array ());
            $arguments = $getopt->getRemainingArgs ();
            if ($arguments)
            {
                $command = array_shift ($arguments);
                if (! preg_match ('~\W~', $command))
                {
                    $dispatcher->setControllerName ($command);
                    $dispatcher->setActionName ('cli');
                    unset ($_SERVER ['argv'] [1]);
    
                    return $dispatcher;
                }
    
                echo "Invalid command.\n", exit;
    
            }
    
            echo "No command given.\n", exit;
        }
    
    
        public function assemble ($userParams, $name = null, $reset = false, $encode = true)
        {
            echo "Not implemented\n", exit;
        }
    }
    

    Now you can simply run your application by executing

    php index.php backup
    

    In this case cliAction method in BackupController controller will be called.

    class BackupController extends Zend_Controller_Action
    {
        function cliAction ()
        {
            print "I'm here.\n";
        }
    }
    

    You can even go ahead and modify Application_Router_Cli class so that not "cli" action is taken every time, but something that user have chosen through an additional parameter.

    And one last thing. Define custom error handler for command-line interface so you won't be seeing any html code on your screen

    In Bootstrap.php

    protected function _initError ()
    {
        $error = $frontcontroller->getPlugin ('Zend_Controller_Plugin_ErrorHandler');
        $error->setErrorHandlerController ('index');
    
        if (PHP_SAPI == 'cli')
        {
            $error->setErrorHandlerController ('error');
            $error->setErrorHandlerAction ('cli');
        }
    }
    

    In ErrorController.php

    function cliAction ()
    {
        $this->_helper->viewRenderer->setNoRender (true);
    
        foreach ($this->_getParam ('error_handler') as $error)
        {
            if ($error instanceof Exception)
            {
                print $error->getMessage () . "\n";
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-29 17:28

    It's actually much easier than you might think. The bootstrap/application components and your existing configs can be reused with CLI scripts, while avoiding the MVC stack and unnecessary weight that is invoked in a HTTP request. This is one advantage to not using wget.

    Start your script as your would your public index.php:

    <?php
    
    // Define path to application directory
    defined('APPLICATION_PATH')
        || define('APPLICATION_PATH',
                  realpath(dirname(__FILE__) . '/../application'));
    
    // Define application environment
    defined('APPLICATION_ENV')
        || define('APPLICATION_ENV',
                  (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV')
                                             : 'production'));
    
    require_once 'Zend/Application.php';
    $application = new Zend_Application(
        APPLICATION_ENV,
        APPLICATION_PATH . '/configs/config.php'
    );
    
    //only load resources we need for script, in this case db and mail
    $application->getBootstrap()->bootstrap(array('db', 'mail'));
    

    You can then proceed to use ZF resources just as you would in an MVC application:

    $db = $application->getBootstrap()->getResource('db');
    
    $row = $db->fetchRow('SELECT * FROM something');
    

    If you wish to add configurable arguments to your CLI script, take a look at Zend_Console_Getopt

    If you find that you have common code that you also call in MVC applications, look at wrapping it up in an object and calling that object's methods from both the MVC and the command line applications. This is general good practice.

    0 讨论(0)
  • 2020-11-29 17:31

    One option is that you could fudge it by doing a wget on the URL that you use to invoke the desirable action

    0 讨论(0)
  • 2020-11-29 17:31

    You cant use -O option of wget to save the output. But wget is clearly NOT the solution. Prefer using CLI instead.

    0 讨论(0)
提交回复
热议问题