0
votes

I am sure this has been asked before but I am having trouble finding what I need. I am building a CMS in Symfony 4.4 and need a dynamic router that gets its routs and page info from a database. Need that ability to have users add pages and remove them with ease.

I can find information on building dynamic pages using a parent slug like this "/blogs/{slug}" but I am trying to build this without the "/blogs/" so just "/{slug}".

Now as far as I understand I can't just use the routing annotations in a controller like this

     /**
     * @Route("/{path}", name="Pages")
     */
    public function index($path, Request $request): Response {
      ...
    }

as that would work for all routes but homepage and make other set routes not work (I believe, If I am wrong let me know, would love to be wrong.)

I was thinking I could write a PHP program that builds a Routes file in YAML, XML, or PHP based on the info in a database but was wondering if there is a more efficient or better way of building this functionality.

Still new to Symfony and feel like I don't know anything.

1
The Symfony CMF Router can load routes from a database, maybe it'll suit your needs or at least serve as inspiration.msg
I have look at this and am still looking at this. I am still only finding how to build /blog/{slug} and not just /{slug}. Perhaps I am missing something.Griffin Longtin
You cannot use annotations for this (at least not in 4), but you can do it if you use a config file, just put that route the last one, routing is determined by its definition order, the first match will be executed. That means that there could still be collisions on user-generated routes, though, if that's what you mean.msg
That is what I thought. I have been using routes.php. I would like to use getDoctrine() in here but can't as it is not a class.Griffin Longtin

1 Answers

0
votes

I found a solution. Not sure it is the best practice but it works. https://symfony.com/doc/4.4/routing/custom_route_loader.html Using custom Route Loader I create a load function that calls my entityManager to get all the URLs I want for my CMS. I then added the routes like this to one controller class function

        foreach ($URLs as $url) {
            $defaults = array('_controller' => 'App\Controller\CMSController::index');
            $requirements = array('parameter' => '\d+');
            $route = new Route($url->getUrl(), $defaults, $requirements);
            $routes->add($url->getPageFunctionName(), $route);
        }