【问题标题】:CakePHP shell to use existing MVC to create pdf from view outputCakePHP shell 使用现有的 MVC 从视图输出创建 pdf
【发布时间】:2012-11-09 20:58:37
【问题描述】:

使用 CakePHP 1.3 我有一个带有方法 single_invoice($customer_id) 的现有 InvoicesController,并且在正常使用时一切正常。但是,我想通过 cake shell 做同样的事情并将其构建为 cronjob。

我创建了 shell,它确实作为 cronjob 运行,所以这不是问题。问题是我无法从 cronjob 获取视图。基本上,这是我目前所拥有的:

class InvoiceCreationShell extends Shell {

    var $uses = array('Institution');

    function main()
    {
        $institutions = $this->Institution->find('all');

        foreach ($institutions as $institution)
        {
            App::import('Core', 'Controller');
            App::import('Controller', 'Invoices');

            $Invoices = new InvoicesController;
            $Invoices->constructClasses();

            $invoice = $Invoices->single_invoice();

            $pdf = create_pdf($invoice);

            file_put_contents($pdf);
        }
    }
}

我希望通过 $invoice 参数返回呈现的视图内容。

【问题讨论】:

    标签: php cakephp cakephp-1.3


    【解决方案1】:

    您不能这样做,因为 Shell 用于 CLI 应用程序,其中 PHP 环境与通过 Web 服务器(如 Apache 或 Nginx)调用的环境不同。

    但是,您仍然可以使用现有的 Web 应用程序功能,并且您有两种选择:

    1. 初始化一个控制器对象

      以下代码示例适用于 CakePHP >= 2.x

      抱歉,最初我没有看到问题是关于 1.3。在这种情况下,第 2 点有一个很好的建议。还有一种方法可以在 CakePHP1.3 中初始化 Controller 对象 - this for example

      在这种情况下,这实际上取决于您的发票生成的实施方式。请记住,视图部分是“不可能的”。因此,如果您渲染到一个变量,然后从该变量创建 pdf(例如),您仍然可以得到它。诀窍是如何在 Shell 中初始化控制器对象:

      首先包括所需的类:

      App::import('Controller','Controller'); App::import('Controller', 'initializedController');

      在 Shell/Task 中有一个变量:

      私有 $initializedController;

      然后:

      $this->initializedController = new initializedController(new CakeRequest('/'), new CakeResponse()); $this->initializedController->constructClasses(); $this->initializedController->startupProcess();

    现在你可以调用Controller中的所有方法了。

    2.向现有WebApp发出HTTP请求

    这可以通过 CakePHP 自己的 HttpSocket Class 或一些请求库如 Guzzle 来实现。

    【讨论】:

      【解决方案2】:

      在与许多人交谈后,我得出的结论是,使用 shell 中的视图是不可能的,在这里和 IRC 一样发帖。所以这是我解决问题的方法:

      我没有尝试让视图从 shell 输出,而是简单地从控制器中渲染视图。以下是控制器解决此问题的示例:

      class InvoicesController extends AppController {
      
          function single_invoice($institution_id)
          {
              /* Do stuff */
      
              return $this->render('single_invoice', 'invoice_layout');
          }
      }
      

      这允许 shell 在 $invoice 参数中捕获渲染视图的内容,然后将其传递给 pdf 生成器。

      我还在 $is_shell 的 single_invoice 操作中添加了一个参数,未显示。然后我将 return $this->render... 包围在 "if ($is_shell) {" 中,检查仅在 shell 使用时才渲染。

      【讨论】:

        猜你喜欢
        • 2011-04-16
        • 1970-01-01
        • 2011-08-01
        • 2018-09-04
        • 2018-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多