简体   繁体   中英

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. 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. Solution is obvious, but which is more correct?

Solution 1: Make return type optional (nullable)

 /**
 * @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

 /**
 * @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)使区域和横幅记录在不需要时不会在数据库中创建。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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