A
A
avada kedavra2015-04-01 23:12:47
PHP
avada kedavra, 2015-04-01 23:12:47

Authorization in PHP + MVC, where to check?

There is an MVC application framework. All requests are sent to index.php, where the configuration file, libraries, model, view, controller base classes and the Router class responsible for routing are connected. Next, the Router::start() method is launched, which directly breaks the URL and calls the desired controller.
How to properly implement authorization? Do check if session is set in each controller?
Somehow it doesn't work out nicely.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
X
xskif, 2015-04-01
@kedavra

The ideal option is to create a middleware layer between the controller and the router. Give the ability to load middleware classes there through the configuration or a predefined folder. Create a class that will check session/cookies. Usually all the logic in such classes lies in the 'run' method.
If you don't want to complicate things, you can create an ApplicationController, which will have the basic functionality for all application controllers, for example, authorization, and inherit all other controllers from it.
You can also add authorization as a RequestInterceptor class, which also connects to the controller (better to the base one) and responds to the controller's prescribed events. Subscribe the interceptor to beforeAction and perform authorization. The last way is more for RESTful applications.

S
Sergey, 2015-04-02
Protko @Fesor

We read about HTTP Middelware, request-response frameworks, don't get hung up on MVC. As a result, the vlow comes out like this:
Let's assume that we have a Kernel interface containing a handle method that accepts a Request as an input and produces a Response as an output. Next...
- We collect the Request from global variables
- We pass it to the garbage that implements the Kernel
- due to the use of the adapter pattern, you can make many implementations of the Kernel interface nested into each other. One implementation resolves routes, the second one handles authorization, the third one adds CORS... and the innermost one already calls the controller of your so-called MVC framework.
Profit - everything can be covered with tests, everything scales conveniently, there are heaps of ready-made implementations. Finally there is the PSR-7.
In any case, authentication must be done in the front controller, and authorization - there may already be options.

D
Dmitry, 2015-04-01
@By_Engine

You need a base controller in which all the necessary parameters will be set. Application controllers inherit from this controller

M
Mike, 2015-04-02
@Mike77

in the model

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question