How to display error message to user in MVC with Slim Router?

I’m using PHP with MVC pattern and the Slim 3 microframework for routing.

I need to show an error message to the user in the twig view. This error is regarding the username or password that they submitted being invalid.

The flow is like this:

  1. the Slim router accepts a GET request from the client on the “/login” route and sends it to the appropriate controller function which displays the login form.
  2. the Slim router accepts a POST request from the client on the “/login” route and sends it to the appropriate controller function for validation of user input and potentially authentication.

At this point I need to give user the feedback that their input was invalid. I can think of a few options, but I’m not sure if any of them are “optimal” or best practice.

  1. add the error message to the $_SESSION and redirect to the “/login” route, which will then display any error messages stored in the session in addition to the login form.
  2. add the error message to the Slim response (\Psr\Http\Message\ResponseInterface) and redirect to the “/login” route, which will then display any error messages stored in the request (or in args) in addition to the login form.
  3. execute the displayLoginForm($request, $response) controller function directly without doing any redirects, since the function is already in the same controller. the error message would be placed in the $request argument.

What would be the best practice method of handling this situation?

Option 2 doesn’t sound like it would work. When you issue the redirect, the user’s browser will send a new request to your app, so your app will have a new request and response object. Whatever you set in the old response will not be there.

Option 1, or variants of it, is what I do. However instead of accessing the $_SESSION variable directly, I use flash messages. You could use the Slim-Flash package or something like Aura.Session which offers both session management and flash messages in one package. As many of the Slim projects I have need to send error (and success) messages frequently, using “flash” messages like that are more convenient and end up with cleaner code in the controller. They also handle removing the temporary error message from the session for you.

I throw the error msg from controller, and display it to user with layer. you can test with my project is powered by sime 3,my login page,when you uses the wrong account or pass, you will get the error msg.try it.