'Pass parameter from URL to controller function with correct type in CakePHP
I am developing a RESTful API using PHP 7 and CakePHP 4.0.
<?php
namespace App\Controller\Api;
use App\Controller\AppController;
class ProductsController extends AppController
{
public function list(int $categoryId, int $limit = 10, int $page = 1)
{
// here's my code with queries and so on
}
}
I would like to call my endpoint with a GET request to this URL:
http://example.com/api/products/list/33/30/1
But I get this error:
Argument 1 passed to App\Controller\Api\ProductsController::list() must be of the type integer, string given, called in /var/www/repo/public/vendor/cakephp/cakephp/src/Controller/Controller.php on line 521
Now, a very simple solution would be to just remove the type from the parameters in the signature of the list method, like this (because, if I just remove the type from the $categoryId parameter, then I get the same error for the other ones):
public function list($categoryId, $limit = 10, $page = 1)
But I'd much rather prefer to keep the "correct" types in my method signature. Am I out of luck here, or is there a way (maybe in the routing configuration, or somewhere else) to prevent Cake (or PHP itself?) to cast the parameters in the URL to string?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
