Backbone.js Pushstate Routing and PHP Framework

2019-06-14 01:28发布

问题:

I am using Backbone.js along with a PHP MVC framework (Codeigniter, Laravel). I'm confused about how URLs will be handled by the PHP router and Backbone router when using Pushstates. (I have not started using pushstates yet, still using hashbangs #). I am not working on a single-page-application, but rather the site is made up of several pages that act like single-page-application on its own.

Problem: If I have a page http://domain.com/user/user123, and clicking a link http://domain.com/user/user123#photos loads some photos via AJAX and I want to get rid of the #, I forsee the problem where a user who goes to http://domain.com/user/user123/photos after clicking on the link decides to copy and paste the URL into another browser tab will see an error 404 page as the PHP framework router (if I assume correctly that the PHP router handles the URL request first before backbone's) does not recognize the existence of this url. How should this problem be solved?

Another problem I think will arise, is how should the view be rendered when the user goes to http://domain.com/user/user123/photos directly? Should the HTML code be duplicated on both the PHP View (for the instance where the user enters the URL directly) and the backbone.js View (for the case where the user clicks on the link from http://domain.com/user/user123)? This does not seem like the optimal solution to me. Or can the View somehow be rendered in both cases by backbone to avoid duplicate code?

Please advise :)

回答1:

You've hit on one of the more challenging aspects of incorporating pushState into a backbone app. Basically, you need to make sure that any route you'll be linking to within your app can also be handled by the server.

The easiest way to solve this, in PHP, is to route all requests for valid URLs (/user/user123) to your root page, and then let backbone call the handler corresponding to the url fragment. This requires you on the server side to actually know what a valid URL is (i.e. /posts/5 is valid, /posts/abc or /aaa/ is not, etc.), but otherwise it's not a huge amount of work.

Ultimately the problem is that you're switching between a stateless protocol (HTTP) and a state-ful application (backbone.js). This requires some careful planning.

Regarding your second question, you don't need to render the view on the server-side, just do everything you would do for a request to the root domain and backbone.js will trigger the appropriate handler (e.g. /user/user123). The only case where you'd want to actually render the view on the server side is if you want to support users without javascript, or make your app RESTful, in which case you would have to duplicate view code (there is no easy way around this).

Hope that makes sense.