如何在控制台/ shell中加载组件 [英] How to load a component in console/shell
问题描述
在CakePHP中,如何在shell中加载组件?
In CakePHP, how do I load a component in a shell?
要在控制器中使用组件,您需要在属性$组件。这对我的壳不起作用。
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
。 (您应该重命名您的类以删除Component后缀,例如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屋!