New controller instance is created on every request


#1

Hey,
i am new to slim. Just trying to build my first project. I call a controller on 4 routes, but every time i call it the instance is created new. So when i try to hold a variable in the first request, it is null on the second one. Anyone has an idea how to fix it?


#2

Hi @jdl!

What you’re describing is how the web (and PHP) work; they’re stateless.

If you want to persist state between requests, you’ll need to use something like a session. You can store data against the session, which sets a cookie in your browser. When your browser sends the cookie on the next request, PHP will identify who you are and reload the session data.

I think that’s what you mean, anyway :+1:


#3

Hey,
thanks for the quick reply. So if i understand correctly, i can’t use the same instance of an object in 2 different requests?


#4

Correct, once the response has been set the application is essentially closed and the object no longer exists.

What you’re trying to do is likely available by sessions as @Antnee says, or perhaps through a flash value that likely uses sessions. If you give us a little more context on what you’re trying to do we can suggest an approach.


#5

Yeah. If you come from a Java background, for example, this can seem very strange. But bear in mind that PHP is a language that was built for the web. Web requests are disposable, which means that the PHP interpreter starts up from scratch on every request, and throws everything away at the end, too.

That’s not technically true, because we have op caching etc, but that doesn’t store state.


#6

Cool, thanks for the explenation.
I tryed to “save” a service in a variable. But on the next request the variable was empty again.
But i fixed it by putting the service in the container and “save” it in a variable via constructor in the parent controller. Now i can call it all the time.