AJAX - PHP Communication patterns - php

I'm building a webapp in MySQL/PHP/Javascript.
In PHP, I've got all the classes from the domain od the problem which persist in the database.
In Javascript, there is a cache with objects from the last queries.
When an object in Javascript is updated by the user, it has to update itself in server-side. Which would be the best way to do this?
Should I create a class in PHP and Javascript for communication purposes? Should each object in Javascript send an AJAX query to a different php file depending on the class of the object it needs to update?
Are there any patterns to follow to solve this?

Creating a separate PHP file for each class would certainly be more maintainable if this is a project of any size at all. It would also allow you to do things like have different server-level authentication based on the classes.
On the JavaScript side, you definitely want some sort of AJAX library, whether you throw it together yourself (I did one once in about 50 lines of JavaScript) or use one of the ones out there. You may need a helper function or two that knows how to serialize the data (XML, JSON, delimited, whatever).
You can write object oriented code in JavaScript, and if you're doing that already, it makes sense to add a write() or updateServer() method to call the AJAX library with the right parameters for consistency. If you're not writing OO code, it still may make sense to have separate functions, but only if there's more than one place you need to persist these objects from.

Most AJAX frameworks (jQuery etc) will send an 'HTTP_X_REQUESTED_WITH' header set to 'xmlhttprequest'. I like to use this to decide which view to use.
This means the same url can be used to retrieve JSON, XML, or HTML snippet via JavaScript or to return a full document if a standard GET / POST request is made.
This means your app will simply revert to normal requests should the user have JS disabled.

I think you should have a look into the RESTful API with PHP and JavaScript. You address your domain model objects as unique resources (e.g. /application/books/1). If you only want to implement CRUD functionality a generic Controller that updates the corresponding domain model (e.g using an ORM tool like Doctrine) should be sufficient.
If you really want to have the same model on the client side in JavaScript depends on your Application. I like the idea of just managing a single JavaScript object on the client side which will be loaded via REST and then populated to HTML Forms and send back e.g. as JSON (or as a simple form submit) to the server. If the client side model idea appeals to you, I recommend to have a look at JavaScript MVC which has a quite interesting model implementation.

Related

PHP Architecture: Save and use "constants" in whole system

I use my PHP (like normal) in a server architecture where I have an incoming request and build an outgoing response. All request attributes (like client ID) are given to each sub function and class to make magic with (like in my Mappers and Models and Helpers).
Is there an idea to work with request data WITHOUT putting it from function to function to function.
Idea 1: Make my Request/Response object static. I have exactly one request and one response so there is no problem to do this.
Idea 2: Saving data in Session (or similar). This also sounds uncomfortable and heavy.
Is there another idea doing this?
Implement your own Request or RequestContext class and populate a object of this type with all the data that ongoing methods might need. This way you don't need a growing number of arguments for each of your functions, instead you just forward the entire Request.
This is much easier to extend and you don't suffer drawbacks of "global" data. It's a typical pattern which is used by a lot of frameworks as well.

REST api - Updating table with POST from view

I'm new to RESTful web services and still figuring out the design/architecture aspect coupled with MVC pattern. I am using Codeigniter framework to implement MVC.
I had a pretty simple question. I am using using form data to update a table in my database. I have written an api that will do this:
http://www.example.com/api/resource/tablename/?param1=info1...
Typical api. What I wanted to know was, in the MVC pattern should I be using cURL in my VIEW to POST data and update my table with the form data or should I still be send the POST data to my controller and make the api call from the controller to update the table.
To me it seems arbitrary at this point as both will accomplish the same thing but what is the standard practice? Is it okay to directly communicate with you api from the VIEW to update your db table??
Is it okay to directly communicate with you api from the VIEW to
update your db table??
Yes, it is...in fact that is pretty much what you should do in this case! Send your data directly to the API. Your API should do all data validation and return an error message (in a standardized format like JSON, XML etc) if any data validation fails OR perform whatever action it needs to do with the POSTed data. A great benefit in doing so would be that your API can be used by any caller and would be a complete ecosystem by itself.
Without knowing more about your intended applications I can say this:
Typically you want to try and keep any processing logic (PHP) out of your views if possible. The whole point of the controller is to handle transaction operations from your model and then pass it to your view. So if you are using an API to gather some data from a service that is intended to be used/manipulated in your view then the logical location for that would be in the controller.
The MVC pattern isn't a hard and fast law of X goes in Y and Y goes in Z. It is a pattern that makes it easy to extend and abstract your data gathering, processing logic, and visual layouts.
Technically depending on the application and how you planned to use it you could create a model for the API so that it could be used in multiple controllers without the need to re-write it.

A Backbone UI and a CMS backend: Wading through the Restful CRUD

Backbone tutorials I have read implement some type of a mini-framework (i.e. Slim) with a RESTful architecture performing CRUD on a server db, like this. The Backbone docs state you need a RESTful api, which I believe is due to the Backbone Route and Sync functionality that keeps models up to date, which is a huge aspect of my choosing to use Backbone.
For example, the line below maps a faux url (route) to the 'addWine' function (within a Slim api):
$app->post('/wines', 'addWine');
Assumption 1: If I have a (PHP) CMS backend (and not a mini-framework) I assume I could simply replace the 2nd parameter (addWine) with my own CMS class method call and return a json object.
Assumption 2 But I would not be able to directly call that same class method from a link in the html without causing backbone to lose state and thus it's ability to sync the model data (and remember the browsers history).
Assumption 3 In that case, I will need to use the Slim api and route backbone urls through (Slim) RESTful CRUD calls in order to access my CMS database to keep backbone happy.
If those assumptions are correct, then it would seem backbone is intercepting those HTTP calls - which leaves me wondering how the whole RESTful + Backbone relationship works. Can you explain some of it?
If my assumptions are incorrect, then I need more help than I thought. Can you help with that?
Thanks
I can't speak intimately to your three assumptions, but as for your final question -- Backbone does not "intercept" HTTP calls -- it constructs them, just as any other javascript library would to create an AJAX request.
Backbone is relatively agnostic to your server side language/framework. Here is what Backbone expects any time "sync" is called:
Backbone's sync function uses different HTTP request types based on which method was called. These different HTTP request types are:
POST
GET
PUT
DELETE
Your framework needs to support all of the above to support the "out of the box" functionality of Backbone. This means that you must specify all of the above routes within your application in order to work with Backbone.
One other thing to note is the "create" and "update" method does not carry post data with the request specifically -- instead it sends a content body with a json digest of the data and expects the server side to properly parse a JSON object and deal with it appropriately.
I say yes to all three assumptions and also agree with #Andy Baird.
Also, the only problem to your project is how to notify Backbone that you have updated the database and you would like it to update itself in the front-end. I can only see two solutions:
1) using Javascript's setInterval() - if you do not need the front end to be updated immediately on DB update, you can check for changes every 1 minute, Backbone knows to only update what has changed and add new stuff but of course this is not healthy to the server if you have 1k active people making repeated request every minute
2) using SocketIO or similar service - this way you can send from the server to Backbone either the entire list of modifications to your DB or a simple 'Please refresh, new stuff waiting'. Check this discussion.

How can i handle a form submit using REAL OOP in PHP

Im used to java and creating UML.. and i was wondering how can PHP be OOP, the objects live only until you make a request.. then they destroy, so if im using a database is useless to create a class and add the members (variables) to the class, they will be useless.. i cant pass the main system object from one page to another, or similar so how can PHP be compare to jave? you never do OOP .. i mean REAL OOP.. not creating classes , in fact your index will be a procedural file with some object instance and then ? how about if i make a html form and i want to submit the data.. i have to call a file which is not a class is a php procedural file were i grab the submited data with POST, from that file you will instance a class and do some logic there.. but for me thats not pure OOP.. can somebody point me to the right way of OOP using a form submit example ?
Thanks!
You're labouring under a misapprehension that object oriented programming by definition includes a persistent environment with objects that exist independantly of page requests. I'm afraid it doesn't.
PHP does do "real" object-oriented programming. But PHP's execution environment is like executing a CGI program: upon a page request, the program starts and it ends when the page is finished. Within that paradigm, objects can exist only as long as the page is producing content. Therefore, the first thing the page must do is to load the framework to define and instantiate the required objects, such as a database handler and object mappers that must load and save their data within a page request cycle. Some frameworks will also create objects with the page-request data that your code and objects can then access, sometimes from within objects.
But PHP does not provide this natively because it does not enforce a framework. It is by nature procedural so a framework must be added so as to define and create the desired objects if you don't want to work that way.
There is an advantage to doing things this way. It means a page's code need only concern itself with a single page request. Almost all issues to do with data-sharing and multiply-threaded execution is pushed out to things that can handle it invisibly, like the database and the web server.
Check out any of the latest php framework and how they handle forms. (like ZF or Yii).
b.t.w the "problem" you refer too is client-server architecture and not a minus of PHP.
Each request is a new process with a new MAIN or new Class with static main function which are practically the same.
"so if im using a database is useless
to create a class and add the members
(variables) to the class, they will be
useless"
It sounds like you want an object-relational mapper. There are several popular ones for PHP, as discussed at this previous question.

Kohana - where do you put AJAX scripts?

I am using Kohana but this question applies to Rails, CI, or any other MVC web development framework. Where is the best place to stick one's server side AJAX scripts?
I was planning on creating an Ajax_Controller and using a method/action per individual script.
For example, a login form on the home page index.php/home would send an XMLHttpRequest to index.php/ajax/login, and the edit profile form index.php/profile/edit would send an XMLHttpRequest to index.php/ajax/editprofile. What's the best practice?
I tend to put my ajax actions in the same controller as the non-ajax actions for any given model.
When I can, I try to use the same actions and only change the output type. Most tasks should have a non-ajax version anyway, so this tends to work quite well. Very handy for reducing logic duplication.
AJAX crosses all of the MVC boundaries. That is, it doesn't go into just one of model, view or controller.
Your AJAX scripts will be calling scripts on your site - so this would involve a section of your controller layer which you've created for the purpose.
That controller in turn would access the database using the interface provided by your model layer, just as a non-AJAX request would.
The data for the response back to the client may be packaged as JSON or XML or something. Technically this is the task of your view layer, though if your application's definition of a view layer is nothing more than "an HTML templating system" rather than "processing and formatting anything that gets sent back to the client whether it's HTML or something else like XML" then your XML or JSON generation may need to go into a new little section of its own.
As for sending the scripts (Javascript files) themselves, this is probably going to be handled directly by the web server rather than from within your MVC framework.
Do you make different controllers for GET and POST requests? I don't. In my opinion, JS requests shouldn't be dealt with differently either.
I personally see JS requests just like GET, POST or any other type of request. So if I have user-related JS-based actions, I simply create them in the user controller.
If you mean the AJAX (Javascript) scripts themselves, these should go into your public/js folder. However, if you mean the actions invoked by these AJAX requests, they should be treated as any other actions of the respective controllers. To be completely RESTful, you should be using a different format (json, xml, etc.) as return values for those actions.
I am a noob, but based on my understanding, to achieve ajax with php mvc... thinking steps might be:
change the definition/function of the existing php view layer from 'HTML template' into 'results formatting (XML,JSON etc..' -> results from relevant module, which then called by controller to output into AJAX object, then it means you need to write view layers into each particular class with formatting methods
PHP module layer stays same
build a Ajax router class with JS which stay the same structure which you route in your PHP
build a ajax results handler class with JS to handle the results got back from PHP controllers (XML JSON etc..), then from here do whatever user interactions you want, this will be called by above Ajax router class
So,
ajax router (send XMLhttprequest)
-> PHP controllers C
-> PHP module -> PHP view results M
-> PHP controllers output results V
-> ajax results handle (into page)
I don't use Kohana but what I do in my framework is that AJAX scripts are controllers. I try to treat them as standalone controllers but in the end they are just controllers.
Using a separate controller is a good idea. I either organize my controllers by function and then actions by return type.
Additionally, when I'm using Pylons I can decorate an action with #jsonify and that will automatically take care of converting python objects to JSON. Very handy.
I like to keep all my ajax requests in one controller, typically dispatching their requests through a shared model (that the non ajax controller also uses)
The main difference being the view that results via the ajax controller (html fragments, json data, etc) or the non-ajax controller (full pages)
You could wrap it up as a general REST-api, and use RESTful conventions and URIs.
Example:
Instead of index.php/ajax/editprofile it could be a PUT request to index.php/api/profile/profilename.

Categories