简体   繁体   English

Symfony 4实体获取器返回类型

[英]Symfony 4 entity getters return types

I'm currently using Symfony 4.1 on PHP 7.1 with Sonata Admin and there is a little problem with entity getters return types... Since I know which fields are nullable, I can set mandatory or optional return type. 我目前在Sonata Admin上使用PHP 7.1上的Symfony 4.1,并且实体获取方法的返回类型存在一些问题...由于我知道哪些字段可以为空,因此我可以设置强制或可选的返回类型。 But this aproach doesn't work when I'm binding entity on the create form of sonata admin, because entity is not initialized and all fields are set to null. 但是,当我在奏鸣曲管理员的创建表单上绑定实体时,此方法不起作用,因为实体未初始化且所有字段均设置为null。 Solution is obvious, but which is more correct? 解决方案很明显,但是哪个更正确?

Solution 1: Make return type optional (nullable) 解决方案1:将返回类型设为可选(可空)

 /**
 * @ORM\Table(name="banner__banner_zone_relation")
 * @ORM\Entity()
 */
class BannerZoneRelation implements TimestampableInterface
{
    /**
     * @var Banner
     * @ORM\ManyToOne(targetEntity="App\Entity\Banner\Banner", inversedBy="bannerZoneRelations", cascade={"persist"})
     * @ORM\JoinColumn(name="banner_id", referencedColumnName="id")
     */
    protected $banner;

    /**
     * @var Zone
     * @ORM\ManyToOne(targetEntity="App\Entity\Banner\Banner",inversedBy="bannerZoneRelations", cascade={"persist"})
     * @ORM\JoinColumn(name="zone_id", referencedColumnName="id")
     */
    protected $zone;

    /
    /**
     * @return Banner|null
     */
    public function getBanner(): ?Banner
    {
        return $this->banner;
    }

    /**
     * @return Zone|null
     */
    public function getZone(): ?Zone
    {
        return $this->zone;
    }
}

Solution 2: Creating instance of Banner and Zone in constructor 解决方案2:在构造函数中创建Banner和Zone的实例

 /**
 * @ORM\Table(name="banner__banner_zone_relation")
 * @ORM\Entity()
 */
class BannerZoneRelation implements TimestampableInterface
{
    /**
     * @var Banner
     * @ORM\ManyToOne(targetEntity="App\Entity\Banner\Banner", inversedBy="bannerZoneRelations", cascade={"persist"})
     * @ORM\JoinColumn(name="banner_id", referencedColumnName="id")
     */
    protected $banner;

    /**
     * @var Zone
     * @ORM\ManyToOne(targetEntity="App\Entity\Banner\Banner",inversedBy="bannerZoneRelations", cascade={"persist"})
     * @ORM\JoinColumn(name="zone_id", referencedColumnName="id")
     */
    protected $zone;

    public function __construct()
    {
        $this->banner = new Banner();
        $this->zone = new Zone();
    }

    /
    /**
     * @return Banner
     */
    public function getBanner(): Banner
    {
        return $this->banner;
    }

    /**
     * @return Zone
     */
    public function getZone(): Zone
    {
        return $this->zone;
    }
}

Which solution is better? 哪种解决方案更好? Thanks for any answer! 感谢您的回答!

我认为选项1(返回null)使区域和横幅记录在不需要时不会在数据库中创建。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM