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.
Related
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.
What I would propose would probably sound strange, but I have my reasons for it.
For a long time, we've had this Spring based API, which originated as an abstract set of REST services for CRUD functionality. With time however, we started building business and presentation layers on top until we reached a state of a dead end. Do not get me wrong, Spring/Hibernate are great frameworks, and being built on top of the JVM has its definite advantages, including performance over other web technologies, such as PHP. Compared to PHP, it gives us a much deeper way of controlling aspects such as transactioning, multithreading, dealing with byte data, control over native C++ applications, using JNI, etc.
Where the stack clearly hits a hard wall, is where the requirements get changed most often, namely the business and presentation layers. Turning the applciation into a modern, user-centered social applciation, we've experienced the toughest challenge in out careers. Java EE presentation technologies are tough to work with. Also, changing the business requirements became a tremendously long cycling because of the traditional hurdles in building testing and deploying massive Java applications.
It also felt like for a large part, we are trying to reinvent the wheel. In the PHP world, so many projects exist already, which give you a complete management system, agnostic to any kind of backend system (mapping hooks to REST/SOAP endpoints) . Many of them have all these functionalities ready, allow for admin-friendly change of scenarious, and rules, have templating, etc. Plus, being PHP based means absolutely no time wasted in building and deploying. Write the change, test, asert that it works, and switch.
Our idea now is to find a way to move the business and presentation layers in such a kind of front-server PHP-based application, and leave the pure backend stuff to Spring/Hibernate. We have a few concerns though, coming from our relative inexperience with Spring.
If we implement the business methods using PHP methods, how do we keep transactional security? I mean if a business method has to make three separate HTTP requests to the JAVA, how can we guarantee that they will all be executed in the same transaction, DB-wise?
Is there a way to use proxies or promise objects between both systems? For instance, if the PHP business method needs to call a Spring search method get a collection of objects from the database, and then pass it on to another spring method, this will mean that teh whole collection will have to be sent back and forth. Perhaps, one could store it in a session object on the JAVA side, and simply sent an empty proxy back to the frontend, which the frontend can bass back to another jav method.
A lot of our Spring based functionailities rely on a structure of plugins, using Spring events. How can we make so that our frontend server also gets notified on every ackend event that happens.
I have two ideas here: a post-processing-filter that simply makes a POST request to a controller on the frontend server, using some naming convention.
or ... using some kind of a message queue, such as JMS or RabbitMQ, or why not even something like Reddis, where one can watch data for changes
Anyone who has done that before? Is this a good idea in general? Any suggestions how to resolve the aforementioned issues?
This is not what you asked, but I think it's worth saying that some of the problems you are experiencing with Java are problems that most experienced Java developers faced some day, and most have found some solution. For instance, you can use Arquillian to do a "faster" TDD in Java. And you can use JRebel to do a "code-and-refresh" approach, like in PHP. Modern IDEs also helps in refactoring, something that helps in the "requirements change" scenario.
Granted, the presentation part is still a big problem with Java. I personally don't like JSF, and (to me), most of the other presentation technologies are either non-intuitive or they are cumbersome.
I would say that this is the reason why a lot of Java developers are becoming adopters of HTML5 and Javascript (backbone.js, underscore.js, jquery, ...) for the frontend, with REST in the backend. There's no need to have PHP in the middle.
I'm afraid I cannot answer your other questions, but perhaps a good start would be to see if PHP could be run from inside a Java EE container? I know this works for Ruby and Python apps, as JRuby and Jython would take care of the bridge between the two world.
Largely what you are trying to do is what we call: SOFEA
In this case PHP is your frontend and Java is your service layer.
Concern 1
Transactions over traditional REST or WS are a PITA.
Either consider aggregating your service calls to do more work so that the whole entire transaction is in one service calls or have Java handle your frontend. Otherwise see Concern 3 with Finagle.
Concern 2
I recommend you stay stateless and do REST or RCP.
It sounds like your concerned with speed which I think you shouldn't worry about till its a problem. However if you do want to do user based caching of objects I would use Redis and its pub/sub feature (or RabbitMQ + memcache).
Concern 3
Use RabbitMQ, or Redis, or/and Finagle.
MY final Opinion
I don't think you need PHP particularly if you know Java.
So much of the web app world today is moving towards Javascript (in the client) I don't see any benefit to using something like PHP serving pages when there are better options like Node.js or just sticking with Java.
And #jpkrohling is right... templating and frotend used to suck in Java but its gotten much better particularly since most of your UI code will be in Javascript anyway.
If you need an example of more modern web stuff in Java have a look at this project: MWA and also by the same author: Handlebars in Java.
To sum it up my opinion and go back to SOFEA: backend = Java and frontend = Javascript
Haven't done this before, not sure if it's a good idea, but here are some thoughts on your questions:
First of all, in the PHP world, each request (whether it uses keep-alive or not) is run as an isolated process, so this scenario is typically unheard of; it's possible to use persistent database connections, but any non-committed transactions are automatically rolled back when the request is done. Now, this is where my knowledge about Spring is lacking, because I'm not sure whether Java can keep a database connection in the same state between requests as long as the same HTTP connection is used; if so, you can use PHP + cURL to perform three HTTP requests while reusing the network connection.
Object (un)marshaling between PHP and Java will probably not work very well; a representation of the collection would have to be made in the form of perhaps a result identifier that can be fetched via REST by PHP and passed back to Java as an opaque string.
It should be noted that PHP requests are typically short-lived, which makes it a good candidate for horizontal scaling; long running processes, such as those for Pub/Sub systems, are therefore seen less often. Personally I prefer using the alternative of sending HTTP requests so that the frontend caching can be abstracted away from the Java service.
I'll add more when I think of anything else, do let me know if my answer gives you more questions :)
There is definitely no straightforward way out. You have to re-write your backend controller layer which exposes REST calls to PHP. You need to group some fine grained services and make them coarse grained.
A word of advise - you can make things work at the end day with tweaking here and there, introducing a queue or another framework or library etc - but you would have also introduced lot of Accidental complexity..
Things can get real nasty in future during maintenance, bug fixes, upgrades etc
If speed of development is a concern, explore other alternative like Play Framework 1.2.x framework, so that you can re-use your server side code as it is.
I am working onr a backbone.js app, where one of my views is a complex feed with different types of subviews.
I will have to generate a static version of that view to be usd for email purposes. I am looking for the most practical solution that will allow me to reuse as much as I can from the existing code without duplication
I came up with two options:
Generate the view statically using php. This will men that I will have to duplicate a lot of the logic because of the different languages.
Set up a simple nodejs http server which will reuse most of the app logic to create a view on the server side. This sounds nice, but I am still unaware how practical such a solution will be in the long run. For ecample, I am completely unaware whether I would be able to use Jquery on the server side to create the layout from an existing html file.
Which one of he two options should I go for and why? Or perhaps there is a third one?
I debated a long time about this exact issue when I started working on my first backbone.js app, because like you I thought it would be a waste to duplicate so much view code. I'm working in rails, and my goal was to use the same format (haml) for partials on the server (haml/ruby) and templates on the client (haml/coffeescript), but that proved to be impossible and anyway not very advisable.
Anyway though, after having worked on the app for several months, I've come to the conclusion that the duplication is not a major issue. It certainly is not worth it trying to avoid duplication if the end result is only a couple of pages. Also, in my case at least, the static page I'm sending from the server did not end up having exactly the same structure as the templates that backbone.js renders, so it's not 100% duplication anyway.
Not sure if that helps, but in any case I'd suggest first duplicating the page and see how much extra work is actually involved. More complex solutions like #2 with the nodejs server strike me as overkill unless you'll really be serving a lot of pages this way.
For what it's worth, here are a few discussions of the topic on SO:
Rails Client side / Server side rendering using single template (handlebars or Mustache) with Sammy.js
Template language that works on both server and client
I'm starting to architect a quite complex web application. The implementation is probably going to be done in PHP, though if there are impressive reasons to choose a different environment I might be convinced.
I've looked at tools like Symfony and CakePHP. The problem is that it feels like they're relatively low level for a modern Web 2.0 application. They handle the basic things like MVC and scaffolding, but not the more advanced UI elements that I'm looking for. Here are some of my requirements:
Single page architecture. With minor exceptions, there should be no page refresh. All actions are done via ajax, the way it's done in gmail, and to a lesser extent in Facebook.
Ajax layout and widget handling. Not only the application doesn't refresh the page, but the developer can specify the layout and load various widgets into different parts of the page. This is somewhat like iGoogle, but should be better integrated.
Support both on the client side and server side for AJAX widgets. It should be trivial to display the result of a select statement in an AJAX table/array like http://developer.yahoo.com/yui/datatable/. This should also apply to other widgets including
Trees
Menus
Forms
Speaking of forms, there should be easy integration with client side validation
Signup/Authentication/Authorization. Including all the housekeeping things like forgot my password, CAPTCHAs, etc.
There's more, but I think I've given enough details so that you get an idea for what I'm looking for. Basically, I'd like to engineer a modern Web 2.0 app and skip writing, testing, debugging things that most web applications need to do. And yes, I know I can take YUI or jQuery and slap it on top of one of the regular platforms, but then I'd have to write all the glue. Now if there are modules that do this, that would be interesting.
So if you say, take Symfony + modules xyz + jQuery and there's your answer, I'd be happy to hear that.
Finally, in terms of priority, I'm looking for something that's scalable, reliable, well engineered more than something that's easy to learn and deploy.
Since you are looking for all things AJAX, why not try GWT? Its not PHP I agree, but it makes writing AJAX applications easy for developers.
I agree with #Iznogood. What your looking for is not actually a framework but a talent.You can make any framework as "igoogle-ish" as possible if you know what your doing.
I suggest look for a framework with a huge and active community like, CI, Cake and Jquery. Search/ask the community for the specific things you need. Plug it in and Presto!
But I'm afraid you'll have to write some of it.
If you don't mind using Java, there is ZK:
http://www.zkoss.org/
I'd prefer using this over GWT.
In php, you might want to consider Cjax http://cjax.sourceforge.net/.
It is MVC oriented, and has a very generic API, with full support for customization, including the development of plugins (There is a full Plugin API available, including documentation, Plugins can be built in PHP and JavaScript in combination -- see uploadify and validate plugins).
It can access all JavaScript functions, Objects and proprieties, and elements properties and functions from PHP server side, with one line of code.
In Cjax,
you can execute ajax actions, inside controllers (ajax requests) - without a line of JavaScript. this allows you to fully function without refreshing the page. It also allows you to access all Js objects from PHP. A good sample that reflects this is the "recursive ajax request" see that demo. The API can be used on page load, when the page first loads, and within every single ajax request.
Do take a look at the documentation and to the 20+ demos included, and no where you will see a single line of JavaScript. It allows you to manipulate elements, containers, request ajax, submit ajax forms, creates overlays, upload files through ajax, all from the server side. Take a glace at the API Table.
It has support for both, server side ajax, and client side, (see plugins JavaScript Documentation)
It plays nice with jQuery - the validation plugin in jquery is full executable in PHP without a line of JavaScript (see http://cjax.sourceforge.net/examples/plugin_validate.php without any custom line of Jquery inside the framework, it's all plugin's work). Ajax Responses from Jquery also get processed by this framework automatically, so using Jquery's Ajax function API wise, is the same as if you were using the Framework's Plugin's JavaScript Ajax Functions.
And you would just have to take your time learning more about it, because it has quite a few more tools that I am sure you'd find useful.
Currently there are two official releases, the generic release and
there is an official release for CodeIgnater of this framework (and it is the leading ajax option for codeignater) , and works great in conjunction other PHP Frameworks and without them.
Signup/Authentication/Authorization. Including all the housekeeping
things like forgot my password, CAPTCHAs, etc.
This is something that you can build within an ajax controller, the framework itself its meant to be a generic "AJAX" framework, so if you are looking for none ajax features, you will need to build them or integrate other PHP Framework with Cjax (such as Codeignater).
I do not know if this matches all of your criteria, or if you ever will find one. However, I like the Zend Framework myself.
As for the UI and AJAX portions - the server side technology matters little, and it's more about browser-side technology and interaction mechanisms, as well as DOM manipulation.
jQuery is my favorite for that. As for the PHP back-end, I tend to develop it with my own codebase that's grown with me over the years.
But all this takes a lot of practice, knowledge, education, research, reading, and posting questions on StackOverflow.com ;)
I would recommend symfony PHP framework since it has very good support for every feature you mentioned, and it can be easily integrated with Zend Framework - as of version 2.0 coming this year it would be integrated in the package. You can easily set symfony to handle AJAX requests so that it would be perfect transparent layer handling server side.
For me, if you look at THAT heavy AJAX, I would recommend searching for some good JavaScript framework - such as Ext.JS - that would handle all client side functionalities.
For the front-end part of your app, you might want to have a look at SproutCore ( http://www.sproutcore.com/ ).
Building a Web application with SproutCore feels more like configuring components than writing code.
There is no glue code.
On the backend all you have to do is accept and emit JSON.
Depends what sort of level you're looking at. If by 'framework' you mean something like Zend or Symphony, then to be honest all the big ones are about as good as each other. They all have strong points and weak points, but none will really meet your criteria.
But your question implies you're looking for something more than that kind of framework. Maybe you're looking for a full-blown CMS platform like Drupal, Joomla or Wordpress?
In that case, again, you need to consider your needs verses the capabilities and pitfalls of each system.
Drupal, for example, has masses of modules, is very powerful, and easy to write your own modules, but isn't object-oriented and doesn't really do MVC, so if that's your bag then you may find it hard to get on with. Wordpress is much easier to get going quickly but is less flexible once you start getting deeper into it.
But again, they all have strengths and weaknesses. If one was clearly the best, it would be an easy choice. But at the end of day perhaps it's better to have several good quality options to choose from.
Have a look at Ext JS, it is pretty good. If it is a commercial project you are doing it isn't free but not too expensive either. It also has a GWT version if you prefer that.
This is only for the front end but it is not too complicated to use any backend that can emit json.
CakePHP is pretty good
I've noticed that a PHP frameworks; Zend, Cake, and Symfony; seem to either generate JavaScript or allow it to be embedded as a string into the PHP itself. Is this a good idea? From people who've used these frameworks/libraries, what has been your experience working with the Ajax and JavaScript helpers? Has it been easy to maintain? Does it cut down on development time?
No it is a bad idea,
Generated javascript usually means that the site won't even function without it (like many asp.net sites). If you want to do more complex things or want to enhance accesibility there is no other way around than clearly seperating HTML from CSS and Javascript.
Seperating Javascript also makes your code more maintainable as you do not need to have your client side frontend developers mess with your PHP code and the other way around.
The best way to use Javascript is to first let php generate your html, then at the bottom of that page include your javascript files and use functionality like onDomReady. This also doesn't force you to use a particular library just because your framework is using that as base for its generated Javascript.
This is quite a subjective question, but personally, I wouldn't want a back-end framework to do this for me. It's better to keep a clean seperation between business logic, presentation, and client-side UI behaviours for a number of reasons:
More maintainable applications.
Easier to test individual components.
Easier collaboration. Different skill-sets can work on different areas.
Should help ensure your application does not rely on JavaScript in the end users environment.
Personally, I like to write my Javascript by hand, unobtrusively so that i just have to add an extra event to document.domReady with for example the correct parameters. That little trigger function then gets the ball rolling.
Best practice of the day:
Keep frontend-code and backend code
untangled as much as you can
I would say it depends, like anything. There is certainly some value in having "smart" server side widgets. For example, a widget that "knows" how to update itself through AJAX, or a form which can handle client side, and server side validation. The latter is an example of which it would be costly and time consuming and error prone to rewrite boring validation code in the client. It doesn't require rocket-science javascript, so as long as your framework can handle it unobtrusively, I would actually advise this route.
Additionally, framework code that will handle GUI stuff also (a la ext or something similar), is also not a bad a idea.
However, anything more complicated than that, please use Javascript itself.
I personally love writing my own Javascript so I don't really want it written for me, but I don't see it as being particularly 'dangerous' or 'harmful' to have frameworks that do it for you, as long as it is properly done. My biggest problem with them is that most of them will work as long as you want the standard behavior of a feature, but as soon as you want something a little different to meet your project's needs better it takes so much work to customize it you would have been better served to do it yourself. At least that was my experience with CakePHP's javascript automation.
My experience with the Javascript and Ajax helpers in CakePHP has been very positive.
They have allowed server-side developers to prototype and build features that otherwise would require someone with real client-side experience to do, all without having worry about the quality of the javascript code they "write" and leaving the real front-end engineers free to focus on the advanced client-side features.
It's not a good idea for the PHP to generate Javascript. The only javascript I would recommend exporting is simple JSON assignments like the following:
<script type="text/javascript"><!--
var MyNamespace.info = <?php echo json_encode($info_array) ?>
// --></script>
This is the easiest way to sanitize PHP information and let it be accessible to javascript on the client. However, anything else should be written in actual JAVASCRIPT FILES that are referenced with tags at the head of the document. The only other appearance of Javascript from server-side files, that I would say is alright, is stuff placed into "onclick" and other such attributes.
The rationale for this is that the Javascript should be written and maintained by front-end people who know Javascript, and the site should be able to work (at least partially) without javascript. There is no reason to generate spaghetti Javascript inline.
Check out my PHP framework, PHP On Pie (http://phponpie.com) for an example of how to implement this properly. It keeps the JS and PHP separate, except when exporting JSON as shown above. However it also provides conventions for easy interoperation between the client and server via AJAX.
I believe you should keep languages apart. Even though they can complement each other. That way you can pick the implementation of said language and create a mix that fits you perfect.
I think there is definitely a place for generated javascript. (1)
The number one reason for generated javascript is ease of maintenance. Any dependencies are explicitly encoded and configured from the framework (PHP, ruby, scala, python) itself. For instance if you move your assets or change the upload directory, just update the configuration and watch things Just Work.
Need client side input validation to take some load off your server? (2) Let the framework generate correct validation code derived directly from your data model for you. With generated, javascripted population your framework can serve pre-rendered, static HTML forms from the cache. This could be a huge win if your forms contain lots of selects and options.
1) Assuming that the client has decided that it's OK for the site to depend (more or less) on javascript, with all the caveats that entails. Graceful degradation may or may not be possible or desirable.
2) You need server side side validation too, but you knew that, right?