Symfony和Wildurand/Hateoasbundle - JSON REPOSNSE没有链接



我正在使用fosrest和willdurand/hateoas捆绑包。我遵循的例子https://github.com/willdurand/hateoas#configuring-links

,但是JSON响应上没有"链接"字段。

/**
 * Users
 *
 * @ORMTable(name="users")
 * @ORMEntity
 * @SerializerExclusionPolicy("ALL")
 * @HateoasRelation("self", href="expr('/users' ~ object.getId())")
 */
class User
{
    /**
     * @var integer
     *
     * @ORMColumn(name="id", type="integer")
     * @ORMId
     * @ORMGeneratedValue(strategy="IDENTITY")
     * @SerializerGroups({"Default", "Deserialize"})
     * @SerializerExpose()
     */
    private $id;
    /**
     * @var string
     *
     * @ORMColumn(name="name", type="string", length=30)
     * @AssertNotBlank()
     * @AssertLength(max="30", min="5")
     * @SerializerGroups({"Default", "Deserialize"})
     * @SerializerExpose()
     */
    private $name;
    /**
     * @var string
     *
     * @ORMColumn(name="email", type="string", length=30)
     * @AssertNotBlank()
     * @AssertEmail()
     * @AssertLength(max="30")
     * @SerializerGroups({"Default", "Deserialize"})
     * @SerializerExpose()
     */
    private $email;
    /**
     * @var string
     *
     * @ORMColumn(name="username", type="string", length=15)
     * @AssertNotBlank()
     * @AssertLength(max="15", min="3")
     * @SerializerGroups({"Default", "Deserialize"})
     * @SerializerExpose()
     */
    private $username;
    /**
     * @var string
     *
     * @ORMColumn(name="password", type="string", length=32)
     * @AssertNotBlank()
     */
    private $password;
    /**
     * @var string
     *
     * @ORMColumn(name="active", type="boolean", length=32)
     * @SerializerGroups({"Default", "Deserialize"})
     * @SerializerExpose()
     */
    private $active = true;
    /**
     * @var ArrayCollection
     * @ORMManyToOne(targetEntity="AppBundleEntityRole", inversedBy="user")
     * @SerializerExpose()
     */
    private $roles;
    public function __construct()
    {
        $this->roles = new ArrayCollection();
    }
    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }
    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }
    /**
     * @param string $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }
    /**
     * @return string
     */
    public function getEmail()
    {
        return $this->email;
    }
    /**
     * @param string $email
     */
    public function setEmail($email)
    {
        $this->email = $email;
    }
    /**
     * @return string
     */
    public function getUsername()
    {
        return $this->username;
    }
    /**
     * @param string $username
     */
    public function setUsername($username)
    {
        $this->username = $username;
    }
    /**
     * @return string
     */
    public function getPassword()
    {
        return $this->password;
    }
    /**
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password = $password;
    }
    /**
     * @return string
     */
    public function getActive()
    {
        return $this->active;
    }
    /**
     * @param string $active
     */
    public function setActive($active)
    {
        $this->active = $active;
    }
    /**
     * @return Collection
     */
    public function getRoles()
    {
        return $this->roles;
    }
    /**
     * @param ArrayCollection $roles
     */
    public function setRoles($roles)
    {
        $this->roles = $roles;
    }
}

主要是我要显示一个指向角色实体的链接,但也许更容易找出是什么原因引起的,即使 self 链接,然后再进行。

这是配置

fos_rest:
    routing_loader:
        default_format: json
        include_format: false
    view:
        view_response_listener: 'force'
    body_converter:
        enabled: true
        validate: true
        validation_errors_argument: validationErrors
    param_fetcher_listener: true
    exception:
        enabled: true
        exception_controller: 'AppBundleControllerExceptionController::showAction'
    serializer:
        groups: ['Default']
sensio_framework_extra:
    view:
        annotations: true
    request:
        converters: true

此配置在所有端点都可以正常工作的含义很好,除了没有链接。

在这一点

[
  {
    "id": 1,
    "name": "Test name",
    "email": "test@email.com",
    "username": "toskadv",
    "active": true
  },
  {
    "id": 2,
    "name": "Test name",
    "email": "test@email.com",
    "username": "toskadv",
    "active": true
  },
  {
    "id": 3,
    "name": "Test name",
    "email": "test@email.com",
    "username": "toskadv",
    "active": true,
    "roles": {
      "id": 1,
      "name": "ROLE_USER"
    }
  }
]

还有控制器数据。

/**
 * Class UsersController
 * @package AppBundleController
 */
class UsersController extends AbstractController
{
    use ControllerTrait;
    /**
     * @RestView()
     */
    public function getUsersAction()
    {
        $users = $this->getDoctrine()->getRepository('AppBundle:User')->findAll();
        return $users;
    }
    /**
     * @param User $user
     * @param ConstraintViolationListInterface $validationErrors
     *
     * @RestView(statusCode=201)
     * @ParamConverter("user", converter="fos_rest.request_body")
     * @RestNoRoute()
     *
     * @return User $user
     */
    public function postUsersAction(User $user, ConstraintViolationListInterface $validationErrors)
    {
        if (count($validationErrors) > 0) {
            throw new ValidationException($validationErrors);
        }
        $em = $this->getDoctrine()->getManager();
        $role = $em->getRepository('AppBundle:Role')->find(1);
        $user->setRoles($role);
        $em->persist($user);
        $em->flush();
        return $user;
    }
    /**
     * @param User|null $user
     *
     * @RestView()
     */
    public function deleteUserAction(User $user = null) {
        if (null === $user) {
            return $this->view(null, 404);
        }
        $em = $this->getDoctrine()->getManager();
        $em->remove($user);
        $em->flush();
    }

    /**
     * @param User $user
     * @return User|FOSRestBundleViewView|null
     *
     * @RestView()
     */
    public function getUserAction(User $user)
    {
        if (null === $user) {
            return $this->view(null, 404);
        }
        return $user;
    }
    /**
     * @param Role $role
     * @return Role|FOSRestBundleViewView
     *
     * @RestView()
     */
    public function getRoleAction(Role $role)
    {
        if (null === $role) {
            return $this->view(null, 404);
        }
        return $role;
    }
    /**
     * @param User $user
     * @return DoctrineCommonCollectionsCollection
     *
     * @RestView()
     */
    public function getUserRolesAction(User $user)
    {
        return $user->getRoles();
    }
    /**
     * @param User $user
     * @param Role $role
     * @param ConstraintViolationListInterface $validationErrors
     *
     * @RestView(statusCode=201)
     * @ParamConverter("role", converter="fos_rest.request_body", options={"deserializationContext"={"groups"={"Deserialize"}}})
     * @RestNoRoute()
     *
     * @return Role
     */
    public function postUserRolesAction(User $user, Role $role, ConstraintViolationListInterface $validationErrors)
    {
        if (count($validationErrors) > 0) {
         throw new ValidationException($validationErrors);
        }
        $role->setUser($user);
        $em = $this->getDoctrine()->getManager();
        $user->getRoles()->add($role);
        $em->persist($user);
        $em->flush();
        return $role;
    }
}

问题是您返回实体,需要从序列化器传递才能获得Hateoas链接。

类似的东西:

我使用jsm_serializer

$serializer = $this->get('jms_serializer');
return new Response(
     $serializer->serialize(
         $users,
         'json',
         SerializationContext::create()->enableMaxDepthChecks()
     ),
     201
);

而不是这样:

return $users;

对我感到羞耻:/

问题是第一步,我只是没有在appkernel.php

中包含捆绑包
new BazingaBundleHateoasBundleBazingaHateoasBundle(),

这是一条缺失的行。没有借口。

相关内容

  • 没有找到相关文章

最新更新