JDelage
JDelage

Reputation: 13682

Pros and cons of passing data via dependency injection vs including it in $_SESSION

I'm writing a small non-commercial web app, and I'm wondering how to pass data from one piece of the code to others. Specifically, I want to output various messages to the user depending on the circumstances ("you're logged in", "logged out", "status updated", etc). (At this point, I don't see the case where I would need to keep several messages in memory, but it's not really relevant.) So I could structure my code with a $_SESSION['message'] variable, or I could systematically pass an instance of a class Message, or even a string variable, from one php file to the next.

I'm not sure if there are compelling reasons to use one approach rather than the other.

EDIT: The "pieces of code" I make reference to above are MVC Controllers that decide which function to execute and what to display. They then redirect to a front controller, so the instance changes. The front controller then loads the views.

Upvotes: 2

Views: 284

Answers (3)

Your Common Sense
Your Common Sense

Reputation: 157916

The question makes not much sense to me.

In case you are talking of different PHP instances (for example, if you made a redirect after succesful login), you have a little choice but sessions.

In case you are talking of passing messages between code pieces within the same PHP script instance, there is no use for the sessions at all.

Upvotes: 2

Madara's Ghost
Madara's Ghost

Reputation: 175028

What you're describing isn't a dependency injection model, it's a Singleton model (as in, pass a single instance of a class all around). Dependency injection is about passing what you need for each specific object/function to run, meaning if you have an authentication function for your users, you would need a database connection, a user, and a password. So your code might look like this:

function auth($db_conn, $user, $pass) {

In your case, for displaying messages to the user, I'd go with the session approach.

Upvotes: 2

Matthew
Matthew

Reputation: 48304

Passing a Message object would allow you to change how things are implemented without having to adjust every piece of code that uses messages. Using a $_SESSION variable directly will tie you to your implementation.

I generally try to avoid using $_SESSION directly anywhere in the application, except in the core "boot strapping" procedure. It is a global variable, and those are by nature generally evil.

Upvotes: 2

Related Questions