使用ZF2框架将选项传递给php脚本


Passing options to php script using ZF2 framework

我的应用程序使用Zend Framework 2,我试图通过命令行运行时将一些选项传递给它:

php index.php generate --date="2015-01-01"

然而,我得到错误:Invalid arguments or no arguments provided

我的控制器看起来像:

namespace Application'Controller;
use Zend'Mvc'Controller'AbstractActionController;
class GenerateController extends AbstractActionController
{
    public function indexAction()
    { 
        $longopts = array(
            'date::',
        );
        $opts = getopt('', $longopts);     
        if (isset($opts['date'])) {
            $date = $opts['date'];
        } else {
            $date = date('Y-m-d');
        }
        var_dump($date);
        die();
    }
}

我希望var_dump显示选项中提供的日期或今天的日期。脚本运行,但只给出上述错误。非常感谢任何帮助。

我的module.config.php功能正常:

// Placeholder for console routes
'console' => array(
    'router' => array(
        'routes' => array(
            'get-happen-use' => array(
                'options' => array(
                    //php index.php get happen --verbose apache2
                                // add [ and ] if optional ( ex : [<doname>] )
                    'route' => 'generate', 
                    'defaults' => array(
                        '__NAMESPACE__' => 'Application'Controller',
                        'controller' => 'generate',
                        'action' => 'index'
                    ),
                ),
            ),
        )
    )
),

你需要在route中定义你的控制台参数或标志。根据文档,你的路由定义应该看起来像

'route' => 'generate [--date=]',

用于可选值flag date,或者如果flag date是必选值:

'route' => 'generate --date=',

然后你可以从request (documentation):

访问控制器中这个标志的值。
$date = $this->getRequest()->getParam('date', null); // default null