Im building a PHP JavaScript web App. My main concern is how can I stitch the JS with PHP. For example; I have some PHP Classes defined in the backend and some object instantiated at the time the first page loads; obviously the JS has no idea about them. When I make an Ajax call to a php file that has no reference to the Objects, how can I access the Object that were already instantiated instead of having re-instantiate then again. Is it good practice to store the Objects in the session maybe? Is there a "best practice" for scenarios like these?
-
php is a share nothing architecture - memory is not shared between requests, all variables are destroyed when the request ends. You can use some kind of cache if needed – Steve Jul 15 '14 at 15:43
-
Do you want to create phonegap like app with using php? – Bik Jul 15 '14 at 15:50
-
no a phone app, but a web app. Sorry if I wasn't clear. – ecorvo Jul 15 '14 at 17:16
2 Answers
PHP is server-side and JS is client-side. So JS can't access PHP variables, functions, objects, etc. Besides that PHP is stateless so that means there is no connection between requests. After the request is done by default everything is gone, but there are several ways to store objects or data over multiple requests, including:
- You can use $_SESSION to store data or objects.
- For data over a single request you can use $_GET or $_POST.
- You can either store data with javascript with for example localStorage.
-
That's ok. It's a choice you have to make. Or you query the data each request over again or you store your object in the SESSION so you only need to query it once. There is nothing wrong with storing objects in the SESSION. It is placed on the world to store data! – S.Pols Jul 15 '14 at 17:30
You say you are building a PHP JavaScript App.
What I read: 'I have no idea what these words means, but they sound cool.'
PHP is a server side language. As allready writen in one of the comments. It is a share-nothing architecture. Objects, variables, ... only live as long as the request lasts. Once the request is over, everything is destroyed.
the request finishes (normally) with an answer. Often HTML or JSON. This HTML holds some Javascript that is interpreted byt the client browsers. It has nothing to do with PHP. It doesn't even have to know that the server is using php.
JavaScript on it turn can use AJAX calls to comunicate with the server. that then parses the query and returns the result. and so on

- 1,365
- 9
- 13