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.
Related
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.
Session is retrieved in SF2 through the Request object. Hmm, this becomes kind of problematical when some architecture is considered - in cases where access to a session vars is needed from within a service.
Or perhaps, I'm not quite correct in this matter? (Hope so).
Obviously each request from a user through a webbrowser is a Request. So as long as we use controller actions in standard SF2, we have Request. But should we then pass the Request object to any service we need?
Passing Request object to all of the services that needs their methods to be run (e.g. storing info, checking settings, putting filters for displaying data etc. - well in some bigger apps it's quite a lot of them!) because it might be needed because of the dependent services, seems to be a very stupid idea to me. It also breaks the "S" in S.O.L.I.D. recommendation for OOP.
So I came up to a conclusion I need either to:
Pass the Request obj to many services just because the dependant service might need some data from it (i.e. broken "S" as above)
Retrieve and process data from Request every time I needed in every single controller action (i.e. code duplication) - in this case I don't pass a Request obj, but previously prepare all data needed - but I must do it then in many action methods in almost all controllers (retrieving/processing data from Request is just a simple call for another service, but then it's not centralized)
I'm putting this question, because I have e.g. the following problem to solve:
I'm using the same filters for all different data (from different data-sources) on the whole page.
Filters can be enabled and disabled - and they should be remembered for all the pages for the single session
I decided that saving "disabled" filters to a session is probably the best approach (because by default all data should be seen, i.e. all filters should be in "enable" state)
The 3rd point - saving data (filters) to a session - is what makes trouble in SF2, as described above. For displaying filtered data on page, I need access to a session, and thus access to the Request obj. And this means I have difficulties in keeping "S" in SOLID, because of making dependency on a service's method to always pass a Request obj to it.
Is there any other, better solution than the 2 mentioned (i.e. one, breaking SOLID, or two, code duplication)?
The session is also a service in the symfony di container, you can simply inject session into your servives
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.
The agavi framework uses the PUT request for create and POST for updating information. Usually in REST this is used the other way around (often referring to POST adding information while PUT replacing the whole data record).
If I understand it correctly, the important issue is that PUT must be idempotent, while POST does not have this requirement. Therefore, I wounder how creating a new record can be idempotent (i.e. multiple request do not lead to multiple creations of a record) in particular when usually the ORM uses an id as a primary key and the id of a new record would not be known to the client (since it is autocreated in the database), hence cannot be part of the request. How does agavi maintain the requirement of idempotence in light of this for the PUT request.
Thanks.
PUT can be used both for creation and for updating complete records. POST is usually used for partial updates and related operations as well as for creating a new type of record on the server without specifying a URL for the resource (e.g. POST to /articles/23/comments returns a 201 status and a Location: /articles/23/comments/283136 header). So in your case (with a sequence/autoincrement ID), you would use that approach.
However, HTML (and thus web forms) is different. It only knows GET and POST, not DELETE and PUT. For deletion and updating operations, it overloads the POST method.
That's why Agavi, by default, maps POST to "write" and GET to "read" - it's the most common use case, and "read" and "write" were chosen because they are relatively neutral and also in a way represent the safety aspects of GET vs POST (safety as in "GET can be called without side effects" and blah).
You can change the mapping of verbs for the AgaviWebRequest implementation in factories.xml; refer to the Agavi users mailing list or the IRC channel if you need help with that (or ask away here). A lot of people on the IRC channel are also quite experienced with URL scheme design in case you need more help with making your API pretty.
Instead of thinking of PUT as creating, think of it as "putting". You put a resource at a URI (ie send an entire resource to a URI).
PUT http://example.com/articles/1
If you repeat this (send the same entire resource to the same URI) you get the same result and you haven't changed the resource at that URI, that's what makes it idempotent.
If agavi's implementation of PUT is idempotent then it is implementing PUT correctly. Otherwise it's not.
PUT can be used to create a resource, except that if the resource already exists (or has already been created by a previous PUT) it will just update it. POST should not update resources, however, if this is simple CRUD. Note that the HTTP verbs do not have a defined mapping to certain actions necessarily, since they're useful for a lot more than just CRUD.
Also note that this question has nothing to do with REST - just proper HTTP usage. So please remove the REST tag.
I've had this problem before. This can be solved by changing the factories.xml
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.