I would like to move all logic into controllers like this: index.php file:
$app = new Slim\App();
$app->group('/api/v1', function (\Slim\App $app) {
$app->group('/users', UsersController::class );
});
UsersController.php file:
class UsersController
{
public function __construct(\Slim\App $app)
{
$app->getContainer()->get('db');
$app->map(['GET'], '/', [$this, 'readAll']);
$app->map(['POST'], '/', [$this, 'create']); //Create a new
$app->map(['PUT'], '/', [$this, 'updateAll']);
$app->map(['DELETE'], '/', [$this, 'deleteAll']);
$app->map(['GET'], '/{id}', [$this, 'read']);
//$app->map(['POST'], '/{id}', [$this, 'createNot']); //Method not allowed (405)
$app->map(['PUT'], '/{id}', [$this, 'update']);
$app->map(['DELETE'], '/{id}', [$this, 'delete']);
}
...
}
But always I got error:
Argument 1 passed to UsersController::__construct() must be an instance of Slim\App, instance of Slim\Container given
What to do to work?
When a controller is not registered in container, then by default, Slim tries to create the controller on its own and passing container instance to the constructor. But because you typehint that controller constructor expect Slim\App
instance, hence you get error.
But I think what you need is actually route like
$app->group('/app/v1', function () use ($app) {
$app->group('/users', function () use ($app) {
$app->get('/', UsersController::class . ':readAll');
$app->post('/', UsersController::class . ':create');
$app->put('/', UsersController::class . ':updateAll');
$app->delete('/', UsersController::class . ':deleteAll');
$app->get('/{id}', UsersController::class . ':read');
$app->put('/{id}', UsersController::class . ':update');
$app->delete('/{id}', UsersController::class . ':delete');
});
});
So there is no need to setup route in controller constructor anymore.
But if you still want to go the way you have right now, then you need to register controller in container.
$container[UsersController::class] = function ($c) use($app) {
return new UsersController($app);
});
Personally, I would not recommend this.