Routing HTTP requests to static class methods

孤者浪人 提交于 2020-01-07 01:24:30

问题


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();

And below is my UserController class on UserController.php

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

Error details:

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

my composer.json

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

回答1:


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

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

namespace Controllers;

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

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


来源:https://stackoverflow.com/questions/43449493/routing-http-requests-to-static-class-methods

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!