如何在控制台/shell 中加载组件 [英] How to load a component in console/shell

查看:22
本文介绍了如何在控制台/shell 中加载组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 CakePHP 中,如何在 shell 中加载组件?

In CakePHP, how do I load a component in a shell?

要在控制器中使用组件,您需要在名为 $components 的属性中包含一组组件.这对我的壳牌不起作用.文档中也没有建议即时"加载.

To use a component in a controller, you include an array of components in a property called $components. That doesn't work for my Shell. Neither does the "on-the-fly" loading suggested in the documentation.

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
    }
    ...

推荐答案

如果您正在尝试从 shell 访问自定义 XyzComponent,那么您可能在那里拥有常用功能.常用功能(也可以从 shell 访问)的正确位置在 /Lib/ 中.

If you are trying to access a custom XyzComponent from a shell, then you probably have commonly-useful functionality there. The right place for commonly-useful functionality (that is also accessible from shells) is in /Lib/.

您可以将旧的 XyzComponent 类从 /Controller/Component/XyzComponent.php 移动到 /Lib/Xyz/Xyz.php.(您应该重命名您的类以删除组件"后缀,例如,XyzComponent"变为Xyz".)

You can just move your old XyzComponent class from /Controller/Component/XyzComponent.php to /Lib/Xyz/Xyz.php. (You should rename your class to remove the "Component" suffix, e.g., "XyzComponent" becomes "Xyz".)

要访问新位置,请在控制器中从 class::$components 数组中删除Xyz".在控制器文件的顶部,添加

To access the new location, in your controller, remove 'Xyz' from your class::$components array. At the top of your controller file, add

App::uses('Xyz', 'Xyz'); // that's ('ClassName', 'folder_under_/Lib/')

现在你只需要实例化这个类.在您的方法中,您可以执行 $this->Xyz = new Xyz(); 现在您使用相同的代码,但也可以从您的 Shell 访问它.

Now you just need to instantiate the class. In your method you can do $this->Xyz = new Xyz(); Now you're using the same code, but it can also be accessed from your Shell.

这篇关于如何在控制台/shell 中加载组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆