Ren
Ren

Reputation: 531

Where is the most appropriate place to create a session in an MVC architecture?

I am developing a PHP application just as an exercise, and I was wondering where the session creation would be more correct.

I receive the login data in a controller, then I ask my model if that user exists and if the password matches. Should this same controller handle session creation? I just can't find a good answer for this.

Upvotes: 4

Views: 566

Answers (4)

Mamuz
Mamuz

Reputation: 1730

Either your application has a bootstrap file, you can initiate your session there. If your Session-Class has an autostart, then you dont care about it in the most cases. If your MVC implements an interceptor pattern you can create a plugin for that, to initiate your session.

Creation Session in controller produce redudant code and one of the important principle is DRY (Dont repeat yourself).

Upvotes: 1

EToreo
EToreo

Reputation: 3086

You might check out the "Front Controller" pattern that is commonly used with the MVC pattern.

From http://en.wikipedia.org/wiki/Front_Controller_pattern

  • The Front Controller Pattern is a software design pattern listed in several pattern catalogs. The pattern relates to the design of web applications. It "provides a centralized entry point for handling requests."

Upvotes: 0

tereško
tereško

Reputation: 58444

Session should be initialized when you first time utilize that storage medium.

Most likely as:

namespace Mapper;

class Session 
{
    public function prepare()
    {
        session_set_cookie_params( ... ); // if needed
        session_start();
    }

    public function store(SomeInterface $object) { ... }
    public function retrieve(SomeInterface $object) { ... }
}

.. where prepare() method is called on session instance before the factory releases it to "general application".

Basically, from model layer's point of view, session is just another type of storage, that you utilize with some sort of mapper. This mapper can be shared throughout the application using factory, which makes sure, that all the parts of model layer are using same object for abstraction the session.

Controllers should not be even aware, that the session is utilized somewhere withing model layer. Only part of model layer, that controllers are aware of, should be the services, through which controller alters the sate of model layer.

Upvotes: 2

moonwave99
moonwave99

Reputation: 22812

The session handler could be a component injected in any controller upon demand, or an application-wide singleton.

I'd go with the first approach on a medium app, and use the latter in a microframework, where the dependencies are less.

Upvotes: 3

Related Questions