Lavavel 面向对象学习 - 代码修改前过程方法风格
Lavavel 面向对象学习 - 代码修改前过程方法风格
需求
看了网站中的 SOLID 设计原则,想尝试一下用面向对象的方法来写代码。
先构建一个需求,假设我想写一个接口,推送微信模板消息,输入用户id,查数据库得到openid,然后调用三方库直接发送模板消息,模板消息已经预先在微信公众号后台设置好,有4个参数。
代码是真实可用的。
修改前的代码
<?php
namespace App\Http\Controllers\Test;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\UserWx;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
class WechatPushController extends Controller
{
//微信推送模板消息接口
//原来的函数,直接写控制器里。
public function index(Request $request)
{
// 先根据用户id,查出openid。
$user_id = $request->input('user_id');
$user = User::find($user_id);
$openid='';
if ($user && $user->union_id) {
$wx_record = UserWx::query()->where('unionid', $user->union_id)->first();
if ($wx_record && $wx_record->openid ) {
$openid = $wx_record->openid;
}else {
return response()->json([
'code' => 400,
'errMsg'=>'用户未关注公司微信公众号,或关注记录没有保存openid字段'
])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
}
}else {
return response()->json([
'code' => 400,
'errMsg'=>'用户不存在,或用户没有union_id'
])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
}
$first = $request->input('first');
$keyword1 = $request->input('keyword1');
$keyword2 = $request->input('keyword2');
$remark = $request->input('remark');
// 设置微信app对象。
$config = [
'app_id' => config('yansongda.wechat.app_id'),
'secret' => config('yansongda.wechat_secret'),
'response_type' => 'array',
];
$app = Factory::officialAccount($config);
//{{first.DATA}}
//业务单号:{{keyword1.DATA}}
//办理进度:{{keyword2.DATA}}
//时间:{{keyword3.DATA}}
//{{remark.DATA}}
// 发送模板消息。
$app->template_message->send([
'touser' => $openid,
'template_id' => 'f9it7NnvjG1XyxtRCGoFo-V7u96TIhT1ZP2yUfE-zNs',
'url' => '',
'miniprogram' => [],
'data' => [
'first' => $first,
'keyword1' => $keyword1,
'keyword2' => $keyword2,
'keyword3' => date('Y-m-d H:i:s'),
'remark' => $remark,
],
]);
return response()->json(['code' => 200,]);
}
}
总结
1、代码清晰易懂,总共78行,但是一点都不面向对象。
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: