最近,我开始在我的所有代码中添加严格的类型。例如,现在我有了一个Doctrine实体,如:
<?php
namespace App\Entity;
class Post
{
private string $title;
private User $creator;
public function __construct(string $title, User $creator)
{
$this->title = $title;
$this->creator = $creator;
}
...
}为了演示Symfony自动化测试用例,我目前创建Post实体,而不提供JSON字符串中的用户:
$client->request(
'POST',
'/api/post',
[],
[],
[],
json_encode([
'title' => 'Sample title',
])
);因此,我收到一个错误,例如:
Uncaught PHP Exception Symfony\Component\Serializerception\MissingConstructorArgumentsException: "Cannot create an instance of App\Entity\Post from serialized data because its constructor requires parameter "creator" to be present." at ./vendor/api-platform/core/src/Serializer/AbstractItemNormalizer.php line 313在我开始为User添加$creator类型之前,这是很好的。显然,$creator应该由正在使用API的当前登录用户填充。
有什么好办法解决这个问题吗?
我注意到Symfony序列化程序可以接受默认的构造函数参数:https://symfony.com/doc/current/components/serializer.html#handling-constructor-arguments
有什么办法在API平台上解决这个问题吗?
发布于 2022-08-01 14:01:17
最好不要手动设置创建者。
你用gedmo/doctrine-extensions (github)吗?
这个扩展提供了许多有用的扩展。
其中之一是可爆。
使用字符串或对象(例如,用户)更新创建、更新甚至属性上的字符串或引用字段。
这是一种自动设置创建者的干净方法。
一旦安装了gedmo/doctrine-extensions,您只需启用blameable
#stof_doctrine_extensions.yaml
stof_doctrine_extensions:
default_locale: fr_FR
orm:
default:
blameable: true并在您的实体中使用它,包括:
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* Only use annotation or attribute depending on your php version
* @Gedmo\Blameable(on="create")
* @ORM\ManyToOne(targetEntity=User::class)
* @ORM\JoinColumn(name="created_by", referencedColumnName="id", nullable=true)
*/
#[ORM\ManyToOne(targetEntity: User::class)]
#[ORM\JoinColumn(name: 'created_by', referencedColumnName: 'id', nullable: true)]
#[Gedmo\Blameable(on: 'create')]
protected $creator;我建议使用扩展,但您也可以使用自己的事件,例如,使用设置$creator值的原则$creator事件侦听器。
https://stackoverflow.com/questions/73194416
复制相似问题