在 CakePHP 中将参数从 URL 传递到具有正确类型的控制器函数

发布于 2025-01-19 14:22:17 字数 992 浏览 6 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

哥,最终变帅啦 2025-01-26 14:22:17

localhost/cakephp210?id=123 //这是我的网址

public function profile($id){

//this is my profile method in controller here i want to get  my id here

 using method $id parameter    help me any one

}

localhost/cakephp210?id=123 //this is my url

public function profile($id){

//this is my profile method in controller here i want to get  my id here

 using method $id parameter    help me any one

}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文