Backbone and PHP Model Code Duplicate - php

So I have decided to take a project I have been working on, and project management system, and convert it from a standard multi-paged application to a single-page application. In the process I have looked at a number of javascript MV*ish frameworks (ember, knockout, backbone, etc...) and have decided to go with backbone.js as it seems the most flexible solution and that I already use underscore.js for both its utilities and template system.
The one biggest concern I have with doing this is the potential code duplication I am going to have for model and business/domain logic in both my PHP models and in my backbone models.
This is just a technical cost I have pay when going with an architecture like this or are there some things I can do to lessen this concern?

You may want to take a look at a previous question I answered involving Node.js:
Reusing backbone views/routes on the server when using Backbone.js pushstate for seo/bookmarking
What I'm currently doing right now is using Davis.js + Mustache + Java Spring MVC backened (based on my original question: Single page Web App in Java framework or examples?).
If the browser does not support Pushstate then I have the server do the entire rendering of the page using a Java version of Mustache (ie standard Web 1.0). If the browser does support Pushstate then the browser will make an AJAX request for a JSON version of the model. The model is then rendered client side use icanhz (ie javascript mustache).
This works fairly well if a large part of your logic is getting a model an then rendering it based on specific URL. That is your business logic is "based on some URL I'm going to render this". This is how most of the sites on the web work (including this one which is still rather web 1.0). Obviously this would not work for say something like real time chat or HTML5 game.
A python version of this design is mentioned here: http://duganchen.ca/single-page-web-app-architecture-done-right/
I'm sure someone has done a PHP version.

If you are using different languages in server and in client I think there is not possibility to avoid this partial logic duplication you are concern on.
If you definitely want to use same code in server and client you have to move all of it to the only common language: JavaScript.
There are multiple JS frameworks those integrate very transparently the development between server and client: derby, meteor, ...

Related

Principle of loading data to REACT.JS

Coming from non-JS html interpretation it's kind of hard for me to grasp the concept of loading server-side data to REACT.JS "view".
Let's say I've have a site built on Laravel (using routes). Each route request (e.g. "/", "contact") has it's own view. That view is loaded with data coming from a controller and displayed in the view. If I change the route I'll be redirected to another view and I'll get different data from a different controller.
Now the question. Let's say I have a simple site. Top part is my login information and maybe some notifications icon the content of the page changes with going to different sections of the web.
So If I keep using Laravel routes. Every page will be "re-rendered" + I'll have to manually select which components belong to that part of the site. I'll have to retrieve the information that stays the same from the whole web (e.g. login details + notification) again - this kills the react.js principle doesn't it?
Also, what is the best way to propagate server-site data to React.JS? Should I just "echo" out JSON object to the view and then "use" it in REACT?
Could I be pointed to some meaningful approach of how to use React.js along with PHP.
You mostly answered your question :-) With Laravel, the UI is rendered on the server. React is mostly interesting for client-side UI. That said, not everything can be done on the server, and some user interactions can only be managed by the browser. That is why jQuery became so successful in addition to PHP.
If your app deliver some complex client-side code, it could be usefull to build this code as React components, even if you keep your current server-side router: to make the code easier to maintain, but also to write - once familiar with React way of implementing things.
If you would like to transform your app to fully use React and a client-side router, that enable browsing the app without re-rendering at each page, this is called SPA (single page apps). The react ecosystem is pretty cool for building SPA. Usually, though, the server is just a static server delivering JS files, and the app connects to a REST API of some kind.
In some cases, routes can also be served from the server, for specific purposes:
Faster display of first page
Social Graph tags can be added to the specific page (to enable usable Facebook
or Twitter shares, for example)
Should you need to enable this server-side routing, which makes your app universal or isomorphic, you must use components that can be understood by both the browser and the server, this is why React app are usually served by Node.js, so everything is in Javascript.
Example tutorial about building a universal app with React https://medium.com/front-end-developers/handcrafting-an-isomorphic-redux-application-with-love-40ada4468af4#.h8p6lc23w (your intuition is right in this case, a JSON object with app current data is sent at first render)
Also check the awesome react page (https://github.com/enaqx/awesome-react) if you're interested in the React ecosystem.
Recap:
PHP + React: Easily add complex components to some pages, better to keep it that way if you just have a lot of static content, SEO, and just a few complex components on a single page that React can help you with.
React + API: Common SPA app, better for rich and complex UI, pretty easy to develop if starting from scratch and familiar with javascript, but complexity arise with performance management and SEO on large apps
Universal React: the best of both worlds, setup kinda complex (cf tutorial)

How much PHP for AngularJS

I'm relatively noob to the world of web developpement, and after learning the basics of HTML5/CSS3/JavaScript/jQuery I've started to learn AngularJS.
The problem is that as I am learning AngularJS, I don't understand what will be the point in learning a server-side language like PHP, it seems like AngularJS can do all the job (UI, views, routing, ...)
I think that the only reason would be to store data (but even that, I can use JSON files, no?)
and if it is, how much PHP do I need to learn? (or which parts of the language)
Thank you and sorry for my english.
Angular is a tool for a specific sort of job. It is not the tool for every job, and neither is PHP.
If you are writing an application that can live client-side, then you can certainly generate all of the dynamic components you need with Angular. There are many web applications out there that are entirely client-side. There are even more that function client-side and talk to a simple API server for their back-end.
If you are creating a web page that is not interactive, then there is little reason for something like Angular. There are benefits to having the DOM filled with content ahead of time. SEO is usually the biggest reason, but you might also consider clients that have disabled JavaScript (if you care about those).
Are you building something that is interactive? Consider a heavier client-side framework like Angular. Are you building a web page that is content-driven? Consider rendering your pages server-side. In the end, you will likely end up with a mix of both anyway.
A large consideration is security. Everything client side is exposed to the world. If the back end is just data storage without validation or protection except as written inside the client, a malicious user could push whatever data they wanted into your site. In addition if you are exposing code that is the core of a business inside the client, every user can see that as well.

PHP Backend Framework for Mobile Web (jQuery) Android and iOS Applications

So I have a simple jQuery Mobile site interfacing with a MySQL database via PHP. Users orders are queried initially, then updated using the mobile web interface. I am not using any PHP framework, just 7 or 8 PHP files I've written for retrieving, updating, creating, and deleting order records.
As I begin to develop the Android and iOS applications, I realized it would be beneficial to have a PHP backend framework that can handle requests to create/read/update/delete my orders and users records from any of the 3 sources without caring which one it is. I want to create a layer of abstraction between the server side database handling and each of the 3 mobile interfaces. I envision being able to make a POST call from the client side, passing a TYPE argument and a JSON array of the data to a generic page like /myserver/mRequest.php, which would determine what to do based on TYPE and handle the processing, returning a STATUS variable and a JSON array of data back to the client.
Is there a good (preferably free) PHP framework that will help layout the backend? I've looked at Zend and a few others, but they seem pretty heavy and intended for desktop sites. I want to minimize the number of calls to the server as well as the amount of data thats sent back and forth (we all know how slow Verizon 3G is).
I'm hoping theres some lightweight framework out there that can be a skeleton for me to organize CRUD functions, check for null values, handle MySQL errors, etc...
If not, a guide to developing a PHP mobile backend would be the next best thing.
Note: I apologize it there is a thread already asking this, but I couldn't find one that I thought fit.
Almost any of the major free frameworks would do the trick, Symfony for example handles regular page templating for your jQM pages and handles ajax nicely too.
However, if you only require the framework for the AJAX handling and something broader, you might be advised to develop your simple scripts, with less effort and less of a learning curve (of course, the learning may be part and parcel of your plan).
Another option is a Data Abstraction layer between your scripts and your PHP, this would give you greater flexibility in terms of your data changes, but not burden you with a hefty framework in between. Propel and Doctrine are worth a look and are often used as part of web frameworks.
I personally really like CodeIgniter, which is a very clean and powerfull lightweight PHP framework with easy database-access.
Just have a look at it.
Greetings,
Steffen

PHP MVC with pure Javascript View : good practice?

My question might not be understandable enough, so let me explain the situation :
I'm working on a big ajax webApp built, server side, with PHP using CodeIgniter. This framework saperates clearly models, controllers and views. The view files are rendered in HTML and then sent to the client that does some js treatments on it (like attaching events).
This way of working seems strange to me, as it separates the view between the server side and the client side.
I was thinking about moving all the View treatments to the client part that will build dynamically its html in js. The server side will then send only raw data.
I worked this way on smaller projects, and I was really happy with the result (easily understandable, portable and reusable).
Is it a right way to implement an MVC app ? Any advices around that reflexion ?
I've done pretty much what you are describing on a fairly large data services app as an internal application. In my case I was using ExtJS for the client-side rendering/views, and was communicating to a C# WCF endpoint exposed on the web server. Essentially requests were made/submitted and responses were serialized to/from JSON. It ran very smooth, once some kinks were worked out. The original author had written a custom serializer to do direct results from their data layer directly... this leads to a lot of extra data going down the pipe. As long as you are judicious with your payload data it can be very effective.
Some caveats though...
You should probably avoid this if you expect users without javascript enabled to be able to access the site (anything involving money transactions from external users).
You will want to document your methodology as clearly as possible.
Finding developers for maintenance tasks after you have implemented your application will be very difficult. (many server-side devs are shy of, scared of, or just plain inneffective with JS skills.
For the most part it's a toss up, I find that most people at least have JS enabled, but may have other things blocked off. AJAX/XmlHttpRequest supports is nearly universal at this point.
As to templating for client-side display, there are a few options there (but that's a separate discussion).
Building JavaScript views works fine within the MVC pattern, since your view is not mixed in with your business logic or model.
However, there are a couple drawbacks to using full javascript views. Mainly it eliminates the ability for graceful degradation if the client has javascript turned off. Also, some browsers (IE) don't have a very fast javascript engine, which will make your page load more slowly. It is true that some of the view is separated between the client and the server, but it kind of makes sense when you think about it.
In most cases the HTML that you send to clients is the same for everyone (unless you are doing browser detection on the server side). However the JavaScript routines are different. If you are using a library like JQuery, this will be hidden from you, but the code that is running on each client may differ greatly. One example of this would be the XMLHttpRequest that is used by firefox/webkit etc browser and the active x control that is used by IE. Since the html portion of the content is the same for everyone it makes sense to build on the server, and since the JavaScript portion of the view may differ, it make sense that it is built on the client side.
HTH
I started using the same approach: JavaScript for the user interface layer and PHP for the database access layer. I'm using AJAX to pass all the data back and forth between the 2 layers. So far, AJAX has occasionally frozen on me, but it has been speedy enough most of the time. So I guess it'll work well enough.
(The result is that my code has gone from 90% PHP with 10% JavaScript...to 65% JavaScript with 35% PHP.)
I've also separated the code for my page views from the code for my triggered event action functions. So I like to think that I have an MVC arrangement now (even though I'm not using an off-the-shelf MVC framework like Backbone.js).
I'm not using HTML templates, though. I don't think it feels natural to have 100% separation between HTML and programming. I think simple programming loops, conditional statements, and JavaScript triggers all go nicely with HTML.
If you will think it in the way that there is the main view that creates the html/js engine and couple of ajax views with the data streams - it will be quite OK in MVC terms imo.
Is there anything more dynamic going on on the site itself? Does it do more AJAXy things, dynamically refresh parts of the site etc.? If so, it may be reasonable to have a Javascript-only site.
Since this is not how the web traditionally works though, sending HTML from the server is still the baseline. If your pages are basically static, if you want to serve older clients, an audience that may have disabled Javascript, an audience that may have accessibility problems with Javascript-only pages, alternative clients that cannot understand Javascript or search engines, you should serve HTML pages from the server. There's nothing wrong with it, it's straight forward, simple and foolproof. There are many things to consider when reinventing the wheel in Javascript on the client side. Unless you have a good use for the potential this offers (see for example the highly dynamic Facebook or Twitter pages), it may be more trouble than it's worth to your users.
It sounds like you are one step away from going from the MVC pattern to the MVVM pattern.
MVVM is ideal for complex user interfaces (which is exactly what you would be creating with all the AJAX and JavaScript and whatnot) because in this case your HTML view will be able to act as the controller via JavaScript. There is a library (warning: I've never used it but it looks promising) for this called Knockout JS.

good php framework for fully ajax-based web applications? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
i'm developing a web application that focus heavily on ajax. the whole application is just on one page except for the threads that are in traditional pages so they can be indexed.
so i have to have very structured JS-codes and i wonder if they are any frameworks out there that are for ajax-based applications.
eg. codeigniter, cakephp and others i have read about dont focus on this. they just organize regular php code according to mvc.
cause my code starts to be very messy (especially the js code) and i really need some structure here. is there a way to have same mvc + oop structure in javascript? i never heard anyone talking about it. even if i put js codes in separate files, one for each page for example, there are a lot of lines and i feel lost and crunch whenever i have to add some new functionalities.
would be great with suggestions and ideas how to structure this up!
I think you have the wrong mindset about this.
AJAX-heavy sites or applications aren't that much different form their Web 1.0 counterparts in their underpinnings. You still have the same basic components: HTTP Requests and responses. It's just that with AJAX you rarely request a full HTML page. Most of the time you're requesting snippets of HTML, XML, or JSON.
So, just because you'll have a web site/app that is 90%+ AJAX driven doesn't mean you need to throw away existing conventions like MVC and look for something new.
And most modern frameworks have plenty of AJAX stuff baked in: ZF, symfony, cake, etc.
EDIT
I don't know of any framework, PHP or JavaScript, geared towards what you are asking. That being said, you might get something out of watching High-performance JavaScript: Why Everything You've Been Taught Is Wrong, Designing the Rich Web Experience, and High Performance Ajax Applications, even though they're a couple years old now.
Also, consider digging into projects that are AJAX heavy and seeing how they tick. ExtJS and jQuery UI based applications would be a good start.
You might check out Zephyr. Never used it myself, I just know that it's mainly for AJAX apps.
The symfony framework is great for Ajax, and they have a well-thought-out approach involving the MVC backend and your JavaScript code, especially the popular JavaScript libraries like JQuery and Scriptaculous.
It would be worth your time to read the chapter on Ajax in the Symfony Askeet tutorial just to see how someone else has done it. Also, the Ajax chapter in the older symfony book outlines other uses besides the search autocomplete feature shown in the Askeet tutorial.
You want something special for ajax, that can integrate into other frameworks? try, Cjax : http://cjax.sourceforge.net/examples/ , good for heavy ajax, with ajax controllers and routes.
I was told to put in more details so here it goes...
It allows you to write ajax in the PHP side, it gives you many tools that you can use to make your development experience a smooth ride. It also saves you tons of time from re-inventing the wheel
Cjax comes with over 70 examples/samples/docs and APIs that can let you do amazing things with a single line of code, that otherwise would take you hours or days, or even weeks!. You know, the usual success message, to lightbox, submitting forms with ajax, and uploading files with ajax, you know - the usual stuff that you would use in your application or website, has become an e-cosystem of ajax functions.
Cjax consolidates all your ajax code in a single place. Making your code more secure. Cjax also has only one point of access. Making your application or website very secure. Cjax lets you use classes and routes your ajax calls through a dispatcher to reach your ajax controller. Includes a callback system, that lets you do ajax requests when the page loads, but also, when you trigger your ajax request once on the server, it lets you run more ajax code, and interact with your application or website right from the back-end, right from your controller. This gives you the freedom to go back and forth, from one ajax method to the other, working in harmony. Also includes a way that you can maninupate all the elements on the page, right from the back-end, all done within one ajax call.
Cjax is a piece of machinery to build ajax features . Uses unconventional methods to push the bounderies in allowing you to just write very few short lines of code .
Cjax has the power to allow you to to call and use your existing JavaScript, without making changes to it. It really lets express yourself in the way that you want to express. You have old, or new custom JavaScript, execute it with Cjax - you can pass data to your existing functions, instanciate them, right from the back-end. You use other 3rd party libraries or code - no problem. Cjax lets you execute it, and pass data to it, right from the back-end, you can call them as many times as you want, no limit, only the sky. You can pass from simple strings, or integers, to entire arrays or objects. Guess what, As a matter of fact, that is what Cjax's plugins are, 'plugins' is just a formality, but what they really are - custom code ran with Cjax. If you run your custom code, you already built a Cjax plugin!
Cjax code is simple easy to understand, and uses convention over configuration approach to do the most, with less.
I will give you some examples:
Pagination: http://cjax.sourceforge.net/examples/pagination.php
autocomplete, ajax uploader, etc.
Check out Yii or Zend Framework.
I build apps like these. My architecture:
Server-side: Zend Framework
The PHP code is exposed as a set of JSON-RPC web services. The web services are implemented with Zend_Json_Server, and don't do anything HTML generation (all UI is handled client-side). Because of this, the server-side code is fairly limited (database interaction, session management, and security).
Client-side: ExtJSThe code is bootstrapped from a single PHP page hosting the ExtJS framework, and after that dynamically loads javascript components as separate files on-demand. Each javascript component calls a web service to initialize itself and load/save data. There are also special translation files (dynamically generated from PHP) to patch the class prototypes with translations.
In this approach the web services do not send back any sort of pre-generated HTML. They are data bridges, shuttling records back and forth. All UI construction is done client-side. Zend_Json_Server exposes a PHP class as a service (the methods of the class are the functions of the service). This keeps the PHP design clean, and offers ultimate flexibility in UI. The mobile front-end is built around the same classes as the RIA front-end. It's also easy to build other apps on top of the same web services (e.g. a windows app, an iphone app, ...). The minimal amount of PHP code keeps server overhead low.
If I were you I would focus more on what javascript framework you're using than on a PHP framework. If you're going whole-hog ajax (without basic html fallback), there's simply no point in getting the server involved in generating the UI (it just slows the app down).

Categories