ThinkPHP 5.1 自定义命令调用其他控制器方法的
在ThinkPHP 5.1中,自定义命令和控制器运行在不同的环境下:命令行环境和HTTP请求环境。直接在自定义命令中调用控制器方法会因为差异而失败。
问题描述:尝试在自定义命令中调用同一目录下的其他控制器方法,但执行失败。
解决方案:
为了在自定义命令中成功调用控制器方法,需要手动实例化控制器对象,然后调用其方法。 这可以通过使用call方法或直接实例化控制器来实现。
以下示例演示了如何通过直接实例化控制器来解决这个问题:
<?php use thinkconsoleCommand; use thinkconsoleInput; use thinkconsoleOutput; // 引入需要调用的控制器 use appcommonconsoleCommandNewCommand; class RedisListener extends Command { protected function configure() { $this->setName('aaa')->setDescription('监听Redis的过期事件'); } protected function execute(Input $input, Output $output) { // 实例化NewCommand控制器 $test = new NewCommand(); // 调用NewCommand控制器的index方法 $test->index(); } }
登录后复制
通过这种方式,RedisListener 命令就能成功调用 NewCommand 控制器中的 index 方法。 请确保正确引入目标控制器类。
以上就是TP5.1自定命令如何调用其他控制器方法?的详细内容,更多请关注php中文网其它相关文章!