DatsunBing
DatsunBing

Reputation: 9076

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 the session but I'm never sure if I should do this in the controller, or in the service.

For example, if a request hits domain.com/user/edit, my controller could get the current user from the session and pass it to the service, or the service could access the session itself.

If I do it in the service it creates a dependency between the service layer and the session object. If I do it in the controller, it makes the controller a bit fatter.

I know it's only a small point but I have a lot of (small) variables stored in the session, and parameter handling for my requests is quite complex in itself.

Thanks!

Upvotes: 3

Views: 1337

Answers (2)

tereško
tereško

Reputation: 58444

Short answer: neither.

Now a bit loner explanation ...

From architectural point of view, the session is form of storage. And in PHP it is quite easy to manipulate which type of storage it actually is.

The services in MVC are the part of model layer which handles the application logic. That is - it deals with interaction between domain objects and storage abstraction (that usually are implemented directly or indirectly as data mappers).

Therefore, you should abstract the $_SESSION accesses (an also initialization) as some sort of SessionMapper, which can handle the storage of domain objects as whole or just storage of specific parameters from those domain objects.

And since session is (usually) a singular structure within your execution if request, you can enforce that by making sure the Factory, which produces the data mappers, creates only one instance of said SessionMapper.

Services only use this (shared via factory) session mapper and controller do not know anything about it.

Upvotes: 4

Starx
Starx

Reputation: 79031

$_SESSION is a global variable. Why do you have to pass something that can be accessed globally?

Unless the session data needs to be validated and the its data needs to be prepared in some way, there is no need to pass such variables to a controller class.

Upvotes: -4

Related Questions