h00ligan
h00ligan

Reputation: 1481

Is there a way to "Inherit" a controller's prefix in Symfony 2?

Is there any way to for one controller to inherit another controller's routing prefix in Symfony2?

I'd like to create an "admin" route and controller that other controllers can inherit the base prefix from, e.g. The admin class would start something like this:

/**
 * @Route("/admin")
 */
class AdminController {...}

And then another class could then "inherit" only the prefix and add to it with its own prefix, example:

/**
 * @Route("/news")
 * @InheritPrefix("AdminController") <-- an imaginary annotation to show what I mean
 */
class NewsController
{
    /**
     * @Route("/", name="admin_news")
     */
    public function indexAction() {...}

    /**
     * @Route("/list-all", name="admin_news_list-all")
     */
    public function listAllAction() {...}
}

The result would be that the URL /admin/news would be routed to the NewsController::indexAction() and /admin/news/list-all would redirect to NewsController::listAllAction()

Then a second class could be created, e.g.

/**
 * @Route("/photos")
 * @InheritPrefix("AdminController") <-- an imaginary annotation to show what I mean
 */
class PhotoController
{
    /**
     * @Route("/new", name="admin_photos_new")
     */
    public function newAction() {...}
}

Then the url /admin/photos/new would redirect to PhotoController::newAction()

I know about the SonataAdminBundle but wanted to know if there was a way to do this without that bundle.

Upvotes: 0

Views: 1352

Answers (1)

Wouter J
Wouter J

Reputation: 41934

You can specify prefixes for a complete RouteCollection. When using annotations, each controller is a collection. But each imported resource is a collection too. This means you can have an admin resource import, with the /admin prefix and a controller with a /news prefix:

# app/config/routing.yml
_admin:
    resource: @AdminBundle/Controller
    prefix: /admin
// src/AdminBundle/Controller/AdminController.php

// ...
class AdminController
// ...
// src/AdminBundle/Controller/PhotoAdminController.php

// ...

/**
 * @Route("/news")
 */
class PhotoAdminController
// ...

Upvotes: 5

Related Questions