問題描述
我想從命令行運行 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 操作的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!