Is this a good or a bad practice to use parent construct method on each child? [closed]

I am trying to create a Widget service.

I have Widget class and his his children: ContactWidget, TestimonialWidget etc. They are depend from TemplateService and from User class.

So using OOP features i can do it this way:

Class Widget (parent):

abstract class Widget
{
    protected $client;
    protected $templateService;
    protected $template;

    public function __construct(TemplateService $templateService, Client $client) 
    {
        $this->templateService = $templateService;
        $this->client = $client;
    }

    public function setTemplate(string $template)
    {
        if (!file_exists($template)) {
            throw new Exception('Widget template "' . $template . '" was not found.');
        }

        $this->template = $template;

        return $this;
    }

    abstract protected function renderWidget() : string;
}

Class ContactWidget (child example):

class ContactWidget extends Widget implements ICustomerForm
{
    use CustomerFormTrait;

    private $formFactory;

    public function __construct(TemplateService $templateService, $client, FormFactoryInterface $form)
    {
        parent::__construct($templateService, $client);

        $this->formFactory = $form;
    }

    public function renderWidget() : string
    {
        $form = $this->buildForm();

        return $this->templateService->render($this->template, [
            'form' => $form->createView(),
            'token' => $this->client->getToken()
        ]);
    }

    public function buildForm() : FormInterface
    {
        $form = $this->formFactory->create(ContactType::class, $this->customer);

        return $form;
    }
}

Class TestimonialWidget (child example):

class TestimonialWidget extends Widget
{
    public function __construct(TemplateService $templateService, Client $client)
    {
        parent::__construct($templateService, $client);
    }

    public function renderWidget() : string
    {
        $testimonials = [[
            'name' => 'John Snow',
            'text' => 'Test'
        ]];

        return $this->templateService->render($this->template, [
            'testimonials' => $testimonials
        ]);
    }
}

So, with this structure, the code is not very beautiful. Since by separating the common parts and methods for all descendants of the Widget class, we must to call the parent constructor and pass the dependencies.

Perhaps there is a more correct solution to this task? Maybe exists a pattern that solves this problem?

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *