Should I pass session data from my controller or read it in the service layer?
I have a fairly typical MVC application in PHP. Quite often I need to grab data from a session, but I'm never really sure if I should be doing this in a controller or in a service.
For example, if the request reaches domain.com/user/edit
, my controller can get the current user from the session and pass it to the service, or the service can access the session itself.
If I do this in a service, it creates a dependency between the service layer and the session object. If I do this in a controller, it makes the controller a little thicker.
I know this is just a small point, but I have a lot of (small) variables stored in the session, and handling the parameters for my queries is pretty tricky on its own.
Thank!
source to share
The short answer: .
Now for a slightly lonely explanation ...
From an architectural point of view, a session is a form of storage. And in PHP it is pretty easy to manipulate the kind of storage it actually has.
Services in MVC are part of the model layer that handles application logic. That is, it deals with the interaction between domain objects and the storage abstraction (which are usually implemented directly or indirectly as data mappers ).
Hence, you should abstract the calls $_SESSION
(as well as initialization) as a kind SessionMapper
that can handle storing domain objects in general, or just storing certain parameters from those domain objects.
And since a session is (usually) a single structure in your execution, if you request a request, you can enforce it by making sure that the Factory
one that produces the data only displays one instance of the specified one SessionMapper
.
Services use this session (shared via a factory) and the controller doesn't know anything about it.
source to share