<?php
declare(strict_types=1);
use DI\ContainerBuilder;
use AppName\Auth\TestController;
use Slim\Factory\AppFactory;
require __DIR__ . '/../vendor/autoload.php';
try {
$builder = new ContainerBuilder();
$builder->useAutowiring(true);
$container = $builder->build();
AppFactory::setContainer($container);
$app = AppFactory::create();
$app->addBodyParsingMiddleware();
$app->addRoutingMiddleware();
// This works!
$app->get('/', function ($request, $response) {
$response->getBody()->write("Hello world!");
return $response;
});
// This gives an error
$app->get('/test', [TestController::class, ':test']);
// same goes for , TestController::class . ':test');
// or with , TestController::class); // __invoke() in the class
$app->run();
} catch (Exception $e) {
echo $e->getMessage();
}
TestController.php
<?php
declare(strict_types=1);
namespace AppName\Auth;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
class TestController
{
public function test(Request $request, Response $response): Response
{
$response->getBody()->write('Hello World');
return $response;
}
}
.htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
# RewriteBase /
# NOT needed unless you're using mod_alias to redirect
RewriteCond %{REQUEST_URI} !/public
RewriteRule ^(.*)$ public/index.php/$1 [L]
# Direct all requests to /public folder
</IfModule>
<?php
namespace Src\Auth\Controller;
class AuthController {
public function __construct() {}
public function loginIndex(Request $request, Response $response, array $args): Response {
$response->getBody()->write('Login');
return $response;
}
}
meu arquivo em config/container.php:
<?php
use Psr\Container\ContainerInterface;
use Slim\App;
use Slim\Factory\AppFactory;
return [
'settings' => function () {
return require __DIR__ . '/settings.php';
},
App::class => function (ContainerInterface $container) {
$app = AppFactory::createFromContainer($container);
// Register routes
(require __DIR__ . '/routes.php')($app);
// Register middleware
(require __DIR__ . '/middleware.php')($app);
return $app;
},
];
meu arquivo de configuraĆ§Ć£o de rotas global (config/routes.php):
<?php
use Slim\App;
return function (App $app) {
foreach (glob( dirname(__FILE__) . '/../routes/*.php') as $routeFile) {
require $routeFile;
}
};
meu arquivo de rotas para auth (routes/auth.php):
<?php
use Src\Auth\Controller\AuthController;
$app->group('/auth/login', function(\Slim\Routing\RouteCollectorProxy $app) {
$app->get('', 'AuthController:loginIndex');
});