【问题标题】:How to dynamically call methods with slim router?如何使用超薄路由器动态调用方法?
【发布时间】:2019-07-25 20:43:16
【问题描述】:

我正在设置 slim 路由器 v4,我希望能够使用路由中的 placeholder 动态调用控制器方法。

即当向“example.com/users/{action}”发出请求时,路由器会自动从 Users.php 控制器调用该方法,而无需我手动指定路由。

基本上,当它们都在 /user 路由下时,我试图避免手动添加超过 100 个组->get(...)。

namespace core\router;
use Slim\Interfaces\RouteCollectorProxyInterface;
use app\controllers\users;

$app->group('/user', function(RouteCollectorProxyInterface $group){
  $group->get('/get-name', '\Users:name')
  $group->get('/get-personality', '\Users:personality');
});

here 提供了进一步的解释,但我不知道该怎么做。

【问题讨论】:

  • 您是否尝试先询问here

标签: php url-routing slim


【解决方案1】:

我建议这样做的方式是使用一个占位符来捕获所有路线。然后,您可以将操作设置为可调用控制器,并根据路由参数执行方法。

路线:

$app->get('/user/{method}', Users::class);

控制器

class Users
{
    public function __invoke(Request $request, Response $response, $args)
    {
        if (empty($args['method'])) {
            throw new InvalidArgumentException();
        }

        $methodName = toCamelCase($args['method']);

        if (!method_exists($this, $methodName)) {
            throw new InvalidArgumentException();
        }

        return $this->{$methodName};
    }

    public function getName(Request $request, Response $response)
    {
        // ...
    }

    public function getPersonality(Request $request, Response $response)
    {
        // ...
    }
}

【讨论】:

  • 那行得通,也必须将 3 个参数从调用传递给方法,$this->{$methodName}($request, $response, $args);
猜你喜欢
  • 1970-01-01
  • 2017-12-20
  • 1970-01-01
  • 1970-01-01
  • 2022-12-16
  • 2013-01-07
  • 2023-04-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多