接上一篇:基于yii2的blog系统开发9-授权ACF&RBAC:
第十七步 控制台命令程序的创建和执行
1.在console/controllers/目录下新建HelloController.php:
<?php
namespace console\controllers;
use Yii;
use yii\console\Controller;
class HelloController extends Controller
{
public function actionIndex()
{
echo "hello console!\n";
}
}
2.在项目目录下执行 ./yii 控制器名/action函数名 即可执行该函数
root@debian:/opt/lampp/htdocs/dev/advanced# ./yii hello/index
hello console!
root@debian:/opt/lampp/htdocs/dev/advanced#
3.带参数的控制台程序:
public function actionHello($name)
{
echo "hello".$name."\n";
//./yii hello/hello haha
}
public function actionHelloArray(array $names)
{
var_dump($names);
/*
root@debian:/opt/lampp/htdocs/dev/advanced# ./yii hello/hello-array haha,qi,a
array(3) {
[0]=>
string(4) "haha"
[1]=>
string(2) "qi"
[2]=>
string(1) "a"
}
*/
}
4.带选项的控制台程序:
<?php
namespace console\controllers;
use Yii;
use yii\console\Controller;
class HelloController extends Controller
{
//选项
public $rev;
public function options($actionID)
{
return ['rev'];
}
public function optionAliases()
{
return ['r'=>'rev'];
}
public function actionChoose()
{
if($this->rev==1){echo "1\n";}
else{echo "2\n";}
}
/*
*
root@debian:/opt/lampp/htdocs/dev/advanced# ./yii hello/choose -r=1
1
root@debian:/opt/lampp/htdocs/dev/advanced# ./yii hello/choose -r=2
2
root@debian:/opt/lampp/htdocs/dev/advanced# ./yii hello/choose --rev=2
2
root@debian:/opt/lampp/htdocs/dev/advanced# ./yii hello/choose --rev=1
1
*/
//选项end
public function actionIndex()
{
echo "hello console!\n";
}
public function actionHello($name)
{
echo "hello".$name."\n";
//./yii hello/hello haha
}
public function actionHelloArray(array $names)
{
var_dump($names);
}
//./yii hello/send 发邮件mailer
public function actionSend(){
// return "sendmail";
$mail= Yii::$app->mailer->compose();
$mail->setFrom('7138784@qq.com');
$mail->setTo('nbllq@qq.com');
$mail->setSubject("mail-test");
//$mail->setTextBody('txtxtxtx'); //发布纯文字文本
$mail->setHtmlBody("<br>askme"); //发布可以带html标签的文本
if($mail->send())
return "success";
else
return "fail";
}
}