How to load a component in console/shell

后端 未结 5 1647
耶瑟儿~
耶瑟儿~ 2020-12-20 17:22

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

5条回答
  •  庸人自扰
    2020-12-20 18:19

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

    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".)

    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/')
    

    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.

提交回复
热议问题