
We read:
Planet PHP
Planet MySQL
Exciting E-Commerce
E-Commerce Blog
Fischmarkt
fukami
Lars Jankowfsky
Themenblog
Thomas Bachem
Matt Asay on OpenSource
Joel on Software
Ibrahim Evsan
Hasematzel
Techcrunch
Indiskretion Ehrensache
Sichelputzer
Alexander Schwinn
Managing Tech
F-LOG-GE
trycatchfinally
About ten years ago there was a rumour. If you want to get things done, and if you want to get them done fast, go for PHP. Yes, it's been like a badly done perl ripoff with even worse object orientation and inconsistent apis, but somehow the people creating in software in PHP were able to deliver. And they were able to deliver fast, open for changes in the last 24 hours and they fixed bugs in production fast. From a software engineering professionals point of view this sounded risky, unprofessional and dangerous. This could only lead to crappy code. A proper software engineer would never use this language, and he won't ever accept changes in the last minute nor work with a customer that does not know exactly what he wants.
Dieser Blogartikel soll zeigen, wie schnell und unproblematisch es sein kann, eine einfache Applikation mit BackboneJs und Zend Framework umzusetzen. Als konkretes Beispiel wird hier eine Applikation zur Verwaltung von Adressen verwendet. Mit dieser Anwendung soll das Zusammenspiel verschiedener Komponenten wie Datenbank, Service Layer mit Zend Framework und Applikations Layer in BackboneJs veranschaulicht werden.
BackboneJs gibt als Kommunikationsinfrastruktur zum Backend REST vor. Aus diesem Grund soll in einem ersten Schritt Zend Framework so konfiguriert werden, dass es RESTful mit dem Frontend kommunizieren kann. Im nächsten Schritt wird die Applikationslogik seitens PHP umgesetzt und somit die konkrete Schnittstelle zum Frontend definiert. Aufbauend auf dieser Schnittstelle wird das Frontend umgesetzt.
Last week I had the chance to attend an Agile Developer Skills Workshop in Berlin.
The 3 day workshop is, next to a Scrum Master or PO Certification, a prerequisite for the Certified Scrum Developer, short CSD.
I was very excited about the ADS workshop and I found it an intersting approach to hold a workshop which focusses on developers rather than on the management side of scrum. Especially as in my experience all the other scrum workshops mainly concentrate on the rituals, artefacts and organisation of Scrum, without giving answers on how to develop high quality software.
JSHint ist ein JSLint Fork von Anton Kovalyov. Dieser hat zwar nicht das Standardwerk der JavaScript-Welt "JavaScript - The Good Parts" geschrieben, dennoch kritisiert er Crockford's jslint, das in dem Buch ein eigenes Kapitel bekommen hat, pointiert mit:
JSHint is a fork of Douglas Crockfords JSLint that does not tyrannize your code. It is designed to detect errors that actually break your code while skipping things that, according to Crockford, are known to contribute mistakes in projects. In other words, JSHint is a fork of JSLint for the real world. The most important difference is that JSHint is developed and supported by the JavaScript developer community and not by one very opinionated person.
A couple of weeks ago, I was attending a three-day workshop for agile developer skills. The workshop was split into five topics: Colaboration, Refactoring, Design & Architecture, Continious Integration and Test Driven Development. Especially the session about Test Driven Development was very interesting. Although I know the principles of TDD I was really impressed by the demonstration of solving a simple exercise (a coding kata) done in Java by the instructors of the workshop. It was not so much the coding in Java that was interesting for me, it was the combination of writing a test, executing the test with a shortcut from the IDE, see the test fail, write the implementation and re-start the test again within the IDE. You will say “that´s test driven development- it´s nothing new!” and you are right! But is there a way to do Test Driven Development in the same way for JavaScript? I mean writing a test, execute the tests with a shortcut from the IDE, see the test fail, implement the method and re-start the test? Yes, there is a way! So let me show you what I have done to do the same coding kata (called Fizzbuzz) with JavaScript.
Cloud technologies and services increase every day. Global players like Amazon put continuously new features to their cloud and products to provide sufficiently functionality of actually web development activities and requirements.
In fact, Amazon starts with the S3 (Simple Storages Service) to provide cloud storage space since 2006 and only a few months later EC2 (Elastic Compute Cloud) was launched a service to provide computing power to manage capacity as many as we need over time. Now, RDS (Relational Database Service) is available to get elastic database power as much as we need to cover all components that we require to implement the whole stack of current web applications.
Use that services to transform the development and of course every application in a liquid and full dynamic status. Every service increase productivity and can be used to cover architecture requirements in sufficient way. That means, use every service as long as we need and allocate capacity as many as we need in the finest way up to 100% not more, not less to reduce resources and costs.
Ok let us start to introduce each important service below to get more details and show examples what we have to do to use these services. Amazon provides a SDK especially for PHP developers to connect each service. You can download the SDK under the following URL:
http://aws.amazon.com/sdkforphp/
To start, download and install the SDK to your destination directory in your application root folder. Before we can start edit the configuration file and change the privacy settings with your AWS (Amazon Web Services) credentials (see Listing 1). To get credentials please create an AWS account on:
http://aws.amazon.com/de/ and follow the instructions.
S3 is the storages service from Amazon where we can store (Create), retrieve (Read), overwrite (Update) and remove (Delete) data. The logical structure based on buckets that contains items like files e.g. images, videos or documents or any data that we want to store. Buckets must have a unique developer-assigned key across the account each item can be contain 1 byte up to 5 terabytes.
First, to store our objects we create a bucket with the method create_bucket. All what we have to do is specify a name of the bucket “testbucket” and the region where we want to create it. In our case the region is “EU_E1” (European 1- Region). Additionally, a simple “if check” covers the return value whether the call was correct.
In the next step, we put files to the bucket and store some data to the cloud. Simply, call the create_object method to handle our request.
Listing 3 shows the PHP snippet to create a test file. Call the method with the bucket name “testbucket”, name of the file “testfile.txt” and some additional parameters in our case “body”, “acl” and “contentType” to specify the characteristic of our data.
Now we want to get back our stored data. To finalize that request we have to use the method get_object.
Listing 4 visualizes that request and shows the method call with the parameters “testbucket” that is our bucket name and the name (key) of the file “testfile.txt” where our data will be stored.
Execute our get_object.php file and receive the entire string from the cloud storage for further use.
Listing 5 covers our example and echoed the string that we have inserted a few minutes before.
To see it is very simple to communicate to our cloud storage with the SDK and execute the proper methods. If you do not know the right method take a look in the library service file where every single method is described well that enclose every required parameter and excepted return values.
EC2 is the next create cloud services that we can use to allocate computing resources for our web environment. Through defined methods from the SDK and the proper service file you can easily start an AMI (Amazon Machine Image) with an operating system that match our requirements. There are images from the market leaders like Linux and Windows systems and you can upload an own image as well whether you need a self defined system e.g. pre-installed web, db or chat server. Please go to the Amazon website:
http://aws.amazon.com/ec2/
to see which kind of images are available that fits your requirements. After we have chosen a suitable images we can start it with a method call from the SDK similar create a bucket in S3.
Listing 6 shows that method call run_instances with the parameter “ami-48aa4921” with specifies the machine images that will be loaded and some optional parameters in that case the type of the underlying hardware configuration which is specified by “m1.micro” instance - currently the smallest type with 2 processor kernels (CPUs) - and round about 613MB RAM. Check the response value with the method isOk. If everything is fine we can connect our recently started machine through a secure shell.
Listing 7 visualize a connection to the virtual machine that we have started. We need only our private key that you can download from the AWS account and the hostname of the machine that you can find on the EC2 overview simply go to the AWS website:
http://aws.amazon.com/ec2/.
After the login (see Listing 8) we see our secure shell of the machine where we can input commands like on our self administrated local systems.
Similar S3, EC2 is also pretty easy to use with some SDK commands like run_instances that helps us to integrate this service into our web application. You need only a valid AWS account (key credentials) to access the service, a machine image like “ami-48aa4921” and a proper instance type e.g. “m1.micro” with sufficient processor and memory power.
The final service that we want to cover is the RDS service the third part to complete our web environment stack. It is also pretty easy to use it with the SDK. Call only a single method to start a new RDS instance and connect to the machine.
See Listing 9 to show an example how to create a database instance. Execute simple the method create_db_instance with the parameter ‘testinstance’ the name of the instance, “5” specifies the size of the db storages in GB, “db.m1.small” clarifies the size of the underlying instance type (varies in processor and memory power), “MySQL” the type of the database system, “testuser” a user name and “testpassword” the password to connect the database. Check also with the isOk method the response value to guarantee the availability of the system.
Now we can connect to our new instantiated database through a secure shell. Input only the following known MySQL client command to connect. Specify the user name, password and the database host (see Listing 10).
After we have connected to the database server we will see the start screen where we can input commands (see Listing 11).
Check out which tables are available and execute the show databases command. Additionally, show all tables in the MySQL database with the show tables command (see Listing 12).
In this blog post we have cover common cloud services from the Amazon service. S3, EC2 and the RDS are services to extend and of course to replace current development architectures where normally dedicated machines and systems work. With the SDK it is very simple to connect all the services, request commands and response values e.g. S3 items. These proposed services cover a small overview about available services. There are much more excellent functionalities we can use to integrate.
SimpleDB is an additional database service that based on a key value store without any relation between items unlike relational database systems. Handle data in domains similar buckets in S3 and retrieve values with proper SQL statements.
Last but not least, SQS (Simple Queue Service) integrate a SOA service. Loosely coupled items communicate through defined interfaces. Add values to a queue at one application point and retrieve items on another. Works asynchronous and can be used to handle jobs that converts large data like image or video rendering. Thank you for your attention to read until the end ;-) if you have any comments please add your notes and ideas after that post.
In this article, I want to highlight some differences between the two PHP frameworks that have been the most popular ones at the time of writing.
Zend Framework (ZF) is currently a quasi-standard in many PHP companies and Symony2's popularity is constantly increasing. Symfony2 is pretty new now and many developers are thinking about if and when to make the switch from ZF to Symfony2 which is why I think we should spend time looking at the frameworks' differences.
I selected three topics that are implemented differently in these frameworks and will describe how each of them does it.
I took the setup of new projects as one category of comparison because it is an important to make this step as easy as possible for developers that are learning a new framework. In my opinion, the adoption time of a new technology somehow correlates with the easiness of starting a project with using this technology.
To set up a Zend Framework (ZF) project, download the framework's minimal package and extract it to an empty directory. You will see two new folders: bin and library. To initialize the project structure, run the included cli script in the project directory like this:
php bin/zf.php create project .
When you now go to http://<hostname>/ with your web browser, you see a blue welcome page which indicates that the installation was successful. To configure a database connection, you will have to manually edit the file application/configs/application.ini and add the following lines to the [production] environment.
After this step, you have a fully functional Zend Framework project which can be configured using different environments. The next step is to implement custom controllers, views and model classes.
Setting up a project with Symfony2 is pretty easy. You start by downloading a copy of the Symfony2 Standard Edition, extract it to an empty directory and can start to configure your project. However your system has to fulfill some requirements which can be checked by running the script check.php in the app folder (just run php check.php in the command line). When all requirements are fulfilled (and you created a virtual host with its DocumentRoot pointing to the project's web directory), you can navigate your browser to http://<hostname>/config.php and configure the project via a fancy web UI. After checking all requirements again, the Symfony2 sandbox asks you to enter your database configuration which will be written to a configuration file afterwards. The sandbox also includes a sample page where you can see that everything is up and running: http://<hostname>/app_dev.php/demo/hello/World.
To use the sandbox for a real project, I suggest removing the demo pages visited before. Remove the line registering the demo bundle from the file app/AppKernel.php and the demo bundle's router configuration from app/config/routing_dev.yml. Last you can delete the bundle's folder src/Acme.
To be able to define different database connection parameters for the various environments (as with ZF), copy the file app/config/parameters.ini to (this example uses the environment dev, of course you can to the same for any other environment!) app/config/parameters_dev.ini and adjust the other config files accordingly:
The initialization process of a new project is very easy with both of the compared frameworks. One benefit of ZF is that it eases the differentiation between different environments when it comes to configuration - all configuration options can appear in one file in multiple configuration environments that inherit default values from other environments in a defined hierarchy. With Symfony2 you have to create a separate config file and include it into your project's configuration as described above.
Symfony2 on the other hand comes with a nice example bundle that contains a sample configuration, controllers, views and even a very basic authentication infrastructure which can be used as template for your own bundles. Of course, the initial project structure of a ZF project has some default controllers as well, but they don't show you how to configure e.g. security.
The Model View Controller (MVC) pattern is one of the basic structural patterns used in application development. It basically applies the concept of Separation of Concerns to the structure of applications in a way that separates business logic (Model), the rendering of user interfaces (View) and user interaction handling (Controller) from each other. Most object-oriented frameworks provide scaffolding for MVC implementations - so do Zend Framework and Symfony2. Let's have a look how MVC is applied in both cases.
In a classical project infrastructure, ZF projects use controllers that contain multiple actions. Every HTTP request sent to the application is being handled by one (in some cases also multiple) controller's action and most of the times, one action is mapped to one view (This is of course due to the fact that in the WWW, user interaction required a reload of the complete web page - at least for a long time. Nowadays, many web pages (so-called single-page- or Ajax-applications) do not need reloads to change the displayed data and views.).
Views are implemented as templates that contain HTML markup code with inlined PHP snippets. To pass data to a view, the controller has to set this data as a member variable on its view. In the view script you can later access this data by using $this->variable.
In web development, the term Model Class is often mistaken for Persistent Entity Class. Model objects do not only represent data stored in a database, but should also contain all the business logic of your applications. I have seen many applications that do all the logic inside of controller classes and only use models to have an abstraction over the database.
ZF cannot force you to have model classes for all your logic and it also does not try to do so. What it does is giving you a utility for implementing your database abstraction: Zend_Db.
Zend_Db is a component of ZF that provides several APIs to access databases and have an abstraction for persistent records. In times of Doctrine 2, I would suggest neither to learn the use of Zend_Db nor to implement a custom database abstraction. Doctrine 2 can be integrated into ZF projects very easily as you can look up in my article from December 6th and it probably will do a better and more efficient job than a custom solution, too.
Besides my own affinity for Doctrine 2, there are several impartial reasons for not using Zend_Db. In my opinion, the biggest disadvantage is that to add custom logic to your entity objects, you end up writing subclasses of Zend_Db_Table_Row_Abstract. This is a thing I really don't like. Dealing with business logic entities that map the application domain should not require you to think about persistence at all (espacially not to subclass a certain class just to make your objects persistable)! You might say "but this is Active Record!" now. Yes, you are right - Zend_Db_Table_Row implements the Active Record pattern. But: Active Record has not heard a word about separation of concerns. Hence it is just a collection of bad OO code.
Using Symfony2, you split your application into one or more bundles. Each bundle has its own controller and model classes, configuration and views. Similar to ZF's modules, controllers and the related model classes are grouped into bundles together with views used by these controllers. This way it is easy to reuse code from other projects by just copying the required bundle.
One difference regarding controllers is the definition of the term controller in Symfony2: A controller is a PHP function that houses all the logic necessary to return a Response object that represents a particular page. (from the Symfony2 Glossary)
Thus a controller does not have to be a full-blown class with differnt actions but only a function handling a specific type of requests. Inside your controller functions, you have to create and return a Response object. How you do this is up to you. There are cases in which you use a templating language (Symfony2 comes with Twig which might take some getting used to it but is very powerful eventually) for rendering HTML but you can always just serialize some data to provide it via a REST API, too.
As with ZF, views are implemented using templates in Symfony2. To use a template, you call the render method in your controller and pass all data required to replace the placeholders in the template. The render method will create a Response object for you which can be returned by your action directly.
When it comes to model classes, there are no restrictions in Symfony2. It is recommended to use Doctrine 2 (which also is included in the distribution package of Symfony2) as your applications' ORM system. Doctrine 2 is already integrated into Symfony2 which makes the configuration really easy. If you follwed the steps in the Project Setup section above, you even configured Doctrine 2 already!
Real MVC is hard to implement the correct way. This is espacially true when it comes to web applications. One major component missing to a real MVC implementation in classic web applications is the synchronity of model and view (which is normally done using an Observer Pattern). Using PHP, HTTP and HTML, you normally render a web page once and the user has to reload the page to see whether there have been changes on the displayed data. By using Ajax in combination with XMPP or any other RealTime-Web implementation, you can imitate this mechanisms. Doing so, you will end up with two MVC implementations: One on the server side and one inside the browser.
After the comparison of ZF and Symfony2 regarding MVC, you cannot say that one does a better job at it. Both frameworks help you separating your code, but the real work has still to be done by the developer using the framework.
Dependency Injection (DI) has been a buzzword in the last few years (again, PHP adopted this technique some years after the Java world did) and still is, so we will have a look on how the ZF and Symfony2 are handling objects dependent on each other.
There is no real DI mechanism in Zend Framework by now. It comes however with multiple components that do something similar to dependency injection. We will have a short look at two of them: The Zend_Registry and Zend_Application_Resources.
The Zend_Registry is a container for services that should be available globally in an application. You can access the registry statically, store values in it and access them somewhere else. This approach can be seen as an implementation of the Service Locator pattern. If you have external dependencies in your controller and/or model classes, you can just read them from the registry every time you need them. Two downsides of the Zend_Registry is that it does support lazy initialization of dependencies and that it cannot provide non-shared objects (to achive this, you can always put factory objects into the registry!).
Another mechanism related to DI is provided by the package Zend_Application_Resource. Resources are dependencies configured at the time the Zend_Application is being bootstrapped. You can access all application resources in your controller by calling $this->getFrontController()->getParam('bootstrap')->getResource($resourceName).
Symfony2 is shipped with a dependency injection component which can be used as a standalone package, too. Every Symfony2 project uses it since the framework itself makes use of it in its core components. Besides that, you can benefit from DI in your own bundles as well. Symfony2's dependency injection container is configured via extensions that specify their services and the objects required to build these services. Imagine for example a user management bundle which sends welcome emails to new users. Therefore there might be a service called Acme\UserBundle\WelcomeMailer which requires a mailer object to perform its work. In this case you would create an extension for the DI container and define your service like this:
To access the welcome mailer in a controller, you just call $this->get('welcome.mailer.acme.user') and receive a lazily created instance of the class Acme\UserBundle\WelcomeMailer. Objects defined as arguments of a service will be provided to the service's constructor as parameters. If you want to use the welcome mailer somewhere else, just define it as an argument of this other class and you will have an instance of the service injected.
As we have seen, the winner of this discipline is Symfony2. It enables developers to define their objects' dependencies explicitely in a very flexible way. Zend Framework on the other side provides mechanisms that ease the distribution of service objects, but does not implement lazi dependency initialization or and injection of dependencies at all.
These were just a few differences between Symfony2 and Zend Framework 1. If you got interested in Symfony2 by this article, you should have a look at the framework's website and read the Symfony2 bible.
All in all I prefer Symfony2 for new projects because it makes me write better OO code. Zend Framework is fine, too, but it looks kind of outdated to me. Anyways I'm also excited to see how ZF 2 (currently beta) works and will spend some time comparing it to Symfony2 as well - maybe in another blog article.
In this article I’d like to compare Backbone, Knockout and JavaScriptMVC under the following points:
So let’s start with Backbone. The documentation of Backbone is available under the following link. The complete documentation is written on a single page. Its very easy to search for topics you are interested in. After a short introduction you’ll find one or more code examples for each topic. These examples are nicely short and well described. Some of them are testable right away. Everything is easy to understand. The only thing missing is a short demonstration how all parts of Backbone work together. But if you search for Backbone snippets on Google you will find lots of examples because it has a wide acceptance among frontend developers.
Backbone is lightweight with just 4.6KB (compressed and Gzipped). It comes along with models, views and controllers to separate the contexts of your application. The only hard dependency of Backbone is underscore.js, a library full of useful utilities and JavaScript functions. For DOM manipulation you are advised to include either jQuery (>1.4.2) or Zepto. To use Backbone just download the backbone.js and underscore.js files and include them in your application. If you include jQuery as well you have a very powerful set to implement complex applications. One thing I experienced myself and read a lot about it on the Internet is the error handling of Backbone. If something went wrong (i. e. you forgot to include underscore.js) a JavaScript error occurs with a message that has nothing to do with the real error. Compared to other implemented MVC patterns, the Backbone.View is a kind of controller. It dispatches events that originate from the UI, with the HTML template serving as the true view. They called it “view” because it represents a logical chunk of UI, responsible for the contents of a single DOM element. Backbone’s main structure exists of Backbone.Model, Backbone.View, Backbone.Collection and Backbone.Router.
Backbone.Model It wraps a row of data into business logic. The backbone.Model provides a basic set of functionality for managing changes. An easy model could look like this:
In this piece of code we extend Backbone.Model with our domain-specific method “promptName”. The “this.set” function sets a hash of attributes on the model and triggers a “change” event. It’s one of the base functions in Backbone.Model and really handy for updating your view if something changed. You easily bind a “change" listener to the instance of your model to observe any changes. Within the callback of your binding you can place your view changes or whatever you like. Let’s have a look at an example.
Backbone.View The general idea of Backbone.View is to organize the interface to logical views. Backed by models each view can be updated independently when the model changes. As well as the model, the view comes along with basic methods like (initialize, render, remove, ...).
In the example we overwrite the function “initialize" which is the constructor of the view class. It is always invoked if an instance is created. Within this constructor we bind the “change:name” listener to the instance of the PersonModel and bind a callback. This callback would be invoked if the name in the model changes. If this happens the new name would be rendered between the body tags.
Backbone.Collection Backbone.Collections are ordered sets of models. Like the model you can bind “change” events as well, so the collection get notified if any model changes. It provides a full suite of underscore.js methods to improve the collection handling.
Backbone.Router Backbone.Router maps URLs to functions and connects them to actions and events. For history routing it uses the history API. So you can use standard URLs like “/page” instead of “#page”. Backbone provides a graceful fallback for browsers without support of the history API.
To compare the complexity of each library I built a simple wish list application. This application should be able to add wishes, remove them and count all added wishes. An implementation with Backbone could look like this:
Backbone is very flexible in the way you want to use it. The view as kind of controller keeps your code small and avoids useless overhead (in JavaScript). Backbone is really easy to understand and with the functions of underscore.js it’s very powerful as well. To use a proper template engine is always a good idea and eases the developing process. Backbone is well known, so you find lots of code examples or solutions for problems in the Internet. Initially you have to write more code as you probably would write normally. But this code is easy to maintain and extend. If you have the base structure of your application it’s much faster to work with Backbone. I am using Backbone for a while now and I absolutely recommend it. It’s best used in medium to large projects. For small projects it’s probably sufficient to “just” use a library like jQuery.
The website of Knockout is well organized and the key concepts are visible at first sight. It teasers “Declarative Bindings”, “Automatic UI Refresh”, “Dependency Tracking” and “Templating”. The documentation is well written and easy to read. It’s pretty short and lots of code examples are provided. The best way to get through the documentation is to read and try the examples. With only reading the documentation it could be difficult to understand Knockout. Have a look at the impressive 20-minute demo video from Steve Sanderson. It gives you a good roundup of knockout. After reading and testing a little while you are able to start programming applications. Awesome.
Knockout is a JavaScript library and not a framework like Backbone or JavaScriptMVC. It doesn’t provide classes to extend or inherit from. Anyway it helps to create rich user interfaces with an underlaying data model. It has features like “Observables and dependency tracking” which automatically updates the UI whenever your data model changes. “Declarative bindings” to connect parts of your UI to your data model. With “Templating” you can build complex, dynamic UIs with nested templates. Knockout is written in pure JavaScript and works with any server or client-side technology. It’s light weight as well with 29KB (minified). Like Backbone you just have to download knockout.js and include it in your application.
Knockout is related to the Model-View-View-Model (MVVM) design pattern to build rich user interfaces. The “model” is independent of any UI and stores the data of your application. The “view model” is the representation layer of the data and operates on a UI. Its important to understand that the view model is not the UI itself. It’s a pure JavaScript object without knowledge of any HTML. It just holds the unsaved data the user is currently working with. The view represents the state of the view model. It displays information from the view model, delegates commands (i.e. click events) to the view model and updates itself if the state of the view model changes. A short example will demonstrate that.
In the view (HTML) the “text” binding clause will associate the DOM element with our view model parameter “personName”. After Knockout is activated via “ko.applyBindings(viewModel)” the view reads the content of this parameter and renders the text between the span tags. So the result of executing this code looks like:
You’ve seen how to create a basic view model and how to display its property via binding. But more interesting is how to update the view automatically. It’s pretty simple and achieved with so called observables. Just change the previous code into this:
That’s it. Try it in the JavaScript console of your browser and you will see the view being updated automatically.
Now I'd like to demonstrate Knockout with the same wish list example like I used in Backbone. So it could look like this:
It’s awesome to see the same example application as written in backbone earlier with much less JavaScript code. But we have to think about readable and understandable code and how hard it is to explain the code to new developers. I think the declarative binding in the HTML is probably hard to read and understand because you don’t really know where it belongs to. Some developers just won’t like mixing JavaScript and HTML together. If you bring your knockout code into good shape, use namespaces in your HTML bindings and create conventions how to use knockout in your application it could be easier to understand and maintain. Because knockout is “just" a library and not a framework you don’t have the benefits of classes, inheritance, fixtures and so on. You have to implement that all by yourself. For huge projects you have to look closer into Knockout to check performance issues. I think knockoutJS is absolutely worth a try. It’s a good decision if you have to implement rich user interfaces. If you organize your code well, it’s possible to build bigger applications. But I think the best use case is in small to medium projects.
The documentation on the website of JavaScriptMVC (JMVC) seems to be complicated and could be overstraining. It’s not that well structured like the previous ones and it is not really clear where to start. The installation process looks really complicated and could keep some developers from using JMVC. You have to download Java JRE and the full download size of JMVC with 27MB will probably surprising you. I can assure you it’s not that bad as it seems. A little bit more description why we have to do all these things could help to understand it easier. Anyway the whole installation process runs without problems and it works like described.
JavaScriptMVC is a really powerful framework. It consists of standalone components like StealJS, FuncUnit, jQueryMX and DocumentJS which are well tested and loved by many developers. This powerful stack provides everything you need to build well organized, tested and documented applications. Let’s have a look how everything fits together.
jQueryMX With this component you have a collection of useful jQuery libraries to implement and organize large-scaled applications. It puts the Model-View-Controller pattern in JavaScript. It comes along with other useful things like an observable system, a DOM extension and special events as well as a browser history routing.
StealJS This awesome component is a “code manager” to keep your code beautiful and well organized. It’s a collection of command line and browser based utilities to do things like:
To generate an application simply execute the following command:
This will generate your application structure with everything you need.
The scaffold generator helps you to create a model quickly. It creates fixtures to simulate a service, widgets with basic actions and all dependencies are automatically included. You can just start editing the widgets for your purpose. All you have to do is to execute the following command:
There are lots of awesome commands to simplify the developing process.
FuncUnit FuncUnit is a web application testing framework. It provides automated unit and functional testing. You can run these tests practically on every browser or system. You can start your tests easily within the browser with:
or run your tests in Envjs with the command:
DocumentJS This component generates a documentation application of your application. The only thing you have to do is to run the following command:
JMVC is so modular you can easily install all the components or just the ones you need.
I like JMVC! It’s easy to structure your code, generate everything you like, check your code all the time and with a single command your application is ready to go. Of course it’s a heavy framework and for the shown example absolutely oversized. It’s not that easy to understand like the previous ones but definitive worth to try it anyway. We use JavaScriptMVC for big projects where unit tests and an API documentations are essential. The framework has proven its power over a “long” time so you will find lots of code examples and solutions for your problems. I would recommend JMVC for big projects or projects with the need of high code quality and well documented API.
The following code demonstrates the wish list example implemented with the help of JavaScriptMVC. I put the code into one single file to improve readability here.
In summery I would say Backbone, Knockout and JavaScriptMVC are all pretty good libraries. I would prefer KnockoutJS for smaller projects to create user interfaces in a short amount of time. For bigger projects I would use BackboneJS. It's easy to implement and well organized. I would choose JavaScriptMVC for large projects where high quality and long term support is expected.
Im IEEE-Standard 1061 sind Softwaremetriken wie folgt beschrieben:
“Eine Softwaremetrik ist eine Funktion, die eine Software-Einheit in einen Zahlenwert abbildet. Dieser berechnete Wert ist interpretierbar als Erfüllungsgrad einer Qualitätseigenschaft der Software-Einheit.”
Jetzt stellt sich die Frage: Wozu benötigen wir Softwaremetriken überhaupt? Diese Frage lässt sich relativ leicht beantworten: Metriken werden benötigt, um Software und deren Qualität messbar zu machen. Hat man nun diese konkreten Werte vorliegen, kann man die Produkte verschiedener Anbieter anhand bestimmter Kriterien miteinander vergleichen, um eine Kaufentscheidung zu erleichtern. Ein weiterer Anwendungsfall für Softwaremetriken ist, dass sich mit ihnen der aktuelle Stand eines Projekts dokumentieren lässt. Werden Metriken über einen längeren Zeitraum gesammelt, erlauben sie Rückschlüsse auf die Entwicklung in einem Team und einem Projekt.
Das Thema Softwaremetriken ist nicht wirklich neu und auch nicht sonderlich spektakulär. Softwaremetriken sind seit vielen Jahren der Gegenstand von Forschung an verschiedensten Universitäten und damit sowohl praktisch als auch theoretisch sehr gut dokumentiert. Die Probleme treten allerdings schon auf, wenn man den ersten Schritt von der Theorie in die Praxis wagt: Für welche Programmiersprachen stehen welche Metriken zur Verfügung?
Etwas Recherche im Internet zeigt, dass es für Java, C und C++ Werkzeuge zur Erfassung von Softwaremetriken wie Sand am Meer gibt. Diese Tatsache ist allerdings auch nicht weiter verwunderlich, da die Forschungsarbeiten in erster Linie auf diesen Sprachen aufbauen und auch die Notwendigkeit eines lückenlosen Qualitätsmonitorings in diesen Bereichen in großem Maß vorhanden ist.
In unserer täglichen Arbeit sind Metriken im PHP Umfeld relevant. Auch hier existiert ein Satz an Werkzeugen, der die wichtigsten Metriken erfasst. Eine Anforderung an Messwerkzeuge ist, dass diese für den Entwickler keinen unnötigen Aufwand verursachen und die Metriken automatisiert erzeugt werden. Zu diesem Zweck generieren Werkzeuge wie beispielsweise phpunit, phpmd und phpcs Ausgaben in xml und lassen sich damit in eine Continuous Integration Plattform wie Jenkins integrieren. Ist dies erreicht, werden die Werkzeuge bei jedem Commit ins Versionskontrollsystem ausgeführt und es stehen allen am Projekt Beteiligten detaillierte Informationen über die Qualität des Quellcodes zur Verfügung.
Da Javascript zunehmend an Bedeutung in der Entwicklung von Webapplikationen gewinnt, besteht auch hier Bedarf an Qualitätssicherung. Um eine möglichst hohe Qualität im Bereich Javascript durchzusetzen, müssen einige Voraussetzungen erfüllt sein. Das Wichtigste, was hier zu nennen wäre, ist die strikte Trennung von Darstellung und Logik. In der Praxis bedeutet dies: HTML stellt die Struktur der Seite und deren logischen Aufbau dar, CSS wird für die Darstellung und das Layouting verwendet und Javascript beinhaltet die Frontendlogik. Diese drei Bereiche sollten strikt getrennt und in jeweils eigenen Dateien abgelegt werden. Durch dieses Vorgehen können die einzelnen Teilaspekte unabhängig voneinander betrachtet werden.
Die einfachste Kategorie von Metriken, die in Javascript zur Verfügung stehen, sind die sogenannten LOC-Metriken (Lines of Code). Bei diesen Metriken werden die Zeilen des Quellcodes gezählt. Ein Tool, mit dem diese Metriken erfasst werden können, ist CLOC. Hier wird neben der reinen Anzahl an Zeilen unterschieden zwischen eigentlichen Codezeilen, Kommentaren und Leerzeilen und auf wie viele Dateien diese verteilt sind.
In Verbindung mit Konventionen, die für das Projekt vereinbart werden, wie beispielsweise die maximale Zeilenlänge oder höchstens ein Statement pro Zeile, machen LOC Metriken Sinn.
Einen weiteren Satz von Werkzeugen bilden die Unittest-Frameworks. Unittests werden verwendet, um Bausteine von Software, die sogenannten Units, zu prüfen. Voraussetzung, um Unittests zu erstellen, ist eine sinnvolle objektorientierte Architektur der Anwendung.
Die erste Metrik, die für Unittests zur Verfügung steht, ist die Anzahl der Tests. Diese kann von einigen wenigen Tests bis hin zu mehreren Tausenden reichen. Die Zahl der Tests für sich gesehen ist allerdings kein Qualitätsmerkmal. Pro Unit, die getestet wird, sollten mehrere Tests existieren. Die minimale Anforderung ist ein Test für den positiven Fall und einer für den Fehlerfall. Je nach Logik in der Einheit, kann es sein, dass mehrere Fälle abgetestet werden müssen, um sicherzustellen, dass die gewünschte Funktionalität reibungslos abläuft.
Als Framework für die Unittests kann beispielsweise qunit verwendet werden. Ursprünglich entstand dieses Werkzeug für die Qualitätssicherung von jquery, kann allerdings unabhängig davon verwendet werden. Zur Automatisierung und Integration in eine Continuous Integration Plattform wie Jenkins wird jsTestDriver verwendet. Für dieses Tool existiert ein Adapter, der bestehende qunit Tests in jsTestDriver lauffähig macht.
Die Qualität von Unittests lässt sich kaum messen. Das einzige Mittel, das eine Aussage über die Qualität der Tests erlaubt, ist die Testabdeckung. Die Testabdeckung beschreibt, wie viel des Quellcodes wirklich durch die Tests abgedeckt ist, also, ob alle if-Statements berücksichtig sind und ob sämtliche Cases in Switch-Statements geprüft werden. Eine Testabdeckung von 100% bedeutet, dass sämtlicher Quellcode durch die Unittests einmal ausgeführt wurde. Aber auch eine hundertprozentige Testabdeckung stellt nicht sicher, dass sämtliche Kombinationen der Applikationslogik geprüft werden. Hier ist es notwendig, dass sich die Entwickler Gedanken über die auftretenden Fälle machen, Testpläne erstellen und diese gezielt durch Unittests absichern.
Jetzt kommen wir zu einem Werkzeug, das in keinem Javascript-Projekt fehlen darf: jslint. Dieses Programm durchsucht den Quellcode nach möglichen Problemen. Hierunter fallen sowohl die korrekte Einrückung des Quellcodes, als auch ein Komma zu viel am Ende einer Arraydefinition oder Zuweisungen in if-Statements statt einem logischen Operator.
Jslint ist sowohl über ein Webformular als auch offline verfügbar. Da die Implementierung vollständig in Javascript erfolgte, ist es problemlos möglich, dieses Tool auf jedem Rechner über die Kommandozeile auszuführen, man benötigt lediglich eine Javascript Engine.
Im alltäglichen Gebraucht hat es sich als praktisch erwiesen, jslint als Pre-Commit Hook einzubinden und jeden Commit abzuweisen, der fehlerhaftes Javascript beinhaltet. Mit jslint4java generiert jslint xml-Ausgaben und kann damit auch in eine Continuous Integration Plattform wie Jenkins integriert werden.
Einen Schritt weiter geht das Javascript Plugin für die Qualitätsmanagement Plattform Sonar. Mit diesem Plugin werden neben den Prüfungen von jslint auch Codeduplikation und Komplexität gemessen.
Doppelter Code ist in vielen Projekten ein Problem, da aus Gründen der Zeitersparnis einfach Code kopiert wird und nicht sauber ausgelagert und von verschiedenen Stellen referenziert wird. Die Copy-Paste-Detection vergleicht allerdings nicht Codeblöcke Wort für Wort miteinander, sondern auf Ebene des Abstract Syntax Trees. Es nützt also nichts, einfach nur Variablen umzubennen oder Whitespaces einzufügen.
Zur Bewertung der Komplexität benutzt das Sonar Javascript Plugin die zyklomatische Komplexität des Quellcodes. Diese Metrik wird beeinflusst durch die Anzahl der Anweisungen und die Kontrollflüsse zwischen diesen. Weist Quellcode eine zu hohe Komplexität auf, ist er schwer zu lesen. Aus dieser Tatsache folgt ein erhöhter Wartungsaufwand und eine länger andauernde Einarbeitungsphase.
Zusammenfassend lässt sich sagen, dass die Qualitätssicherung im Bereich Javascript momentan noch in den Kinderschuhen steckt. Allerdings ist hier eine rasante Entwicklung zu beobachten. Vor allem im Bereich der Continuous Integration und Continuous Inspection ist eine erfreuliche Tendenz festzustellen. Immer mehr Werkzeuge lassen sich in Plattformen integrieren und ermöglichen so die regelmäßige Prüfung von Javascript Quellcode in einem Projekt.
Allgemein lässt sich festhalten, dass eine Metrik für sich alleine gesehen in den seltensten Fällen wirklich aussagekräftig ist. Kombinationen verschiedener Metriken oder Metrikgruppen hingegen erlauben Rückschlüsse auf die Qualität der Applikation.
Hier ein kurzes Beispiel, um diesen Sachverhalt zu verdeutlichen: Nimmt man eine Funktion, kann man über die LOC-Metrik herausfinden, aus wie vielen Zeilen diese Funktion besteht. Dieser Wert an sich erlaubt kaum eine Aussage, außer, dass eine große Anzahl von Zeilen nicht erstrebenswert ist, da sich diese Funktion dann tendenziell um mehr als eine Sache kümmert. Zieht man die zyklomatische Komplexität zu Rate, kann man schon qualifiziertere Aussagen treffen. Eine umfangreiche Funktion mit einer hohen Komplexität stellt ein Problem dar und sollte in kleinere Einheiten unterteilt werden; eine lange Funktion mit geringer Komplexität deutet auf eine prozedurale Funktion hin, die ebenfalls verbesserungswürdig ist. Sinnvoll sind demnach relativ kurze Funktionen mit moderater Komplexität.
Neben dem reinen Qualitätsaspekt kann durch Metriken auch die Performance des gesamten Teams oder einzelner Entwickler gemessen werden. Hier beginnt die Messung schon bei der Anzahl an Commits oder Lines of Code, die ein Entwickler erstellt. Auch hier gilt, jede Metrik kritisch zu hinterfragen. Interessanter sind dann Kombinationen wie beispielsweise die Anzahl der Zeilen pro Commit. Commits mit einer großen Anzahl von Zeilen sind meist problematisch, da sie dem Prinzip atomarer Commits widersprechen.
Die Metriken eines Projekts sollten allen am Projekt Beteiligten zur Verfügung stehen. Nur durch einen offenen Umgang lassen sich die Vorteile der Softwaremessung ausnutzen. Stehen dem Team alle Informationen über die Qualitätsaspekte der erstellten Software zur Verfügung, können die einzelnen Entwickler gezielt an ihren Schwächen arbeiten und das Projekt gemeinsam stabilisieren und den maximalen Nutzen aus ihren Fähigkeiten ziehen.
The first and even most simple modification of HTML5 compare to HTML 4.01 or XHTML 1.0 is the document type, which changed from
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
to
<!DOCTYPE html>
As
you can see immediately the version number is missing. The WHAT working
group even calls the HTML5 specification now „HTML living standard“ and
there are updates in the specification almost every week. This
shouldn‘t be a problem for anyone because all modern browser like
Firefox, Chrome, Safari, Opera and even Internet Explorer 10 are using
their HTML5 rendering engine if the HTML5 document type is parsed.
Another
goal during the HTML5 draft was a cleanup and removal of obsolete and
bad defined elements in HTML 4.01 and XHTML 1.0. HTML5 should have been
much more simpler and all redundant elements should be removed. Tags
like <acronym>, <applet>, <dir>, <frame> and
<frameset> are not part of the spec anymore. As you can see with
the removal of the last two elements it‘s not possible to build frame
based web pages with HTML5. HTML5 also requires to use Cascading Style
Sheets (CSS) for the representation of web pages, all elements and
attributes for styling content were also removed. This removal includes
attributes like plaintext, isindex, align, alink, vlink and HTML tags
like <basefont>, <big>, <center>, <font>,
<s>, <strike>, <tt>, <u>.
There are a lot of small improvements to
solve daily web development problems. Embedded images now have a border
with 0 pixels instead an ugly blue border by default and the
<script> tag now assumes to have JavaScript included. If you add
links or images to your webpage, please use the „id“ attribute instead
„name“ because it‘s much easier for DOM manipulations. One really great
improvement is the character set declaration. Instead of adding
<meta http-equiv=“Content-Type“ content=“text/html;charset=UTF-8“>
you only need this:
<meta charset=“UTF-8“>
And, please only use UTF-8, nothing else.
A
lot of stuff was added to the HTML specification which everyone used
but never was part of the standard. HTML5 now officially features the
<iframe> element and the <embed> tag for embedding Plugins
like our beloved Flash.
For many people the new HTML5
tags like <audio> and <video> are the most visible change
looking deeper into HTML source code. With the new <section>
element it‘s now possible to group section within a web page. It‘s not
for design definition, only for semantic structures. For design proposes
you should still use the <div> element like you do today. To mark
content inside a section, HTML5 introduces the <article> element.
For example, you can use this new tag for board postings in a forum,
for blog postings, for user comments in your content management system
or even a whole article in a online magazine. In these parts of the page
you can add side content boxes with the <aside> element. If you
e.g. want to add a skyscraper ad on the left side, put it into an
<aside> tag.
The navigation should be marked with the
<nav> element and the navigation items should be listed as an
unordered list inside the root element. If you have to group headers
like <h1> to <h6> you can now use the <hgroup> tag. A
group of headers are part of a section of a document according to the
HTML5 standard. The document header and footer have to own tags which
are - quite easy to guess - <header> and <footer>. A HTML5
document can consist of multiple headers, for example at the beginning
of a document or to group a header for an introduction and a header:
<header>
<p>Welcom to</p>
<h1>Mayflower Blog</h1>
</header>
The
<footer> element can be used multiple times, too. You can use it
for example to mark the end of a section or usally to mark the end of
the HTML document. This is the area to add relevant links or copyright
hints, the contact address for the author should be added by using the
<address> tag.
It‘s also quite easy to migrate the current structures of your web page to HTML5. For example it would be in most cases just a
<div id="footer">This is the end.</div>
converted to
<footer>This is the end.</footer>
This
blog post is just a very short overview what you can do with HTML5, I
didn‘t mentioned the possibilities of Web Workers, Web Sockets, Canvas,
SVG or Web Storage. But you can test a lot of things now and you should
do it. The world will move to HTML5, at the end of 2012 more than one
billion HTML5 capable smartphones and Microsofts Windows 8 will wait for
your HTML5 applications.
Dass Firebug in JavaScript programmiert wurde dürfte den meisten bekannt sein. Das gleiche gilt für den WebInspector von WebKit, wie er in Safari oder Google Chrome zu finden ist. Es dürfte also nicht wundern, dass für mobile Geräte mit Weinre von Patrick Mueller bereits 2010 eine Portierung des WebInspectors geschaffen wurde, die über eine JS-Include auf der im Website-Header im Mobilen Browser Remote Debugging Funktionalität zur Verfügung stellt. Somit kann bequem über dem Desktop eine Mobile Webseite debugged werden. Weinre läuft heute als PhoneGap Projekt, ist sozusagen Standard und ist natürlich auf GitHub zu finden.
Das Ganze hat aber leider eben leider Grenzen, was Features wie Breakpoints, Backtraces und Profiling angeht, d.h. genau die nützlichen Features, die normalerweis unter dem “Script”-Tab im Debugger-Panel zu finden sind.
Der nächste konsequente Schritt war also, den Debugger direkt in den Browser Runtime zu heben und eine Remote API anzubieten bzw. eine Verbindung zu dem ohnehin schon existierenden V8 DebuggerProtocol zu schaffen, dass sich allerdings nur auf JavaScript Debugging beschränkt. Das Gesamtpaket nennt sich dann WebKit Remote Debugging Protocol. Währenddessen arbeitete Google auch am ChromeDevToolsProtocol was aber mittlerweile deprecated ist.
Seit Frühjahr diesen Jahres bietet nun WebKit sein Remote Debugging Feature an, welcher praktisch alle bekannten WebInspector Features unterstützt - dazu zählen:
Das Feature kann bereits seit einigen Chrome Versionen getestet werden. Eine aktuelle Chrome Version bevorzugt kann eine Debugger-Instanz mit chrome --remote-debugging-port=9222 gestartet wird.
Sodann ist eine zweite Browserinstanz für den Remote Web Inspector nötig - diese muss jedoch Ihr eigenes Nutzerprofil verwenden, um Probleme zu vermeiden: chrome --user-data-dir=<existierendes Verzeichnis>
Mit Navigation auf http://localhost:9222 im zweiten Browserfenster findet sich nun eine Thumbnail-Übersicht der geöffneten Tabs des zu debuggenden Browsers. Ein weiterer Klick auf das ein Thumbnail lädt nun den Debugger auf die komplette Seite, mit dem wie gewohnt gearbeitet werden kann.

Somit kann zusammenfassend folgendes zur Funktionsweise gesagt werden:
In iPhone oder Android-WebKits sucht man den Debugger derzeit noch vergebens (about:debug), auch wenn es bereits einige ROMs für Android mit Web Inspector Support gibt. Blackberrys Playbook hingegen besitzt schon entsprechende WebKit Funktionalität.
Der Debugger bietet für den Browser eine vereinfachte, aber noch experimentelle JavaScript API, die z.B. auch durch Chrome Extensions angesprochen werden kann. Nach Google’s Vorstellungen sollen damit auch WebIDEs wie Cloud9 zum bereits integrierten JavaScript Debugger (lib-v8debug) einen vollwertigen “WebInspector” erhalten.
Opera demonstrierte bereits 2008 mit DragonFly und Scope einen funktionierenden Remote Debugger, mit dem es möglich ist sich an an einen Opera Mobile oder auch Desktop Opera via TCP-Port ranzuhängen und nicht nur JavaScript zu debuggen. Nachteil an der ganzen Sache: Im Mobile Web dominiert derzeit WebKit.

Ein ähnliches Projekt existiert seit Anfang diesen Jahres mit Firebug Crossfire, was ähnliche Möglichkeiten bieten soll. Zudem unterstützen die JavaScript Development Tools (JSDT) für Eclipse bereits Crossfire. Derzeit befindet sich das Projekt jedoch noch in der Alpha-Phase, aber darf bereits getestet werden.
Für den, der nodejs debuggen muss, gibt es mit dem NodeInspector eine schicke Lösung, mit der es möglich ist, dies bequem im Browser zu erledigen. NodeInspector ist wie ebenfalls wie Weinre eine Adaption von WebInspector.
Für JavaScript Debugging in der IDE, d.h. bequem Breakpoints in den Quelldateien des geöffneten Projekts setzen, haben wir zum einen die ChromeDevTools als Eclipse-Plugin. Zum anderen hat IntelliJ mit IDEA 10.5 und PHPStorm 3 das V8 DebuggerProtocol bereits implementiert.

Eine weitere einfache JavaScript-Konsole stellt z.B. JSConsole bereit, dass zum Debuggen von iPhone oder Android-Mobile Apps benutzt werden kann.



















