tags:

views:

35

answers:

3

hello I am using zend framework and i am trying to combine it with doctrine. Not the hardest thing to do but what I wanted to do is a class with a static member that will be the entity manager and I want to create it just ONCE in THE WHOLE APPLICATION CONTEXT.

When I was playing with static variables in php to learn how it works in order to do what I want I realize that php creates a new instance of a static variable in each request. So the static variable only remains static through the request not the entire application is that correct, can someone tell how to do static variables for the whole application no matter the request that came to the server.

thanks

A: 

What you're looking for sounds like the Singleton Pattern. Look at that reference for ideas on how to implement it in your project.

GSto
No he's not. He wants an application scope, not request scope.
hopeseekr
A: 

Yes, static variables remain only for the life of the request. If you want a value to persist beyond that, you'll need to save it to some sort of external-to-PHP storage, like memcache or a database.

Alex Howansky
thanks for the response alex you are right
mongaru
A: 

You can't do this with PHP directly, you'd need some kind of persistence, like serializing the object and saving it in a database, and even then, you're going to run into a lot of concurrency issues.

PHP not only creates a new instance of each static variable for each request, it basically runs your entire application with each request. In fact, assuming you're running a web server like apache, it's running more than one instance of your application at once, since apache is capable of handling mutiliple requests at once. So even if you were able to serialize an object to a some sort of persistence like a database, you'd probably be overwriting changes that another instance of your application had made to it.

mikeocool
thanks mikeocool I was reading in php documentation that this can not be done. Although the part that multiple instances of my application are running at once doesnt seem to nice to hear. Didnt know that.
mongaru
Having multiple instances of your app running at the same time is actually something that's totally normal in almost all types of web app stacks. If you only ever had one instance of your app running, you'd only be able to handle one request at a time, and your site would slow down real quick anytime more than one user was using it. Generally, it's not something you need to worry about, but definitely good to be aware of for avoiding cases like this where it could cause a race condition.
mikeocool