Есть множество контроллеров, у которых принцип работы одинаковый. Располагаются они все по namespace app\presentation\controllers
. Именование у всех стандартное с постфиксом Controller
. Все методы, которые вызываются по запросу тоже стандартные и имеют префикс action
. Подскажите, как можно реализовать универсальный маршрут по такому шаблону: /<controller:\w+>/<action:\w+>/
или /{controller}/{action}/
.
Была попытка такой реализации, но не удается автоматически передавать параметры:
$routes->add('default', new Route('/{controller}/{action}', [
'_controller' => static function (Request $request) {
$controller = $request->attributes->get('controller');
$action = $request->attributes->get('action');
$controllerClassName =
'app\\presentation\\controllers\\'
. implode('', array_map('ucfirst', explode('-',$controller)))
. 'Controller';
$controllerClass = new $controllerClassName;
return call_user_func_array([$controllerClass, $action], $request->query->all());
}
]));
Само приложение выглядит так:
class App {
private UrlMatcher $matcher;
private ControllerResolver $controllerResolver;
private ArgumentResolver $argumentResolver;
public function __construct(UrlMatcher $matcher, ControllerResolver $controllerResolver, ArgumentResolver $argumentResolver)
{
$this->matcher = $matcher;
$this->controllerResolver = $controllerResolver;
$this->argumentResolver = $argumentResolver;
}
public function handle(Request $request)
{
$this->matcher->getContext()->fromRequest($request);
try {
$request->attributes->add($this->matcher->match($request->getPathInfo()));
$controller = $this->controllerResolver->getController($request);
$arguments = $this->argumentResolver->getArguments($request, $controller);
$response = call_user_func_array($controller, $arguments);
$response->headers->set('Content-type', 'application/json');
return $response;
} catch (ResourceNotFoundException $exception) {
return new Response('Not Found', 404);
} catch (\Exception $exception) {
return new Response('An error occurred', 500);
}
}
}
И корневой файл, который все это дело запускает:
$request = Request::createFromGlobals();
$routes = include __DIR__ . '/config/routes.php';
$context = new RequestContext();
$context->fromRequest($request);
$matcher = new UrlMatcher($routes, $context);
$controllerResolver = new ControllerResolver();
$argumentResolver = new ArgumentResolver();
$framework = new App($matcher, $controllerResolver, $argumentResolver);
$response = $framework->handle($request);
$response->send();
UPD.
Если добавить такой метод получения параметров, но это будет актуально только для $_GET
запросов, но есть проблема с отловом ошибок:
$arguments = $request->query->all();
array_shift($arguments);
return call_user_func_array([$controllerClass, $action], $arguments);
Выдает на экран при включенном дебаге:
error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
Fatal error: Uncaught ArgumentCountError: Too few arguments to function app\presentation\controllers\LeapYearController::index(), 0 passed in /var/www/php/custom-framework/config/routes.php on line 29 and exactly 1 expected in /var/www/php/custom-framework/app/presentation/controllers/LeapYearController.php:12
Stack trace: #0 /var/www/php/custom-framework/config/routes.php(29): app\presentation\controllers\LeapYearController->index()
#1 [internal function]: {closure}()
#2 /var/www/php/custom-framework/app/App.php(34): call_user_func_array()
#3 /var/www/php/custom-framework/index.php(28): app\App->handle()
#4 {main} thrown in /var/www/php/custom-framework/app/presentation/controllers/LeapYearController.php on line 12