1.控制器的靈活性(支持Ajax)
控制器要支持普通請(qǐng)求和AJAX請(qǐng)求,體現(xiàn)在參數(shù)的獲取以及結(jié)果返回。
比如:
public function update(Request $request, $model_id = 0)
{
try {
// 參數(shù)獲取
if (!$model_id) {
$model_id = $request->get("model_id");
if (!$model_id) {
throw new \Exception("Invalid input", "4007");
}
}
//邏輯處理
//結(jié)果返回
if ($request->ajax()) {
return Response::json([
"errcode" => "0000",
"errmsg" => "Success"
]);
} else {
return redirect() -> to('/admin/user/wxtmpl/show'."/".$model->id) -> with("message", "更新消息成功");
}
} catch (\Exception $e) {
info(__METHOD__."\n".$e->getTraceAsString());
info($e->getCode()." | ".$e->getMessage());
if ($request->ajax()) {
return Response::json([
"errcode" => $e->getCode()? $e->getCode(): "5000",
"errmsg" => $e->getMessage(),
], JSON_UNESCAPED_UNICODE);
} else {
return redirect()->back()->withInput()->withErrors([
"fail" => $e->getMessage(),
]);
}
}
}
2.參數(shù)的合法性驗(yàn)證
在Laravel里面,提供了Validator門面來(lái)進(jìn)行參數(shù)合法性驗(yàn)證 。
use Illuminate\Support\Facades\Validator;
//基本用法
$validator = Validator::make($request->all(), [
"first" => "required",
], [
"first.required" => "請(qǐng)?zhí)顚?xiě)first",
]);
if ($validator->fails()) {
$msg = $validator->messages()->first();
throw new \Exception($msg);
}
//自定義錯(cuò)誤信息,在本例中,:attribute占位符將會(huì)被驗(yàn)證時(shí)實(shí)際的字段名替換
//你還可以在驗(yàn)證消息中使用其他占位符
$messages = [
"same" => "The :attribute and :other must match",
"size" => "The :attribute must be exactly :size"
];
3.框架調(diào)用命令行
$exitCode = Artisan::call("shencom:get:tags:list:wx", ["acctid" => $acct_id])
即,使用Artisan門面的call函數(shù)。
4.RequestOnly
$data = $request->only([
"name", "desc", "logo", "cate_id"
]);
可獲得和下面語(yǔ)句相同的效果
$data = array(
"name" => $request->get["name"],
"desc" => $request->get["desc"],
....
);
5.Transaction事務(wù)
在查看文章的時(shí)候給文章的瀏覽量增加1。
//控制器中的方法
public function articleDetail($route, $id){
try{
\DB::transaction(function() use($id){
Article::addViewCnt($id);
});
}
}
//模型中的方法
use SC\Forum\Models\Article as BaseArticle;
class Article extends BaseArticle{
public static function addViewCnt( $article_id ){
$result = Static::find($article_id);
if($result){
$result->read)cnt += 1;
$result->save();
return true;
}else{
return false;
}
}
}
6.在Laravel5.1中使用SMTP驅(qū)動(dòng)實(shí)現(xiàn)郵件發(fā)送
參考
在config/mail.php里面做如下配置
return[
'driver' => 'smtp',
'host' => 'smtp.qq.com',
'port' => 465,
'from' => ['address' => '893302826@qq.com', 'name' => 'LeoStupidWise'],
'encryption' => 'ssl',
'username' => '893302826@qq.com',
'password' => 'lxmixneovtxnbfgf',
'sendmail' => '/usr/sbin/sendmial -bs',
'pretend' => false,
]
HOST:郵箱所在主機(jī),163對(duì)應(yīng)smtp.163.com,QQ使用smtp.qq.com,其實(shí)還有更復(fù)雜的情況,QQ郵箱可以在郵箱設(shè)置里面去看到。
PORT:郵箱發(fā)送服務(wù)端口號(hào),默認(rèn)25,如果設(shè)置SMTP的SSL加密,該值為465。嘗試時(shí),25端口沒(méi)有發(fā)送成功,只有設(shè)置SSL在465才能發(fā)送成功。
FROM:address表示發(fā)送郵箱,name表示發(fā)送郵箱使用的用戶名。
ENCRYPTION:加密類型,null表示不加密,也可以設(shè)置為tls/ssl。
USERNAME:表示郵箱賬號(hào)。
PASSWORD:表示登陸郵箱對(duì)應(yīng)的授權(quán)碼,QQ郵箱在設(shè)置中能獲取。
PRETEND:是否將郵件發(fā)送記錄到日志中。