V
V
Vladislav2014-09-05 17:06:30
PHP
Vladislav, 2014-09-05 17:06:30

How to correctly raise a 404 error in the router if it is a controller?

The router accepts a URL like class/action/param/123/param/1234 etc.
Those. I have to check the parity of the entered URL (when divided into an array), if it is odd, then issue a 404 controller
. Then check if there is a required class, if there is none, issue a 404 controller.
Then check if there is a required class method, if there is none, call the controller 404.
What construction should be used under these conditions?

try {
//тут проводим проверку на четность URL
//если не проходит, то 
throw new Exception('не все параметры введены');

//далее подключаем нужный класс, если он есть
if(file_exist(путь к файлу)){
$startController = new $nameController();
}else throw new Exception('такого класса нет');

//проверяем наличие метода в классе
if(metod_exist($startController,  $nameAction)){
$startController -> $nameAction($params);
}else throw new Exception('такого метода нет');

//если поймали исключение, то
} catch (Exception $e) {
$startController =  new error404();
$startController -> index();
}

Norm to do so?
I want to hear opinions...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2014-09-05
@DubecZ

Opinions... you already have trouble with routing, so you can score and continue to do as you please.
if you take the piece you gave:
replace with
and paths resolve in autoload
Calls to the action imply that you always have an array as arguments. An array of parameters. IMHO this sucks. Agree, so cool:

function ($id, $page = 1) {
    
}
// ...

call_user_func_array([$controller, $actionName], $params);

or even call through reflections, then you can also change the order of the arguments and resolve by name.
otherwise normal. Only I would call the controller as ErrorHandlingController or something like that and redirect to it any request that fell with an exception.

A
Alexander Kubintsev, 2014-09-05
@akubintsev

The exception approach seems to me to be quite sensible. The only caveat is to make a separate type of exception, such as PageNotFoundException. It is not correct to use \Exception, because you never know where else \Exception can be thrown in the code

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question