【问题标题】:Integrating existing pages in a Zend Framework application在 Zend Framework 应用程序中集成现有页面
【发布时间】:2010-08-06 23:09:03
【问题描述】:

是否可以绕过 Zend Framework 网站中的任何控制器?相反,我希望执行一个普通的 PHP 脚本,并且它的所有输出都应该放在来自 ZF 的布局/视图中:

请求 --> 执行 PHP 脚本 --> 捕获输出 --> 将输出添加到视图 --> 发送响应

挑战是将现有页面/脚本集成到新创建的 Zend Framework 站点中,该站点使用 MVC 模式。

干杯

【问题讨论】:

  • 问得好,我认为你在正确的轨道上。

标签: php zend-framework


【解决方案1】:

我在.htaccess 文件中创建了一个新条目:

RewriteRule (.*).php(.*)$ index.php [NC,L]

现在对普通 .php 文件的每个请求都由 ZF 的 index.php 处理。

接下来我创建了一个额外的路由来将这些请求路由到某个控制器操作:

$router->addRoute(
  'legacy',
  new Zend_Controller_Router_Route_Regex(
    '(.+)\.php$',
    array(
      'module' => 'default',
      'controller' => 'legacy',
      'action' => 'index'
    )
  )
);

这是适当的操作:

public function indexAction() {
  $this->_helper->viewRenderer->setNoRender();
  $this->_helper->layout->setLayout('full');

  // Execute the script and catch its output
  ob_start();
  require($this->_request->get('DOCUMENT_ROOT') . $this->_request->getPathInfo());
  $output = ob_get_contents();
  ob_end_clean();

  $doc = new DOMDocument();
  // Load HTML document and suppress parser warnings
  @$doc->loadHTML($output);

  // Add keywords and description of the page to the view
  $meta_elements = $doc->getElementsByTagName('meta');
  foreach($meta_elements as $element) {
    $name = $element->getAttribute('name');
    if($name == 'keywords') {
      $this->view->headMeta()->appendName('keywords', $element->getAttribute('content'));
    }
    elseif($name == 'description') {
      $this->view->headMeta()->appendName('description', $element->getAttribute('content'));
    }
  }

  // Set page title
  $title_elements = $doc->getElementsByTagName('title');
  foreach($title_elements as $element) {
    $this->view->headTitle($element->textContent);
  }

  // Extract the content area of the old page
  $element = $doc->getElementById('content');
  // Render XML as string
  $body = $doc->saveXML($element);

  $response = $this->getResponse();
  $response->setBody($body);
}

非常有用:http://www.chrisabernethy.com/zend-framework-legacy-scripts/

【讨论】:

  • +1 引用 Chris Abernethy 页面,这很棒。
  • @user413773:您如何处理对 site.com/news/ 的请求,该请求应该是 site.com/news/index.php 而不是NewsController::indexAction()
【解决方案2】:

在您的控制器(或模型)中,您可以添加:

$output = shell_exec('php /local/path/to/file.php');

此时您可以根据需要解析和清理$output,然后将其存储在您的视图中。

您可以将要执行的 php 文件存储在 scripts 目录中。

如果 PHP 文件存储在远程服务器上,您可以使用:

$output = file_get_contents('http://www.example.com/path/to/file.php');

【讨论】:

  • 我不认为shell_exec() 填充了可能导致php 脚本无法运行的$_SERVER 变量。
【解决方案3】:

在你的视图中创建一个标准的 php include/require 来嵌入你的 php 脚本的输出

【讨论】:

  • 除非您从视图中调用它,否则它将不起作用,否则它将仅放置在实际视图内容之后。此外,根据输出的格式,可能会有一些额外的标签需要解析出来(HTML、HEAD、BODY 等)。在控制器和/或模型中处理它可能会更好,而不是在视图中。
猜你喜欢
  • 2010-11-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-17
  • 2021-06-28
  • 2012-09-15
  • 2011-02-21
  • 1970-01-01
  • 2011-04-05
相关资源
最近更新 更多