mercredi 28 avril 2021

Constructing objects in a symfony Entity php

I'm trying to create a form with different types composed out of different elements. I'm confused as to what i'm able to add into a entity class.

I don't want https://symfony.com/doc/current/forms.html, just information on this more simplistic example

<?php

namespace App\Entity;

use App\Repository\FormTypeRepository;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass=FormTypeRepository::class)
 */
class FormType
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $name;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $type;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getType(): ?string
    {
        return $this->type;
    }

    public function type(): void
    {
        /*@todo*/
    }
}

Could the type function be used to instantiate objects? Or should this be a factory or some other Design Pattern and used within a service?

interface FormTypeInterface {
  method();
}


public function type(): ?FormTypeInterface
{
  $type = $this->getType();
  if (class_exists($type)) return;
  return new $$type;
}

Where should I add the code for the interface and concrete classes? Or should I even do it that way.

service mock

class Service {
  public function handle() {
    $formTypeEntity = /* ... */
    $type = SomeFactory::make($formTypeEntity);
  }
}

Aucun commentaire:

Enregistrer un commentaire