(1) 新建一个command类,并在command类里面写相应的执行函数
其中变量act就是指函数名,handle里面会先判断该函数是不是存在,如果存在就执行,如果不存在就提示函数不存在
class UploadTeachingMaterials extends Command
{
protected $signature = 'uploadMaterials {act} {--folder=}';
protected $description = '上传教材';
/**
* 执行控制台命令
*/
public function handle()
{
$method = $this->argument('act');
if (method_exists($this, $method)) {
$this->$method();
echo "执行完成
";
} else {
echo "${method} is not exists
";
}
}
public function test()
{
xxxxxxx;
}
}
应先填写类的 signature 和 description 属性,这会在使用 list 命令的时候显示出来。执行命令时会调用 handle 方法,你可以在这个方法中放置命令逻辑。
到相应的目录下:比如你的laravel项目名叫test,那你就应该在test/目录下执行
php artisan list

(2)在kernel.php中注册该类
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
CommandsTeachingMaterialsUploadTeachingMaterials::class,
];
/**
* Define the application's command schedule.
*
* @param IlluminateConsoleSchedulingSchedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
}
}
(3)执行该command命令
php artisan uploadMaterials 方法名 --folder=变量名
注意:
在执行command的命令的时候,为了对用户更友好,要有输出结果和提示,同时要进行错误处理,将异常和错误,或者其他有用的信息放到日志中。
转载:https://www.cnblogs.com/cjjjj/p/9754962.html
