Search code examples
phpsymfonysymfony4return-typephp-7.1

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!


Solution

  • I would think option 1 (return null) so that zone and banner records aren't created in the database if they're not necessary.