基于symfony搭建REST API

基于symfony搭建REST API(二)

2018-11-27  本文已影响66人  又起风了_

开始POST/GET/PUT/DELETE请求,以下操作都将在UserController.php文件中进行

  1. 声明UserController,继承FOSRestController类
/**
 * 根路径,使api router看起来像 http://xxx.xxx/api/v1/...
 * @Route("/v1")
 */
class UserController extends FOSRestController
{
  //pass...
}
  1. 创建新用户(POST)
    /**
     * 注册-生成用户
     *
     * @Rest\Post("/users")
     * @param Request $request
     * @return View
     */
    public function post(Request $request): View
    {
        $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 . '@163.com');
        }
        $em = $this->getDoctrine()->getManager();
        $em->persist($user);
        $em->flush();

        return View::create($user, Response::HTTP_CREATED);
    }
  1. 获取所有用户
     /**
     * 获取所有用户信息
     *
     * @Rest\Get("/users")
     * @return View
     */
    public function list() :View
    {
        $r = $this->getDoctrine()->getRepository(User::class);
        $users = $r->findAll();

        return View::create($users, Response::HTTP_OK);
    }
  1. 获取单个用户信息
    /**
     * 获取用户信息
     *
     * @Rest\Get("/users/{userId}")
     * @return View
     */
    public function getAction(int $userId) :View
    {
        $r = $this->getDoctrine()->getRepository(User::class);
        $user = $r->find($userId);
        return View::create($user, Response::HTTP_OK);
    }
  1. 更新用户信息(PUT)
    /**
     * 更新数据(项目复杂或兼容所有浏览器时,可使用POST代替)
     * @Rest\Put("/users/{userId}")
     * @return View
     */
    public function put(int $userId, Request $request) :View
    {
        $r = $this->getDoctrine()->getRepository(User::class);
        $user = $r->find($userId);
        //这里只修改mail
        if ($mail = $request->get('mail', '')) {
            $user->setMail($mail);
            //save
            $em = $this->getDoctrine()->getManager();
            $em->flush();
        }

        return View::create($user, Response::HTTP_OK);
    }
  1. 删除用户(DELETE)
    /**
     * @Rest\Delete("/users/{userId}")
     * @param int $userId
     * @return View
     */
    public function delete(int $userId) : View
    {
        $r = $this->getDoctrine()->getRepository(User::class);
        if ($user = $r->find($userId)) {
            //delete action
            $em = $this->getDoctrine()->getManager();
            $em->remove($user);
            $em->flush();
        }

        return View::create([], Response::HTTP_NO_CONTENT);
    }

以上,下节将介绍使用Service代替部分代码。

上一篇下一篇

猜你喜欢

热点阅读