在 Drupal 中使用 Zend 框架
如果您想在Drupal中使用ZendFramework,那么大多数时候您可以使用Zend模块。这需要一些配置,但将包括框架并实例化Zend_Loader_Autoloader类,以便一切准备好运行。
Zend模块有许多不同的策略来包含框架,如果您想或不想使用库模块,这会很方便。该模块使用hook_init()钩子来包含和实例化Zend_Loader_Autoloader对象,这意味着这在每次页面加载时完成;即使没有使用该框架。
对于我的特定用例,这是不可接受的,因为我仅在需要时使用ZendFramework的单个组件来调用第三方API。因此,我需要一种替代方法,这让我创建了一个函数,可以按需自动加载框架自动加载器。我选择将ZendFramework包含在模块目录中,以便我正在处理的模块是独立的。如果需要,这可以很容易地更改为另一个目录。
function mymodule_autoload_zend() { $zend_path = realpath(drupal_get_path('module', 'mymodule')); set_include_path(get_include_path() . PATH_SEPARATOR . $zend_path); require_once 'Zend/Loader/Autoloader.php'; Zend_Loader_Autoloader::getInstance(); }
这意味着当我需要运行一些ZendFramework特定的代码时,我可以调用这个函数并照常继续。下面是一个使用LiveDocxAPI基于给定模板文件创建PDF文档的示例。
function mymodule_generate_pdf($filename, $arguments, $template) { //包括Zend mymodule_autoload_zend(); //获取模板位置 $module_dir = drupal_get_path('module', 'mymodule'); $template_file = realpath($module_dir . '/templates/' . $template); if (!file_exists($template_file)) { drupal_set_message('Template file "' . $template . '" not found in templates folder.', 'error'); return FALSE; } $phpLiveDocx = new Zend_Service_LiveDocx_MailMerge(); //登录LiveDocx $phpLiveDocx->setUsername('username')->setPassword('password'); //设置模板 $phpLiveDocx->setLocalTemplate($template_file); //将数据分配给模板 foreach ($arguments as $key => $value) { $phpLiveDocx->assign($key, $value); } $phpLiveDocx->createDocument(); $document = $phpLiveDocx->retrieveDocument('pdf'); //将新文档保存到文件 $document_location = realpath(file_directory_path()) . '/pdfs'; file_put_contents($document_location . '/' . $filename . '.pdf', $document); return $document_location . '/' . $filename . '.pdf'; }
可以对这个脚本做更多的事情来改进文件名冲突等问题,但它只是为了提供一个简单的例子。假设您已经设置了模板,您可以通过以下方式运行它。
mymodule_generate_pdf('the_file',array('key'=>'value'),'template.docx');
ZendFramework有许多不同的组件,它们可以像LiveDocx一样用作类中的drop。仅使用几行代码意味着您可以拉入您需要的任何类并立即开始使用它。无论您使用Zend模块还是mymodule_autoload_zend()方法取决于您的要求,但它们都使用本质上相同的代码,因此可以在需要时进行交换。
本文专门针对Drupal7编写,但这些原则也应适用于Drupal6和8。