Skip to content

Instantly share code, notes, and snippets.

@vjandrea
Created March 15, 2022 06:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vjandrea/74fa811af27fcf9eedd4f0db35ca6ba0 to your computer and use it in GitHub Desktop.
Save vjandrea/74fa811af27fcf9eedd4f0db35ca6ba0 to your computer and use it in GitHub Desktop.
Controller inheritance and extension
<?php
# src/Controller/ParentController.php

namespace App\Controller;

use App\Entity\Product;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class FatherController extends AbstractController
{
    public function __construct(private EntityManagerInterface $entityManager, private LoggerInterface $logger) {}

    #[Route('/father', name: 'app_father')]
    public function index(): Response
    {
        $products = $this->entityManager->getRepository(Product::class)
                                        ->findBy([], ['name' => 'ASC']);

        if (empty($products)) {
            $this->logger->error('Products list is empty');
        }

        return $this->json([
            'products' => $products,
        ]);
    }
}
<?php
# src/Controller/ChildController.php

namespace App\Controller;

use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Routing\Annotation\Route;

class ChildController extends FatherController
{
    public function __construct(private EntityManagerInterface $entityManager, private LoggerInterface $logger, private MailerInterface $mailer)
    {
        parent::__construct($this->entityManager, $this->logger); // <= use parent to instantiate FatherClass
    }

    #[Route('/child', name: 'app_child')]
    public function index(): Response
    {
        $this->mailer->send(/** ... */);

        return $this->json([
            // ...
        ]);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment