Cakephp 我如何创建一个路由来接受带有维护路径的 id 和 cat id?

Cakephp how can I created a route for accept both id and cat id with maintain path?

我有一个 API 前缀路由,我有一个控制器,我试图在其中获取产品,然后按 id 获取产品,然后按类别 id 获取产品。

所以,我创建了一个前缀路由

$routes->scope('/api', function (RouteBuilder $routes) {
        $routes->setExtensions(['json']);
        $routes->resources('Shops',[
            'prefix' => 'Api',
            'path' => 'shops',
            'map' => [
                'getProducts' => [
                    'action' => 'getProducts',
                    'method' => 'GET',
                    'path' => '/products'
                ],
                'getProductById' => [
                    'action' => 'getProducts',
                    'method' => 'GET',
                    'path' => '/products/{id}',
                ],
                'getProductBySubcatId' => [
                    'action' => 'getProducts',
                    'method' => 'GET',
                    'path' => '/products/cat/{cat_id}',
                    'subcat_id' => [0-10]
                ],
            ]
        ]);
 });

实际上我正在尝试做

public function getProducts($id = null, $cat_id = null)
{   
        if($id)
          -----
        else if($cat_id)
          ----
}

我需要获取像

这样的数据

http://localhost:8000/api/shops/products/cat/1.json

现在 以下 URL

http://localhost:8000/api/shops/products/1.json

我正在获取参数传递

protected params => [
'id' => '1',
'pass' => [
   (int) 0 => '1',
],

但是对于 catId 我没有通过 http://localhost:8000/api/shops/products/cat/1.json

protected params => [
'catId' => '1',
'pass' => [ ],

我还可以发送字符串作为猫 ID 的参数

protected params => [
'catId' => 'A',
'pass' => [ ],

如何在 pass 中添加 catId?另外,如何添加 catId 始终为 int 的验证?

将尝试在您的方法中使用扩展运算符:

public function getProducts(...$params)
{   
   //try to understand spread operator
   debug($params);

   if (count($params) == 2 && !is_number($params[0]) && is_number($params[1]) {
     $id = strval($params[0]);
     $cat_id = intval($params[1]);
   }

  if (count($params) == 1 && is_number($params[0]) {
     $id = null;
     $cat_id = intval($params[0]);
   }
   // ... implement your code     
}

你可以用connectOptions

解决
map [
  // your map 
],
'connectOptions' => [
    'catId' => '[0-9]+',
    'pass' => ['id','catId'],
],

查看详情RouteBuilder.php class