很多人做多年开发只懂得PHP能在浏览器下运行或者只能结合APACHE等WEB服务器运行,却不晓得,PHP也能用命令行执行,或许是由于大多人在WINDOWS平台做开发部署运行,比较少接触LINUX。
THINKPHP 在5.0对cli支持比较好,那么现在介绍一下,怎么用THINKPHP自带命令来运行一个 HELLO WORLD!
我们构建一个PHP命令 hello
#> php think hello
hello word !
代码示例
首先在application 文件夹下建立一个新文件夹command(用来放我们自定义的Tp命令) 我们取名叫Hello.php(随意取)
<?php namespace app\command; use think\console\Command; use think\console\Input; use think\console\input\Argument; use think\console\input\Option; use think\console\Output; use think\Request; class Hello extends Command{ //继承think\console\Command /** * 重写configure * {@inheritdoc} */ protected function configure() { $this->setName(‘hello‘) ->setDescription(‘hello word !‘); } /** * 重写execute * {@inheritdoc} */ protected function execute(Input $input, Output $output) { $output->writeln(‘hello word !‘); } } ?>
这样我们简单的hello命令就完成了.
可是现在我们cd 到tp根目录(就是有think这个php文件的目录) 执行php think hello 报错 : Command "hello" is not defined.
这是因为我们还缺少一个配置文件
编辑 application/command.php(没有就新建) 加上Hello.php文件的namespace
<?php return [ "app\\command\\Hello", ]; ?>
大功告成!
很多人会问,在浏览器能执行,还要这个命令行干什么,有什么用?
其实作用还是比较多的,比如需要定时生成报表等,可以通过cli命令在服务器内定期执行。
原文:https://www.cnblogs.com/vxianfeng/p/9803392.html