Defining a route in Symfony 2 with variable action

Just imagine, I have a controller with several actions. And in order to achieve each action, I have to define it strictly in the routing.yml file as follows:

admin_edit_routes:
    pattern:  /administrator/edituser
    defaults: { _controller: MyAdminBundle:Default:edituser }
admin_add_routes:
    pattern:  /administrator/adduser
    defaults: { _controller: MyAdminBundle:Default:adduser }

And I can have many such pages. What I want to achieve is to define the necessary actions in my URI, as the Kohana routes do. I mean, I just want to use one route for all actions: (the code below is not valid, for example)

admin_main_route:
    pattern:  /administrator/{action}
    defaults: { _controller: MyAdminBundle:Default:{action} action:index}

It will send all requests to / administrator / {anything} to this route, and then, according to the action specified in the uri, the necessary action will be called. If no action is specified in the uri, then we get an indexing action.

Is this possible in Symfony 2 anyway, and if so, how? Thanking in advance.

+4
2

. API- () " " GET, . .
, , ? , ?

{{ path('dynamic_route', { 'method': 'addUser' }) }}

, Symfony, , . - CodeIgniter Kohana. "Front Controller"

, annotations. Symfony .

namespace Acme\FooBundle\Controller;

/**
 * @Route("/administrator")
 */
class DefaultController extends Controller
{
    /**
     * @Route
     */
    public function indexAction(Request $request);

    /**
     * @Route("/adduser")
     */
    public function addUserAction(Request $request);

    /**
     * @Route("/edituser")
     */
    public function editUserAction(Request $request);

    /**
     * @Route("/{tried}")
     */
    public function fallbackAction($tried, Request $request)
    {
        return $this->indexAction($request);
    }
}

fallbackAction /administrator/*, indexAction.

, " " .
, .

+3

, , , . dynamicAction action , . , params.

/**
 * Default Controller.
 *
 * @Route("/default")
 */
class DefaultController extends Controller
{

    /**
     * @Route("/{action}/{params}", name="default_dynamic")
     */
    public function dynamicAction($action, $params = null)
    {
        $action = $action . 'Action';
        if (method_exists($this, $action)) {
            return $this->{$action}($params);
        }

        return $this->indexAction();
    }
}

, - : >

+1

Source: https://habr.com/ru/post/1543948/


All Articles