Pergunta

i'm trying to implement Respect/Rest in my existing CMS.

The Problem: I would like to create a single magic route to works like: /admin/*/save, calls the * controller...

I would like to make something like this:

$r->any('/admin/*/save/*/', function($controller, $id = null) use ($r) {
  return $r->dispatchClass($controller,array($id));
});

Note that i don't know which HTTP method user is using.

Actually I "solved" this problem with something like:

$r->any('/admin/*/save/*/', function($controller, $id = null) use ($tcn) {
  $r = new Router;
  $r->any('/admin/*/save/*/', $tcn($controller . '_save'), array($id));
  return $r->run();
});

$tcn is a named function that returns the full namespace of the controller.

I know it's not a good approach.

EDIT:

This project wants to be Open Source, but it's still being created. We're trying to transport an old project made on functional paradigm to OOP. We are trying to learn about OOP while making an useful project. Actuall state of the files can be found at: https://github.com/dindigital/skeleton

Alganet: The bootstrap for admin routes can be found at: https://github.com/dindigital/skeleton/blob/master/admin_routes.php

A simple controller sample: https://github.com/dindigital/skeleton/blob/master/src/app/admin/controllers/TagController.php https://github.com/dindigital/skeleton/blob/master/src/app/admin/controllers/TagSaveController.php

I liked the Forwards and also the Factory approach... I could not decide yet.

Foi útil?

Solução

Tricky question! That depends a lot of why are you making these routes dynamic. Can you show us some sample structure for your controllers so I can improve the answer?

Meanwhile, two native features that can help:

Forwards

You can treat the problem as an internal forward (does not make redirects). It's normally to redirect to other static routes, but you can redirect to a new one as well:

$r->any(
    '/admin/*/save/*/', 
    function ($controller, $id) use ($tcn, $r) {
        return $r->any(
            "/admin/$controller/save", 
            $tcn($controller . '_save'),
            array($id)
        );
    }
);

Factory Routes

Also, Respect\Rest implements factory routes. It is experimental but stable in tests:

$r->factoryRoute(
    'ANY',
    '/admin/*/save/*/', 
    'MyAbstractController',
    function ($method, array $params) use ($tcn) {
        return new $tcn($params[0] . '_save');
    }
);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top