将 HTTP 请求路由到静态类方法 [英] Routing HTTP requests to static class methods

查看:60
本文介绍了将 HTTP 请求路由到静态类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用 Slim Framework 来创建我的 rest API.一切正常,直到我尝试将 HTTP 请求路由到静态类方法(我之前使用过匿名函数).下面是我在 index.php 上的新路由代码:

I just started using Slim Framework to create my rest API. Everything works well until I try to route HTTP request to a static class method (I used the anonymous function before). Below is my new route code on index.php:

include "vendor/autoload.php";
$config = ['settings' => [
               'addContentLengthHeader' => false,
               'displayErrorDetails'    => true,
               'determineRouteBeforeAppMiddleware' => true
            ]
          ];

$app = new \Slim\App($config);
$app->get('/user/test', '\App\Controllers\UserController:test');
$app->run();

下面是我在 UserController.php

class UserController{
    public function test($request, $response, $args){
        $array = ['message'=>'your route works well'];
        return $response->withStatus(STAT_SUCCESS)
                        ->withJson($array);
    }
}

错误详情:

Type   : RuntimeException
Message: Callable \Controllers\UserController does not exist
File   : /var/www/html/project_api/vendor/slim/slim/Slim/CallableResolver.php

下面是我的项目文件夹树

Below is my project folder tree

project_api/
           index.php
           vendor/
                 slim/slim/Slim/CallableResolver.php

           Controllers/
                      UserController.php

我的composer.json

{
    "require": {
        "slim/slim": "^3.8",
        "sergeytsalkov/meekrodb": "*",
        "slim/http-cache": "^0.3.0"
    }
},
"autoload": {
    "psr-4": {
        "Controllers\\": "Controllers/"
    }
}

推荐答案

看来你的命名空间定义不正确.在您的 composer.json 中,Controllers 命名空间下的 UserController 类.

It seems that your namespace is define improperly. In your composer.json, class UserController under the namespace Controllers.

您应该在 UserController.php 的顶部定义一个命名空间:

you should define a namespace at the top of your UserController.php:

namespace Controllers;

并将 index.php 中的 $app->get() 更改为:

and change $app->get() in your index.php to:

$app->get('/user/test', 'Controllers\UserController:test');

这篇关于将 HTTP 请求路由到静态类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆