大多数phpslim3用法的例子都是这样的
$app->get('/hello/{name}', function ($request, $response, $args) { ... });
但不仅仅是,在回调括号中编写代码,我更喜欢创建一个具有独立函数的类;
关键是我的代码不起作用。我的回答是:
消息:Callable Api \ CreateAccountController不存在 文件:C:\ Users \ dedeu \ Documents \ Work \ php \ l21-api-slim \ vendor \ slim \ slim \ Slim \ CallableResolver.php
行:90
我已经检查了这个文档文件,但也没有用(有效,但我做错了)
https://www.slimframework.com/docs/v3/objects/router.html#post-route
composer.json
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/",
"App\\": "src/",
"Api\\": "src/Api/"
}
},
"autoload": {
"psr-4": {
"Api\\": "src/Api/"
}
},
router.php
<?php
use Slim\Http\Request;
use Slim\Http\Response;
use Api\CreateAccountController;
// Routes
// $app->get('/[{name}]', function (Request $request, Response $response, array $args) {
// // Sample log message
// $this->logger->info("Slim-Skeleton '/' route");
$app->post('/api/moip/create-account', \Api\CreateAccountController::class . ':create');
dependencies.php
<?php
// DIC configuration
$container = $app->getContainer();
// view renderer
$container['renderer'] = function ($c) {
$settings = $c->get('settings')['renderer'];
return new Slim\Views\PhpRenderer($settings['template_path']);
};
// monolog
$container['logger'] = function ($c) {
$settings = $c->get('settings')['logger'];
$logger = new Monolog\Logger($settings['name']);
$logger->pushProcessor(new Monolog\Processor\UidProcessor());
$logger->pushHandler(new Monolog\Handler\StreamHandler($settings['path'], $settings['level']));
return $logger;
};
$container['CreateAccountController'] = function($c) {
$view = $c->get("view"); // retrieve the 'view' from the container
return new \Api\CreateAccountController($view);
};
CreateAccountController.php
<?php
namespace Api;
class CreateAccountController
{
protected $view;
public function __construct(\Slim\Views\Twig $view) {
$this->view = $view;
}
public function create($request, $response, $args) {
$data = $request->getParsedBody();
$status = $response->getStatusCode();
if(!isset($data["teste"])){
// print_r('rara rasputin');
$out = array('message' => 'you lack infos', 'code' => 400);
$response = $response->withJson($out, 400);
return $response;
}
$response = $response->withJson($data, 201);
return $response;
}
}
代码可能会以某种方式看起来很混乱,因为我有点想做任何事情来使这个工作。 (已经尝试将\ Api \ CreateAccountController切换到\ CreateAccountController
我的项目路径
答案 0 :(得分:4)
更改composer.json
"autoload-dev": {
"psr-4": {
"App\\Test\\": "tests"
}
},
"autoload": {
"psr-4": {
"App\\": "src"
}
},
运行composer update
以确保应用所有设置。
将文件CreateAccountController.php
复制到src/Api/
更改CreateAccountController.php
<?php
namespace App\Api;
然后像这样修复容器条目:
$container[\App\Api\CreateAccountController::class] = function($c) {
// ...
}