I am in the process of removing direct dependencies from an existing project. I have now come to removing the direct use of $_SESSION inside scripts. This is to make the same scripts available for an environment other than a web server such as PHP CLI.

The code base I am working on consist primarily of classes, so I have thought of making a generic interface declaring common methods such as fetch($key), exists($key), delete($key) and so on. Any class requiring access to the session would then implement this interface, thus making testing easier (which is almost impossible at the moment).

So the questions are:

  1. Do you guys think this is a good approach
  2. Are there other ways to achieve the same abstraction

I am open to suggestions of all kind as I am also using this as a learning opportunity. If you link me to a library doing this I would prefer if you could also write a few words about why you chose it.

1 Answer 1


It's quite common in large MVC frameworks to see the session superglobal wrapped in an object, and the idea of being able to inject something else in its place in a CLI context is a good one.

Try looking into components other people hand already built, as well. The Symfony HttpFoundation component and Zend Diactoros might be of interest, if you're using the $_SESSION superglobal to work out details of the HTTP request.


In case it wasn't clear from the above, I was suggesting having a single class that handles session interaction; I think a compositional approach like this would lead to cleaner architecture than the use of inheritance proposed by the title of your question. It kind of depends on the specifics of your code, but I think that this approach combined with the use of mock objects in unit testing will probably improve the testability issue you've identified with inline access to global state.

  • Thanks for you answer. I had looked over the source code from Symfony and found it troublesome finding where things were actually done. After some time I started wondering if Symfony actually did something like this. The Zend Diactoros sound nice though. Again, thanks.
    – AnotherGuy
    Commented Aug 1, 2015 at 19:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.