Syllz
Syllz

Reputation: 340

Symfony: Dynamic route for multiple entities

Currently working with Symfony 5.2

I am trying to create a dynamic route for multiple enties which have mostly same properties (some still have other fields too, but all have the same default properties).

Example (minified)

Entity News:
- id, title, author

Entity Event:
- id, title, author

I am now trying to create a dynamic route to fetch News or Events from my the repository.

class ContentController extends AbstractController {
    
    /**
     * @Route("/{type}", name="get_content")
     */
    public function get(string $type) {  //type is the name of the entity e.g.   'news'   or   'event'
        //fetch from repo
        $results = $this->getDoctrine()->getRepository(/* entity class */)->findAll();
    }
}

I already came up with some ideas, but not sure if they are good practise.

1) use full namespace for the entity (how do I check if the class exists? error handling?)
$results = $this->getDoctrine()->getRepository('App\\Entity\\News')->findAll();
$results = $this->getDoctrine()->getRepository('App\\Entity\\' . ucfirst($type))->findAll();



2) provide a route for each entity and call a generic function (not exactly what I want because I have like 10+ entities for this)

class ContentController extends AbstractController {
    
    /**
     * @Route("/news", name="get_news")
     */
    public function get_news() {
        $results = getContent(News::class);
    }

    /**
     * @Route("/event", name="get_event")
     */
    public function get_event() { 
        $results = getContent(Event::class);
    }


    public function getContent($class) {
        return $this->getDoctrine()->getRepository($class)->findAll();
    }
}

Mabye some of you have better ideas/improvements and can help me out a bit.

Upvotes: 0

Views: 487

Answers (1)

Vadim Shmakov
Vadim Shmakov

Reputation: 26

You can define available for fetching entities manually.

class ContentController extends AbstractController
{
    /**
     * @Route("/{type}", name="get_content")
     */
    public function get(string $type)
    {  //type is the name of the entity e.g.   'news'   or   'event'
        //fetch from repo
        $results = $this->getDoctrine()->getRepository($this->getEntityClassFromType($type))->findAll();
    }

    private function getEntityClassFromType(string $type): string
    {
        //define your entities manually
        foreach ([News::class, Event::class] as $class) {
            $parts = explode('\\', $class);
            $entity = array_pop($parts);

            if ($type === lcfirst($entity)) {
                return $class;
            }
        }

        throw new NotFoundHttpException();
    }
}

Or check your entities dynamically using $entityManager->getMetadataFactory()->hasMetadataFor($className);

Upvotes: 1

Related Questions