yii2.0系列四:随时更新的小技巧

1.接口支持 POST 且前端不用修改

在 action 里设置:

	public $enableCsrfValidation = false;

2.添加返回 header:
	Yii::$app->response->headers->add('Access-Control-Allow-Origin','*');
 

3.使用 curl 发出请求,要用的时候经常要从网上查,这里记一下

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
// 把头信息记录到 output,改为0则不会有头信息
curl_setopt($ch, CURLOPT_HEADER, 1);
$output = curl_exec($ch);


4.使服务器可以解析 post 的 json 参数
 

        'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => 'xxx',
            'parsers' => [
                'application/json' => 'yii\web\JsonParser',
                'text/json' => 'yii\web\JsonParser',
            ],
        ],
这样当 post 的 Content-Type 是 application/json 或者 text/json 的时候,可以通过  Yii:: $app -> request ->post() 直接获取到解析后的 Array

5.配置服务器发送邮件

'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            // send all mails to a file by default. You have to set
            // 'useFileTransport' to false and configure a transport
            // for the mailer to send real emails.
            'useFileTransport' => false,
            'transport' => [
                'class'=>'Swift_SmtpTransport',
                'host' =>'smtp.exmail.qq.com',
                'username'=>'xxx',
                'password' =>'xxx',
                'port' => 25,
                'encryption' => 'tls'
            ],
            'messageConfig'=>[
                'charset'=>'UTF-8',
                'from' => ['xxx'=>'xxx']
            ],
        ],

然后发送邮件的代码如下:

        $mail = Yii::$app->mailer->compose();
        $mail->setTo($to);
        $mail->setSubject($subject);
        $mail->setHtmlBody($msg);
        if ($mail->send()) {
            //success
        } else {
            // fail
        }


6.bindActionParams 函数可以用于在调用 action 之前处理参数或者做某些前置检查,$params 是参数数组,可以直接用 $params['paramName'] 来获取参数值

    public function bindActionParams($action, $params)
    {
        // 这个链接要对外开放,直接放出去
//        if ($action->controller->id == 'file' && $action->id == 'listpic')  {
//            return parent::bindActionParams($action, $params);
//        }
        if ($action->controller->id == 'test')  {
            return parent::bindActionParams($action, $params);
        }
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值