我发现自己陷入了Symfony 4项目中。实际上,我有一个实现Serializable的用户实体,以及两个serialize
和unserialize
(PHP)方法来序列化我的实体。
除了在某一点上我有一个循环参考问题。我看到我可以使用“深度选项”来纠正此问题。并且JMS Serializer可以轻松处理它。
所以我安装了JMS Serializer捆绑包。
但是在浏览了几个站点,几个文档之后,我不明白如何修改用户实体以使用JMS的序列化而不是PHP的序列化,并使用深度。
class User implements UserInterface, Serializable
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* Adresse email de l'utilisateur
* @ORM\Column(type="string", length=180, unique=true)
* @Assert\NotBlank()
* @Assert\Email(message="Veuillez renseigner un email valide")
*/
private $email;
/**
* Rôles de l'utilisateur
* @ORM\Column(type="json")
*/
private $roles = [];
/**
* Ordres de mission de l'utilisateur
* @ORM\OneToMany(targetEntity="App\Entity\OrdreMission", mappedBy="user")
* @MaxDepth(2)
*/
private $ordreMissions;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Entreprise", inversedBy="users")
* @ORM\JoinColumn(nullable=false)
* @MaxDepth(2)
*/
private $entreprise;
/**
* String representation of object
* @link http://php.net/manual/en/serializable.serialize.php
* @return string the string representation of the object or null
*/
public function serialize()
{
return serialize([
$this->id,
$this->email,
$this->password,
]);
}
/**
* Constructs the object
* @link http://php.net/manual/en/serializable.unserialize.php
* @param string $serialized <p>
* The string representation of the object.
* </p>
* @return void
*/
public function unserialize($serialized)
{
list (
$this->id,
$this->email,
$this->password,
) = unserialize($serialized);
}
我在“ ordreMission”和“ entreprises”属性上添加了@ MaxDepth(2),我想使用JMS序列化器序列化我的实体,并使用深度选项。
但是我不知道怎么做
您有两种方法可以使用JMSSerializerBundle:
直接从您的实体开始,使用@Annotations
ans @MaxDepth像这样:
namespace YourNamespace \ Entity;使用Doctrine \ ORM \ Mapping作为ORM;使用JMS \ Serializer \ Annotation作为序列化程序;使用JMS \ Serializer \ Annotation \ MaxDepth作为MaxDepth;
/**
* User
*
* @ORM\Table(name="user")
* @ORM\Entity(repositoryClass="YourBundle\Repository\ProgrammerRepository")
* @Serializer\ExclusionPolicy("all")
*/
class User implements UserInterface
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
* @Serializer\Expose
*/
private $id;
/*[...]*/
/**
* Ordres de mission de l'utilisateur
* @ORM\OneToMany(targetEntity="App\Entity\OrdreMission", mappedBy="user")
* @MaxDepth(2)
*/
private $ordreMissions;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Entreprise", inversedBy="users")
* @ORM\JoinColumn(nullable=false)
* @MaxDepth(2)
*/
private $entreprise;
}
从控制器代码执行操作:
$ serializer = $ container-> get('jms_serializer');$ serializer-> serialize($ user,'json');$ data = $ serializer->反序列化($ jsonData,'YourNamespace \ User','json');
带配置文件:请参见Configuration reference
希望这会有所帮助,