从命令行运行 Zend Framework 操作

时间:2023-05-05
本文介绍了从命令行运行 Zend Framework 操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我想从命令行运行 Zend Framework 操作以生成一些文件.这可能吗?我需要对使用 ZF 的现有 Web 项目进行多少更改?

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 that is using ZF?

谢谢!

推荐答案

这实际上比您想象的要容易得多.引导程序/应用程序组件和您现有的配置可以与 CLI 脚本重用,同时避免在 HTTP 请求中调用的 MVC 堆栈和不必要的权重.这是不使用 wget 的优势之一.

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.

像您的公共 index.php 一样启动您的脚本:

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'));

然后您可以像在 MVC 应用程序中一样继续使用 ZF 资源:

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');

如果您希望向 CLI 脚本添加可配置参数,请查看 Zend_Console_Getopt

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

如果您发现自己也有在 MVC 应用程序中调用的通用代码,请考虑将其封装在一个对象中,并从 MVC 和命令行应用程序调用该对象的方法.这是一般的良好做法.

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.

这篇关于从命令行运行 Zend Framework 操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:如何将变量作为标准输入从 PHP 传递到命令行 下一篇:如何从命令行执行 PHP 代码?

相关文章