在 CakePHP 中,如何在 shell 中加载组件?
要在 Controller 中使用组件,您需要在名为 $components 的属性中包含一组组件。这对我的 shell 牌不起作用。文档中也没有建议“即时”加载。
class MakePdfsShell extends Shell {
public $components = array('Document'); // <- this doesn't work
public function main()
{
$this->Document = $this->Components->load('Document'); // <- this doesnt work either
$this->Document->generate(); // <- this is what I want to do
}
...
最佳答案
我有一些 xml 实用程序,可以在我的一些 Controller 中使用。其中一个 Controller 通过 cake 控制台启动一个繁重的任务,这样它就可以通过 PHP CLI 在后台安静地运行,同时用户的请求立即完成(一旦任务完成,它会将结果通过电子邮件发送给用户) .
xml 实用程序足够通用,可以在 Controller 和 shell 程序中使用,但对于应用程序而言过于特定,无法保证它们的供应商地位。提供的带有 Lib 文件夹的解决方案不像 CakePhp v3
那样工作好像没有Lib
文件夹。
花费了相当长的时间后,我设法将我的 Controller 组件加载到 shell 任务中。以下是如何:
namespace App\Shell;
use Cake\Console\Shell;
use Cake\Core\App;
use Cake\Controller\Component;
use Cake\Controller\ComponentRegistry;
use App\Controller\Component\XmlUtilitiesComponent; // <- resides in your app's src/Controller/Component folder
class XmlCheckShell extends Shell
{
public function initialize() {
$this->Utilities = new XmlUtilitiesComponent(new ComponentRegistry());
}
...
$this->Utilities
现在可以在我的整个 shell 类中使用。
关于cakephp - 如何在控制台/shell 中加载组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28511023/