在 CakePHP 中将参数从 URL 传递到具有正确类型的控制器函数
我正在使用 PHP 7 和 CakePHP 4.0 开发 RESTful API。
<?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
}
}
我想通过对此 URL 的 GET 请求来调用我的端点:
http://example.com/api/products/list/33/30/1
但我收到此错误:
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
现在,一个非常简单的解决方案是从 list
签名中的参数中删除类型方法,像这样(因为,如果我只是从 $categoryId
参数中删除类型,那么我对其他参数会得到相同的错误):
public function list($categoryId, $limit = 10, $page = 1)
但我更愿意保留“正确的” " 输入我的方法签名。 我是不是运气不好,还是有办法(也许在路由配置中,或其他地方)阻止 Cake(或 PHP 本身?)将 URL 中的参数转换为字符串?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
localhost/cakephp210?id=123 //这是我的网址
public function profile($id){
}
localhost/cakephp210?id=123 //this is my url
public function profile($id){
}