用php造了一个地址自动识别功能
地址自动识别现在普遍,特别是用在快递填写地址,姓名,手机号码的时候,会把这些按照一定的规范填写后,点击自动识别后,会自动填写到各自的input。最近也简单的实现了这个功能,给后台添加用户的时候,自动识别地址
具体问题具体分析!代码实现基于laravel完成。一个laravel完整的功能得具备这些:路由route,Model, View, Controller, 我这里用的有依赖注入服务容器等功能,当然,用到地址,你首先要有地址库。。。
下面来看看是如何实现的,这里我只贴出核心代码。
UsersController控制器
在这里新建构造函数,实现容器的依赖注入UsersRepository
/** @var UserRepository */
private $userRepository;
public function __construct(UsersRepository $userRepo)
{
$this->userRepository = $userRepo;
}
接下来就新建地址识别的方法, $discernDel 接收的数据是从前端传过来的,后面再贴前端代码。 业务代码处理交给容器UsersRepository里的方法getDiscern处理
/**
* Function:地址识别
* Author:Mr.Zhou
* @param Request $request
* @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response|
* \Laravel\Lumen\Http\ResponseFactory|\Symfony\Component\HttpFoundation\Response
*/
public function getDiscern(Request $request)
{
$discernDel = $request->input('discernDel');
try{
DB::beginTransaction();
$address = $this->userRepository->getDiscern($discernDel);
DB::commit();
}catch (\Exception $e){
DB::rollBack();
$msg = "信息提示:".$e->getMessage().",行:".$e->getLine();
return response(['code' => 0, 'msg'=>$msg]);
}
return response(['code'=>1,'msg'=>$address]); //地址识别完成
}
来看看userRepository容器处理地址识别的各种业务代码
/**
* Function:识别地址
* Author:Mr.Zhou
*/
public function getDiscern($discernDel)
{
if (empty($discernDel)) {
throw new \Exception("请传入要识别的地址");
}
$discernDel_left = explode ('[', $discernDel);
if (!isset($discernDel_left[1])) {
throw new \Exception("你填写的地址规则错误,手机号码应该用[]");
}
$discernDel_right = explode (']', $discernDel_left[1]);
if (!isset($discernDel_right[1]) || empty($discernDel_right[1])) {
throw new \Exception("你填写的地址规则错误,手机号码应该用[]");
}
$name = $discernDel_left[0];
if (empty($name)) {
throw new \Exception("你填写的姓名有误!");
}
$mobile = $discernDel_right[0];
if (empty($mobile) || checkMobile($mobile) == 0) {
throw new \Exception("你填写的手机号码格式有误!");
}