Php Slim框架与自动组路由
我想将所有逻辑移到控制器中,如下所示: index.php文件:Php Slim框架与自动组路由,php,slim,slim-3,Php,Slim,Slim 3,我想将所有逻辑移到控制器中,如下所示: index.php文件: $app = new Slim\App(); $app->group('/api/v1', function (\Slim\App $app) { $app->group('/users', UsersController::class ); }); class UsersController { public function __construct(\Slim\App $app) {
$app = new Slim\App();
$app->group('/api/v1', function (\Slim\App $app) {
$app->group('/users', UsersController::class );
});
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']);
}
...
}
UsersController.php文件:
$app = new Slim\App();
$app->group('/api/v1', function (\Slim\App $app) {
$app->group('/users', UsersController::class );
});
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']);
}
...
}
但我总是犯错误:
传递给UsersController::\uu构造()的参数1必须是
Slim\App实例,给定Slim\Container实例
如何工作?当控制器未在容器中注册时,默认情况下,Slim会尝试自行创建控制器,并将容器实例传递给构造函数。但因为您键入了提示,控制器构造函数期望
Slim\App
实例,所以您得到了错误
但我认为你们需要的是一条像这样的路线
$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');
});
});
所以不再需要在控制器构造函数中设置路由
但是,如果您仍然想按照现在的方式进行,那么您需要在容器中注册控制器
$container[UsersController::class] = function ($c) use($app) {
return new UsersController($app);
});
就我个人而言,我不建议这样做。看看这个。它使用slimphp使用MVC概念