So, I know that the general idea in PHP is that the whole application is loaded and executed every time the page loads. But for optimization of a sizable object-oriented PHP app that needs to be portableā¦is it possible to load an object into memory that can be used for every request, not recreated for each one?
I've seen people using the $_SESSION variable for something like this, but that seems like it is a) ugly, b) will take up a lot of space on the server, and c) doesn't really do what I need it to as it's a session by session sort of thing.
Is there some sort of $_ALL_SESSIONS? ;)
(Or, approaching the question from a different angle, are purely static objects loaded into memory each time you load the page with a standard Apache mod-php install?)
You are more or less looking for an equivalent of ASP/IIS's Application object in PHP. AFAIK there isn't one.
There is EG(persistent_list), a list of "objects" that are not (necessarily) removed after a request is served. It's used by functions like mysql_pconnect(), pg_pconnect(), ... But it is not directly accessible by script code.
memchache has already been mentioned. Can you please elaborate on "purely static objects" ?
Maybe you could serialize it and store it in memcache? I don't know if that would be any faster though.
Not by default, no. You'll have to use some workaround, whether it be a 3rd party tool (memcached, DBMS, etc.), or a built-in mechanism (sessions, serializing to a file, etc.) Whether it's faster than recreating the object for each record is up to you.
You could also write a PHP plugin for this. :) Or maybe there already is one. A quick google search revealed nothing but I didn't try very hard.
If you do decide on writing one yourself know that it's not as straightforward as it sounds. For example, webservers such as Apache spawn several child processes for handling requests in parallel. You'll have to be tricky to get data across to them. Not to mention proper locking (and lock breaking if a request hangs), handling of webserver clusters, etc.
What you can do is use the CLI version of PHP to write a 'daemon' app which persists across requests and maintains state etc, and then have a regular web based script which can communicate it with via sockets or some other mechanism (here's one example)
If the server is Your own machine then it should be possible to run a process in background that would do the "global thing". You could communicate with it using SOAP.
You would only need to create a SOAP object.
That's the only way I see to really create a long-lived object for php. Everything else is just serialization. There might be a technology outside PHP for that purpose though.
Honestly, I don't think Your object is big and complicated enough for it to be created and populated longer than it takes to make a SOAP call. But if creating this object requires lots of DB connections - it's plausible that my idea could help...
Related
Question about best practices / scaling of the web application.
What would be the best way to access application settings on which all users rely and can not modify. Data needs to be served in JSON, application is written in PHP / JS.
Have 3 ways in my mind:
Serve json as a php get request which will call final method
final function get_requestJSON()
{
return json_encode(array(.... ));
}
Serve is as a flat file with JSON written in it and use file_get_contents
Store it in text format in MySQL backed and access it directly with a model.
Which one of those would be considered fastest?
Any thoughts?
j
Don't worry about speed in this case (unless you know that the wrong solution is unacceptably slow) and instead think of your requirements. This is especially true because if you are issuing server calls through a client, there's going to be a latency anyway that will likely dwarf the time for this operation.
Also, the scenarios are not mutually exclusive. You can store things in a database, and use JSON as your protocol for sending things back and forth (for example).
I recommend you instead think about all the things you can see doing with this information, both now and in the future, and let that guide you towards a decision.
Taking all into consideration, php library with methods is the best solution for me. Thanks for the info though.
Any idea how to implement this (http://fluin.com/63) using MySQL+PHP+Javascript(mootools)?
In a nutshell, it's a realtime threaded conversational web app.
Update:
This uses http://www.ape-project.org/home.html
Any idea how to implement realtime stuff without AJAX push (ape)?
Install Firefox.
Install Web Development toolbar
Install Firebug
Install HttpFox
Read docs of above tools re how to use, what they can do.
Go to http://fluin.com/63. Use above tools to inspect.
Read up on Databases and data models, and MySQL.
Build your own.
Well, this depends on your definition of realtime, which, in its technical meaning, is simply impossible with public ip networks and traditional tcp stack, for you have no control over timing.
Closer to the topic though, to get any web page updated without direct user intervention, you'd have to use javascript to poll server for changes since the last successful poll, and do this over certain intervals of time. In calculating these intervals you'll have to consider both network/server load, and the delay that is comfortable for the user.
The server, of course, will have to store the new data and its timely status (creation timestamps are one way of doing it), to be able to distinguish between content already delivered to various clients.
As soon as the server reports new content, it is inserted into a dom page via javascript and the user sees the response.
This is a bit general, of course, but you should get the idea.
Isn't it like a shoutbox ? here an example of one
Doing this properly using PHP only is very hard. When you have 5 users you could use long-polling, but it will definitely not scale when you have let's say 1000 users.
Using comet with PHP?
The screencast(link) in my post shows how you could implement it, but it has a couple of flaws:
It touches the disc(disc is very slow compared to memory).
To make matters worse it also polls the disc frequently(filemtime()).
Maybe phet(PHP) is able to scale. You should try that out.
To make it scale I think you need at least:
a good implementation of long-polling(at least long-polling. You have better transports) that can handle load.
keep data in memory(much faster than dics) using something like redis or memcached.
I would use:
node.js with socket.io(video) module.
to keep data in memory I would use node_redis(video).
I just finished taking a final exam on web applications. Capping off what had been a rather easy (albeit lengthy - 12 pages) exam was a question asking us to code an implementation of sessions, similar to that done by javax.http.HttpSession.
I hate to admit, it stumped me. I cranked out a rather BS implemetation using a HashMap and did some craziness with a random cookie string mapping to a serialized HashMap on the server, but I'm pretty sure it's bogus...and now I'm dying to know how it's actually done.
Particularly as someone who has used PHP extensively but for whatever reason never bothered to learn the magic behind the convenience, I'm very interested to learn more about the underlying implementations of sessions. J2EE and PHP for sure, but any other languages/frameworks are great, too. Thanks!
From my understanding - you're close.
From my understanding a cookie with what is essentially an MD5 "ID" is saved on the client side and delivered via cookie or modified GET.
On the server side the "session" data with matched sessionID is saved in a temp file (on Linux it is defaulted to /tmp). The session directory I believe can be set in the PHP.ini file.
As it is an interface, you may look at the class(es) implementing it in an open-source web container like Tomcat, and see for yourself.
I am working on a project has me constantly pinging a php script for new data, so if I understand this correctly that means that the php script being pinged gets run over and over indefinitely. It works but i'm guessing its a huge strain on the server, and is probably considered ugly and bad practice. Am I right about that?
Is there any way I could keep the connection to the script alive and make use of php's built in output buffering to flush the contents I need, but keep the script running for infinity using some sort of loop so when new data is available it can be output. Is this a bad idea as well?
I'm just looking for input form developers out there with more experience.
One last thing...
Are there any other ways to keep a constant flow of data going (excluding technologies such as flash or silverlight)?
If what you have currently works and continues to work when tested against the kind of load you might expect in this application, it is not really considered bad practice. It is not a crime to keep it simple if it works. Anything that does what you are describing is going to go against the grain of the original model of the web, so you're venturing into shaky territory.
I do recommend you check out the Comet technique. It is mostly popular for the inverse of what you want - the server pushing information to a page continuously - but it can obviously work both ways. Although your mileage may vary, I've heard good things. As Wikipedia describes it:
In web development, Comet is a neologism to describe a web application model in which a long-held HTTP request allows a web server to push data to a browser, without the browser explicitly requesting it. Comet is an umbrella term for multiple techniques for achieving this interaction. All these methods rely on features included by default in browsers, such as Javascript, rather than on non-default plugins.
It almost seems like php wouldn't be the best choice of language for this. Possibly consider something like scala or erlang which are setup to handle this type of long lived messaging better.
You have to learn how to use sockets in php.
Start from here: http://php.net/manual/en/book.sockets.php
And afair here is useful manual about writing standalone php apps: Advanced PHP Programming
I'd say that depends. If you want the data transfers to be started by the client, your best choice here would be some ajax (like getxmlhttpobject or just iframes if you feel like cheating :P). If you want the transfers to be started by the server, then, perhaps php is not the language you want to use.
You can use ajax to have http-streaming. Take a look at ajaxpatterns.
I currently have a custom session handler class which simply builds on php's session functionality (and ties in some mySQL tables).
I have a wide variety of session variables that best suits my application (primarily kept on the server side). Although I am also using jQuery to improve the usability of the front-end, and I was wondering if feeding some of the session variables (some basics and some browse preference id's) to a JS object would be a bad way to go.
Currently if I need to access any of this information at the front-end I do a ajax request to a php page specifically written to provide the appropriate response, although I am unsure if this is the best practice (actually I'm pretty sure this just creates a excess number of Ajax requests).
Has anyone got any comments on this? Would this be the best way to have this sort of information available to the client side?
I really guess it depends on many factors. I'm always having "premature optimization ..." in the back of my head.
In earlier years I rushed every little idea that came to my mind into the app. That often lead to "i made it cool but I didn't took time to fully grasp the problem I'm trying to solve; was there a problem anyway?"
Nowadays I use the obvious approach (like yours) which is fast (without scarifying performance completely on the first try) and then analyze if I'm getting into problems or not.
In other words:
How often do you need to access this information from different kind of loaded pages (because if you load the information once without the user reloading there's probably not much point in re-fetching it anyway) multiplied by number of concurrent clients?
If you write the information into a client side cookie for fast JS access, can harm be done to your application if abused (modified without application consent)? Replace "JS" and "cookie" without any kind of offline storage like WHATWG proposes it, if #1 applies.
The "fast" approach suits me, because often there's not the big investment into prior-development research. If you've done that carefully ... but then you would probably know that answer already ;)
As 3. you could always push the HTML to your client already including the data you need in JS, maybe that can work in your case. Will be interesting to see what other suggestions will come!
As I side note: I've had PHP sessions stored in DB too, until I moved them over to memcached (alert: it's a cache and not a persistent store so may be not a good idea for you case, I can live with it, I just make sure it's always running) to realize a average drop of 20% of database queries and and through this a 90% drop of write queries. And I wasn't even using any fancy Ajax yet, just the number of concurrent users.
I would say that's definately an overkill of AJAX, are these sessions private or important not to show to a visitor? Just to throw it out there; a cookie is the easiest when it comes to both, to have the data in a javascript object makes it just as easily readable to a visitor, and when it comes down to cookies being enabled or not, without cookies you wouldn't have sessions anyway.
http://www.quirksmode.org/js/cookies.html is a good source about cookie handling in JS and includes two functions for reading and writing cookies.