为了减少UserController中的逻辑代码,可以把大部分的操作放到Service中来处理,这样使得控制器中的代码变得更简洁。
- 在Service目录下创建UserService类,具体代码如下:
<?php
/**
* Created by PhpStorm.
* User: mac
* Date: 2018/11/27
* Time: 下午2:02
*/
namespace App\Service;
use App\Entity\User;
use App\Repository\UserRepository;
use Symfony\Component\HttpFoundation\Request;
class UserService
{
/**
* @var UserRepository
*/
private $userRepository;
public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
/**
* @param int $userId
* @return User|null 返回一个User实例或Null
*/
public function getUser(int $userId): ?User
{
return $this->userRepository->find($userId);
}
/**
* 获取所有用户
*
* @return array|null
*/
public function getUsers(): ?array
{
return $this->userRepository->findAll();
}
/**
* 添加用户
*
* @param Request $request
* @return User
*/
public function addUser(Request $request): User
{
$user = new User();
$name = $request->get('name');
$user->setName($name);
$pass = $request->get('pass');
$encrypt_pass = password_hash(trim($pass), PASSWORD_BCRYPT);
$user->setPass($encrypt_pass);
if ($mail = $request->get('mail')) {
$user->setMail($mail);
} else {
$user->setMail($name . '@xxx.cn');
}
return $user;
}
/**
* 更新用户
*
* @param int $userId
* @param Request $request
* @return User|null
*/
public function updateUser(int $userId, Request $request) : ?User
{
$user = $this->userRepository->find($userId);
if (!$user) {
return null;
}
if ($mail = $request->get('mail')) {
$user->setMail($mail);
}
return $user;
}
}
- 修改UserController部分代码
#添加构造函数,把UserService实例放到$userService属性中
public function __construct(UserService $userService)
{
$this->userService = $userService;
}
/**
* 注册-生成用户
*
* @Rest\Post("/users")
* @param Request $request
* @return View
*/
public function post(Request $request): View
{
$user = $this->userService->addUser($request);
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
return View::create($user, Response::HTTP_CREATED);
}
/**
* 获取用户信息
*
* @Rest\Get("/users/{userId}")
* @return View
*/
public function getAction(int $userId) :View
{
$user = $this->userService->getUser($userId);
return View::create($user, Response::HTTP_OK);
}
/**
* 获取所有用户信息
*
* @Rest\Get("/users")
* @return View
*/
public function list() :View
{
$users = $this->userService->getUsers();
return View::create($users, Response::HTTP_OK);
}