Information on i Phone application development

January 27th, 2012

CEO of apple blessed the world with his development in technology called ‘i Phone'. It is a smart phone equipped with multimedia and internet services. The first i Phone hit the market in 2007 now 5th generation i Phones are available in the market.

Go to Source

24 Extremely Useful Ruby Gems for Web Development

January 27th, 2012

One of the nicer things about developing on the Ruby platform is the sheer amount of meticulously categorized, highly reusable code wrapped up as aptly named ‘gems’.

I’m sure you’ve heard of popular frameworks like Sinatra or the super popular Rails but you’re missing an entire spectrum of gems that handle issues at a much lower level. Start using these and watch your productivity shoot through the roof!


A Quick Note

I’m well aware that some of the gems listed here have Rails, or parts of Rails, as a dependency. That doesn’t mean that they are any less useful or need to be sneered at.


CarrierWave

Upload files in your Ruby applications, map them to a range of ORMs, store them on different backends. It works well with Rack based web applications, such as Ruby on Rails.

Related reading

<hr /

Kaminari

Kaminari is a Scope & Engine based, clean, powerful, customizable and sophisticated paginator. Kaminari supports multiple ORMs (ActiveRecord, Mongoid, MongoMapper) multiple web frameworks (Rails, Sinatra), and multiple template engines (ERB, Haml).

Related reading


HAML

Haml (HTML Abstraction Markup Language) is a layer on top of XHTML or XML that’s designed to express the structure of XHTML or XML documents in a non-repetitive, elegant, easy way, using indentation rather than closing tags and allowing Ruby to be embedded with ease. It was originally envisioned as a plugin for Ruby on Rails, but it can function as a stand-alone templating engine.

Related reading


Authlogic

A simple, unobtrusive model based Ruby authentication solution. Authlogic is very flexible, it has a strong public API and a plethora of hooks to allow you to modify behavior and extend it.

Related reading


Shoulda

Shoulda is a gem that allows you to create more understandable tests for your Ruby application. Shoulda allows you to provide context to your tests enabling you to categorize tests according to a specific feature or scenario you’re testing.

Related reading


factory_girl

factory_girl provides a framework and DSL for defining and using factories – less error-prone, more explicit, and all-around easier to work with than fixtures. It has straightforward definition syntax, support for multiple build strategies (saved instances, unsaved instances, attribute hashes, and stubbed objects), and support for multiple factories for the same class (user, admin_user, and so on), including factory inheritance.

Related reading


RMagick

RMagick is an interface between the Ruby programming language and the ImageMagick and GraphicsMagick image processing libraries.

Related reading


Cancan

CanCan is an authorization library for Ruby on Rails which restricts what resources a given user is allowed to access and is decoupled from user roles. All permissions are stored in a single location and not duplicated across controllers, views, and database queries.

Related reading


Nokogiri

Nokogiri is an HTML, XML, SAX, and Reader parser. Among Nokogiri’s many features is the ability to search documents via XPath or CSS3 selectors. Nokogiri parses and searches XML/HTML very quickly, and also has correctly implemented CSS3 selector support as well as XPath support.

Related reading


SASS

Sass makes CSS fun again. Sass is an extension of CSS3, adding nested rules, variables, mixins, selector inheritance, and more. It’s translated to well-formatted, standard CSS using the command line tool or a web-framework plugin.

Related reading


Formtastic

Formtastic is a Rails FormBuilder DSL (with some other goodies) to make it far easier to create beautiful, semantically rich, syntactically awesome, readily stylable and wonderfully accessible HTML forms in your Rails applications.

Related reading


Capistrano

Capistrano is a utility and framework for executing commands in parallel on multiple remote machines, via SSH. It uses a simple DSL (borrowed in part from Rake) that allows you to define tasks, which may be applied to machines in certain roles. It also supports tunneling connections via some gateway machine to allow operations to be performed behind VPN’s and firewalls.

Related reading


Omniauth

OmniAuth is a Ruby authentication framework that provides a standardized interface to many different authentication providers such as Facebook, OpenID, and even traditional username and password.

Related reading


Bundler

Bundler is a tool that manages gem dependencies for your ruby application. It takes a gem manifest file and is able to fetch, download, and install the gems and all child dependencies specified in this manifest. It can manage any update to the gem manifest file and update the bundle’s gems accordingly. It also lets you run any ruby code in context of the bundle’s gem environment.

Related reading


resque

Resque (pronounced like “rescue”) is a Redis-backed library for creating background jobs, placing those jobs on multiple queues, and processing them later. Resque is heavily inspired by DelayedJob.

Related reading


Jammit

Jammit is an industrial strength asset packaging library for Rails, providing both the CSS and JavaScript concatenation and compression that you’d expect, as well as YUI Compressor and Closure Compiler compatibility, ahead-of-time gzipping, built-in JavaScript template support, and optional Data-URI / MHTML image embedding.

Related reading


capybara

Capybara helps you test Rails and Rack applications by simulating how a real user would interact with your app. It is agnostic about the driver running your tests and comes with Rack::Test and Selenium support built in.

Related reading


Active Merchant

Active Merchant is an extraction from the e-commerce system Shopify. Shopify’s requirements for a simple and unified API to access dozens of different payment gateways with very different internal APIs was the chief principle in designing the library. It was developed for usage in Ruby on Rails web applications and integrates seamlessly as a plugin but it also works excellently as a stand alone library.

Related reading


eventmachine

EventMachine implements a fast, single-threaded engine for arbitrary networkcommunications. It’s extremely easy to use in Ruby. EventMachine wraps all interactions with IP sockets, allowing programs to concentrate on the implementation of network protocols. It can be used to create both network servers and clients.

Related reading


mustache

Inspired by ctemplate, Mustache is a framework-agnostic way to renderlogic-free views.As ctemplates says, “It emphasizes separating logic from presentation:it is impossible to embed application logic in this templatelanguage.

Related reading


Passenger

Phusion Passenger™ — a.k.a. mod_rails or mod_rack — makes deployment of Ruby web applications, such as those built on the revolutionary Ruby on Rails web framework, a breeze.

Related reading


Chef

Chef is a system integration framework designed to bring the benefits of configuration management to your entire infrastructure. With Chef, you can manage your servers by writing code, not by running commands.

Related reading


Thinking Sphinx

A concise and easy-to-use Ruby library that connects ActiveRecord to the Sphinx search daemon, managing configuration, indexing and searching.

Related reading


Wrapping Up

So those were some of the awesome gems I’ve found extremely useful when I’m whipping up a web app in Ruby. I’m a 100% sure I’m missing a metric butt load of others though. Let me know about your favorite gems in the comments below and thank you so much for reading!


Go to Source

Meet Crockford’s JSDev

January 26th, 2012

Recently, Douglas Crockford released a neat tool that makes the process of developing and testing your JavaScript a bit easier. Interested in learning more? Watch today’s quick tip to find out!


Watch the Screencast


Show Link


Will you use JSDev?

I’m curious; is this something that you’ll use in your daily coding? I’m still not sure, myself. Let us hear your thoughts in the comments!


Go to Source

Iphone App Development: Over 500,000 Iphone Apps So Far

January 25th, 2012

As the figure shows on Apple site that there are over 500,000 apps. Just Imagine! And, for the Iphone App Development people, this is just the beginning. Phone users (I mean, the iPhone lovers!) are simply not stopping downloading apps, more and more apps for simplifying their work life, personal life, and everything that comes in between. Kudos to Iphone App Development people!

Go to Source

Opensource Customization: Why To Use

January 24th, 2012

Open source software and web applications, such as Linux, Apache Server, Paint.net, Magento, Joomla, Drupal, etc., are very useful. However, there are many people who are ready to go for paid-for software and are doubtful about the benefits of using Open Source Software. But, there are lots of benefits that they can gain from OSS. Here is a list of benefits.

Go to Source

.htaccess Files for the Rest of Us

January 24th, 2012

.htaccess files are used to configure Apache, as well a range of other web servers. Despite the .htaccess file type extension, they are simply text files that can be edited using any text-editor. In this article, we’ll review what they are, and how you can use them in your projects.

Please note that .htaccess files don't work on Windows-based systems, although they can be edited and uploaded to a compatible web server, and on Linux-based systems they are hidden by default.

In order to work with htaccess files locally, to see how they work and generally play around with them, we can use XAMPP (or MAMP) on the Mac – a package that installs and configures Apache, PHP and MySQL. To edit these .htaccess files on Mac, we should use a text editor that allows for the opening of hidden files, such as TextWrangler.

A .htaccess file follows the same format as Apache’s main configuration file: httpd.conf. Many of the settings that can be configured using the main configuration file can also be configured with them, and vice versa.

A setting configured in an .htaccess file will override the same setting in the main configuration file for the directory which contains the file, as well as all of its subdirectories.

They are sometimes referred to as dynamic configuration files because they are read by the server on every request to the directory they are contained within. This means that any changes to an .htaccess file will take effect immediately, without requiring a reboot of the server, unlike changes made to the global configuration file. It also means that you pay a slight performance hit for using them, but they can be useful when you don't have access to the server's main configuration file.

So now we all know what .htaccess files are, how they are edited and worked with, and some of their pros and cons, let's look at how they can be used and some of the cool stuff they can do.


Redirects and URL Rewriting

A popular use of .htaccess files is to perform redirects or rewrite URLs. This can help with SEO following a domain name change, or file-structure reorganisation, or can make long unsightly URL more friendly and memorable.

Redirections

A redirection can be as simple as the following:

Redirect 301 ^old\.html$ <a href="http://localhost/new.html" target="_blank">http://localhost/new.html</a> 

This sets the HTTP status code to 301 (moved permanently) and redirects all requests to old.html transparently to new.html. We use a regular expression to match the URL to redirect, which gives us a fine degree of control to ensure only the correct URL is matched for redirection, but adds complexity to the configuration and administration of it. The full URL of the resource being redirected to is required.

Rewrites

A rewrite rule can be as simple as this:

RewriteEngine on
RewriteRule ^old\.html$ new.html

In this example, we just provide a simple file redirect from one file to another, which will also be performed transparently, without changing what is displayed in the address bar. The first directive, RewriteEngine on, simply ensures that the rewrite engine is enabled.

In order to update what is displayed in the address bar of the visitor's browser, we can use the R flag at the end of the RewriteRule e.g.

RewriteRule ^old\.html$ <a href="http://hostname/new.html" target="_blank">http://hostname/new.html</a> [r=301]

The r flag causes an external redirection which is why the full URL (an example URL here) to the new page is given. We can also specify the status code when using the flag. This causes the address bar to be updated in the visitor's browser.

One of the possible uses for URL rewriting I gave at the start of this section was to make unsightly URLs (containing query-string data) friendlier to visitors and search engines. Let's see this in action now:

RewriteRule ^products/([^/]+)/([^/]+)/([^/<WBR>]+) product.php?cat=$1&brand=$2&<WBR>prod=$3

This rule will allow visitors to use a URL like products/turntables/technics/sl1210, and have it transformed into product.php?cat=turntables&<WBR>brand=technics&prod=sl1210. The parentheses in between the forward slashes in the above regular expression are capturing groups – we can use each of these as $1, $2 and $3 respectively. The [^/]+ character class within the parentheses means match any character except a forward-slash 1 or more times.

In practice, URL rewriting can be (and usually is) much more complex and achieve far greater things than this. URL rewriting is better explained using entire tutorials so we won't look at them in any further detail here.


Serving Custom Error Pages

It's just not cool to show the default 404 page anymore. Many sites take the opportunity offered by a file not found error to inject a little humour into their site, but at the very least, people expect the 404 page of a site to at least match the style and theme of any other page of the site.

Very closely related to URL rewriting, serving a custom error page instead of the standard 404 page is easy with an .htaccess file:

ErrorDocument 404 ";/404.html";

That's all we need; whenever a 404 error occurs, the specified page is displayed. We can configure pages to be displayed for many other server errors too.


Restricting Access to Specific Resources

Using .htaccess files, we can enable password protection of any file or directory, to all users, or based on things like domain or IP address. This is after all one of their core uses. To prevent access to an entire directory, we would simple create a new .htaccess file, containing the following code:

AuthName ";Username and password required";
AuthUserFile /path/to/.htpasswd
Require valid-user
AuthType Basic

This file should then be saved into the directory we wish to protect. The AuthName directive specifies the message to display in the username/password dialog box, the AuthUserFile should be the path to the .htpasswd file. The Require directive specifies that only authenticated users may access the protected file while the AuthType is set to Basic.

To protect a specific file, we can wrap the above code in a <files> directive, which specifies the protected file:

Files ";protectedfile.html";>
AuthName ";Username and password required";
AuthUserFile /path/to/.htpasswd
Require valid-user
AuthType Basic
</Files>

We also require an .htpasswd file for these types of authentication, which contains a colon-separated list of usernames and encrypted passwords required to access the protected resource(s). This file should be saved in a directory that is not accessible to the web. There are a range of services that can be used to generate these files automatically as the password should be stored in encrypted form.


Block Access to Certain Entities

Another use of .htaccess files is to quickly and easily block all requests from an IP address or user-agent. To block a specific IP address, simply add the following directives to your .htaccess file:

order allow,deny
deny from 192.168.0.1
allow from all

The order directive tells Apache in which order to evaluate the allow/deny directives. In this case, allow is evaluated first, then deny. The allow from all directive is evaluated first (even though it appears after the deny directive) and all IPs are allowed, then if the client's IP matches the one specified in the deny directive, access is forbidden. This lets everyone in except the specified IP. Note that we can also deny access to entire IP blocks by supplying a shorter IP, e.g. 192.168.

To deny requests based on user-agent, we could do this:

RewriteCond %{HTTP_USER_AGENT} ^OrangeSpider
RewriteRule ^(.*)$ http://%{REMOTE_ADDR}/$ [r=301,l]

In this example, any client with a HTTP_USER_AGENT string starting with OrangeSpider (a bad bot) is redirected back to the address that it originated from. The regular expression matches any single character (.) zero or more times (*) and redirects to the %{REMOTE_ADDR} environment variable. The l flag we used here instructs Apache to treat this match as the last rule so will not process any others before performing the rewrite.


Force an IE Rendering Mode

Alongside controlling how the server responds to certain requests, we can also do things to the visitor's browser, such as forcing IE to render pages using a specific rendering engine. For example, we can use the mod_headers module, if it is present, to set the X-UA-Compatible header:

Header set X-UA-Compatible ";IE=Edge";

Adding this line to an .htaccess file will instruct IE to use the highest rendering mode available. As demonstrated by HTML5 Boilerplate, we can also avoid setting this header on files that don't require it by using a <FilesMatch directive like so:

<FilesMatch ";\.(js|css|gif|png|jpe?g|pdf|<WBR>xml|oga|ogg|m4a|ogv|mp4|m4v|<WBR>webm|svg|svgz|eot|ttf|otf|<WBR>woff|ico|webp|appcache|<WBR>manifest|htc|crx|xpi|<WBR>safariextz|vcf)$";>;
  Header unset X-UA-Compatible
</FilesMatch>

Implement Caching

Caching is easy to set up and can make your site load faster.

Caching is easy to set up and can make your site load faster. 'Nuff said! By setting a far-future expires date on elements of sites that don't change very often, we can prevent the browser from requesting unchanged resources on every request.

If you're running your site through Google PageSpeed or Yahoo's YSlow and you get the message about setting far-future expiry headers, this is how you fix it:

ExpiresActive on
ExpiresByType image/gif                 ";access plus 1 month";
ExpiresByType image/png                 ";access plus 1 month";
ExpiresByType image/jpg                 ";access plus 1 month";
ExpiresByType image/jpeg                ";access plus 1 month";
ExpiresByType video/ogg                 ";access plus 1 month";
ExpiresByType audio/ogg                 ";access plus 1 month";
ExpiresByType video/mp4                 ";access plus 1 month";
ExpiresByType video/webm                ";access plus 1 month";

You can add different ExpiresByType directives for any content that is listed in the performance tool you're using, or anything else that you want to control caching on. The first directive, ExpiresActive on, simply ensures the generation of Expires headers is switched on. These directives depend on Apache having the mod_expires module loaded.


Enabling Compression

Another warning we may get in a performance checker refers to enabling compression, and this is also something we can fix simply by updating our .htaccess file:

FilterDeclare   COMPRESS
FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/html
FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/css
FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/javascript
FilterChain     COMPRESS
FilterProtocol  COMPRESS  DEFLATE change=yes;byteranges=no

This compression scheme works on newer versions of Apache (2.1+) using the mod_filter module. It uses the DEFLATE compression algorithm to compress content based on its response content-type, in this case we specify text/html, text/css and text/javascript (which will likely be the types of files flagged in PageSpeed/Yslow anyhow).

In the above example we start out by declaring the filter we wish to use, in this case COMPRESS, using the FilterDeclare directive. We then list the content types we wish to use this filter. The FilterChain directive then instructs the server to build a filter chain based on the FilterProvider directives we have listed. The FilterProtocol directive allows us to specify options that are applied to the filter chain whenever it is run, the options we need to use are change=yes (the content may be changed by the filter (in this case, compressed)) and byteranges=no (the filter must only be applied to complete files).

On older versions of Apache, the mod_deflate module is used to configure DEFLATE compression. We have less control of how the content is filtered in this case, but the directives are simpler:

SetOutputFilter DEFLATE
AddOutputFilterByType DEFLATE text/html text/css text/javascript

In this case we just set the compression algorithm using the SetOutputFilter directive, and then specify the content-types we'd like to compress using the AddOutputFilterByType directive.

Usually your web server will use one of these modules depending on which version of Apache is in use. Generally, you will know this beforehand, but if you are creating a generic .htaccess file that you can use on a variety of sites, or which you may share with other people and therefore you don't know which modules may be in use, you may wish to use both of the above blocks of code wrapped in <IfModule module_name> directives so that the correct module is used and the server doesn't throw a 500 error if we try to configure a module that isn't included. You should be aware that it's also relatively common for hosts that run a large number of sites from a single box to disable compression as there is a small CPU performance hit for compressing on the server.


Summary

We looked at some of the most common uses for .htaccess files, and reviewed how we can achieve certain tasks that, as website builders/maintainers, are of particular interest to us. As is the case with any introductory tutorial of this nature, the subjects we've covered are presented as introductions to a particular topic. There are many other options and configurations than we have been able to look at, so I'd strongly recommend further reading on any subject that is of particular interest.


Go to Source

The Importance of a Sitemap

January 23rd, 2012

A sitemap is often considered redundant in the process of building a website, and that is indeed the fact if you made a sitemap for the sake of having one. By highlighting the importance of having a well constructed sitemap, you will be able to tailor your own sitemap to suit your own needs.

Go to Source

Testing your PHP Codebase with EnhancePHP

January 22nd, 2012

You know it; I know it. We should be testing our code more than we do. Part of the reason we don’t, I think, is that we don’t know exactly how. Well, I’m getting rid of that excuse today: I’m teaching you to test your PHP with the EnhancePHP framework.


Meet EnhancePHP

I’m not going to try to convince you to test your code; and we’re not going to discuss Test Driven Development, either. That’s been done before on Nettuts+. In that article, Nikko Bautista explains exactly why testing is a good thing and outlines a TDD workflow. Read that sometime, if you aren’t familiar with TDD. He also uses the SimpleTest library for his examples, so if you don’t like the look of EnhancePHP, you might try SimpleTest as an alternative.

As I said, we’ll be using the EnhancePHP. It’s a great little PHP library—a single file—that offers a lot of testing functionality.

Start by heading over to their download page and grabbing the latest version of the framework.

We’re going to be building a really simple Validation class to test. It won’t do too much: just return true if the item passes validation, or false if it doesn’t. So, set up a really simple little project:

We’ll do this is a semi-TDD fashion, so let’s start by writing a few tests.


Writing Tests

Out little class is going to validate three things: email addresses, usernames, and phone numbers.

But before we get to writing actual tests, we’ll need to set up our class:

<?php

class Validation_test extends \Enhance\TestFixture {
	public function setUp () {
		$this-> val = new Validation();
	}

}

This is our start; notice that we’re extending the class \Enhance\TestFixture. By doing so, we let EnhancePHP know that any public methods of this class are tests, with the exception of methods setUp and tearDown. As you might guess, these methods run before and after all your tests (not before and after each one). In this case, our setUp method will create a new Validation instance and assign it to a property on our instance.

By the way, if you’re relatively new to PHP, you might not be familiar with that \Enhance\TestFixture syntax: what’s with the slashes? That’s PHP namespacing for you; check out the docs if you aren’t familiar with it.

So, the tests!

Email Addresses

Let’s start by validating email addresses. As you’ll see, just doing a basic test is pretty simple:

public function validates_a_good_email_address () {
	$result = $this->val->validate_email("john@doe.com");
	\Enhance\Assert::isTrue($result);
}

We simply call the method we want to test, passing it a valid email address, and storing the $result. Then, we hand $result to the isTrue method. That method belongs to the \Enhance\Assert class.

We want to make sure our class will reject non-email addresses. So, let’s test for that:

public function reject_bad_email_addresses () {
	$val_wrapper = \Enhance\Core::getCodeCoverageWrapper('Validation');
	$val_email = $this->get_scenario('validate_email');
	$addresses = array("john", "jo!hn@doe.com", "john@doe.", "jo*hn@doe.com");

	foreach ($addresses as $addr) {
  		$val_email->with($addr)->expect(false);
	}
	$val_email->verifyExpectations();
}

This introduces a pretty cool feature of EnhancePHP: scenarios. We want to test a bunch of non-email addresses to make sure our method will return false. By creating a scenario, we essentially wrap an instance of our class in some EnhancePHP goodness, are write much less code to test all our non-addresses. That’s what $val_wrapper is: a modified instance of our Validation class. Then, $val_email is the scenario object, somewhat like a shortcut to the validate_email method.

Then, we’ve got an array of strings that should not validate as email addresses. We’ll loop over that array with a foreach loop. Notice how we run the test: we call the with method on our scenario object, passing it the parameters for the method we’re testing. Then, we call the expect method on that, and pass it whatever we expect to get back.

Finally, we call the scenario’s verifyExpectations method.

So, the first tests are written; how do we run them?


Running Tests

Before we actually run the tests, we’ll need to create our Validation class. Inside lib.validation.php, start with this:

<?php

class Validation {
	public function validate_email ($address) {

	}
}

Now, in test.php, we’ll pull it all together:

<?php

require "vendor/EnhanceTestFramework.php";
require "lib/validation.php";
require "test/validation_test.php";

\Enhance\Core::runTests();

First, we’ll require all the necessary files. Then, we call the runTests method, which finds our tests.

Next comes the neat part. Fire up a server, and you’ll get some nice HTML output:

Very nice, right? Now, if you’ve got PHP in your terminal, run this is in the terminal:

EnhancePHP notices that you’re in a different environment, and adjusts its output appropriately. A side benefit of this is that if you’re using an IDE, like PhpStorm, that can run unit tests, you can view this terminal output right inside the IDE.

You can also get XML and TAP output, if that’s what you prefer, just pass \Enhance\TemplateType::Xml or \Enhance\TemplateType::Tap to the runTests method to get the appropriate output. Note that running it in the terminal will also produce command-line results, no matter what you pass to runTests.

Getting the Tests to Pass

Let’s write the method that causes our tests to pass. As you know, that’s the validate_email. At the top of the Validation class, let’s define a public property:

public $email_regex = '/^[\w+-_\.]+@[\w\.]+\.\w+$/';

I’m putting this in a public property so that if the user wants to replace it with their own regex, they could. I’m using this simple version of an email regex, but you can replace it with your favourite regex if you want.

Then, there’s the method:

public function validate_email ($address) {
	return preg_match($this->email_regex, $address) == 1
}

Now, we run the tests again, and:


Writing More Tests

Time for more tests:

Usernames

Let’s create some tests for usernames now. Our requirements are simply that it must be a 4 to 20 character string consisting only of word characters or periods. So:

public function validates_a_good_username () {
	$result = $this->val->validate_username("some_user_name.12");
	\Enhance\Assert::isTrue($result);
}

Now, how about a few usernames that shouldn’t validate:

public function rejects_bad_usernames () {
	$val_username = $this->get_scenario('validate_username');
	$usernames = array(
		"name with space",
		"no!exclaimation!mark",
		"ts",
		"thisUsernameIsTooLongItShouldBeBetweenFourAndTwentyCharacters");

	foreach ($usernames as $name) {
  		$val_username->with($name)->expect(false);
	}
	$val_username->verifyExpectations();
}

This is very similar to our reject_bad_email_addresses function. Notice, however, that we’re calling this get_scenario method: where’s that come from? I’m abstracting the scenario creation functionality into private method, at the bottom of our class:

private function get_scenario ($method) {
	$val_wrapper = \Enhance\Core::getCodeCoverageWrapper('Validation');
    return \Enhance\Core::getScenario($val_wrapper, $method);
}

We can use this in our reject_bad_usernames and replace the scenario creation in reject_bad_email_addresses as well. Because this is a private method, EnhancePHP won’t try to run it as a normal test, the way it will with public methods.

We’ll make these tests pass similarly to how we made the first set pass:

# At the top . . .
public  $username_regex = '/^[\w\.]{4,20}$/';

# and the method . . .
public function validate_username ($username) {
	return preg_match($this->username_regex, $username) == 1;
}

This is pretty basic, of course, but that’s all that’s needed to meet our goal. If we wanted to return an explanation in the case of failure, you might do something like this:

public function validate_username ($username) {
	$len = strlen($username);
	if ($len < 4 || $len > 20) {
  		return "Username must be between 4 and 20 characters";
	} elseif (preg_match($this->username_regex, $username) == 1) {
  		return true;
	} else {
  		return "Username must only include letters, numbers, underscores, or periods.";
	}
}

Of course, you might also want to check if the username already exists.

Now, run the tests and you should see them all passing.

Phone Numbers

I think you’re getting the hang of this by now, so let’s finish of our validation example by checking phone numbers:

public function validates_good_phonenumbers () {
	$val_phonenumber = $this->get_scenario("validate_phonenumber");
	$numbers = array("1234567890", "(890) 123-4567",
		"123-456-7890", "123 456 7890", "(123) 456 7890");

	foreach($numbers as $num) {
  		$val_phonenumber->with($num)->expect(true);
	}
	$val_phonenumber->verifyExpectations();
}

public function rejects_bad_phonenumnbers () {
	$result = $this->val->validate_phonenumber("123456789012");
	\Enhance\Assert::isFalse($result);
}

You can probably figure out the Validation method:

public $phonenumber_regex = '/^\d{10}$|^(\(?\d{3}\)?[ |-]\d{3}[ |-]\d{4})$/';

public function validate_phonenumber ($number) {
	return preg_match($this->phonenumber_regex, $number) == 1;
}

Now, we can run all the tests together. Here’s what that looks like from the command line (my preferred testing environment):


Other Test Functionality

Of course, EnhancePHP can do a lot more than what we’ve looked at in this little example. Let’s look at some of that now.

We very briefly met the \Enhance\Assert class in our first test. We didn’t really use it otherwise, because it’s not useful when using scenarios. However, it’s where all the assertion methods are. The beauty of them is that their names make their functionality incredibly obvious. The following test examples would pass:

  • \Enhance\Assert::areIdentical("Nettuts+", "Nettuts+")
  • \Enhance\Assert::areNotIdentical("Nettuts+", "Psdtuts+")
  • \Enhance\Assert::isTrue(true)
  • \Enhance\Assert::isFalse(false)
  • \Enhance\Assert::contains("Net", "Nettuts+")
  • \Enhance\Assert::isNull(null)
  • \Enhance\Assert::isNotNull('Nettust+')
  • \Enhance\Assert::isInstanceOfType('Exception', new Exception(""))
  • \Enhance\Assert::isNotInstanceOfType('String', new Exception(""))

There are a few other assertion methods, too; you can check the docs for a complete list and examples.

Mocks

EnhancePHP can also do mocks and stubs. Haven’t heard of mocks and stubs? Well, they aren’t too complicated. A mock is a wrapper for object, that can keep track of what methods are called, with what properties they are called, and what values are returned. A mock will have some test to verify, as we’ll see.

Here’s a small example of a mock. Let’s start with a very simple class that counts:

<?php

require "vendor/EnhanceTestFramework.php";

class Counter {
  public $num = 0;
  public function increment ($num = 1) {
    $this->num = $this->num + $num;
    return $this->num;
  }
}

We have one function: increment, that accepts a parameter (but defaults to 1), and increments the $num property by that number.

We might use this class if we were building a scoreboard:

class Scoreboard {
  public $home = 0;
  public $away = 0;

  public function __construct ($home, $away) {
    $this->home_counter = $home;
    $this->away_counter = $away;
  } 

  public function score_home () {
    $this->home = $this->home_counter->increment();
    return $this->home;
  }
  public function score_away () {
    $this->away = $this->away_counter->increment();
    return $this->home;
  }
}

Now, we want to test to make sure that the Counter instance method increment is working properly when the Scoreboard instance methods call it. So we creat this test:

class ScoreboardTest extends \Enhance\TestFixture {
  public function score_home_calls_increment () {
    $home_counter_mock = \Enhance\MockFactory::createMock("Counter");
    $away_counter = new Counter();

    $home_counter_mock->addExpectation( \Enhance\Expect::method('increment') );

    $scoreboard = new Scoreboard($home_counter_mock, $away_counter);
    $scoreboard->score_home();

    $home_counter_mock->verifyExpectations();
  }
}

\Enhance\Core::runTests();

Notice that we start by creating $home_counter_mock: we use the EnhancePHP mock factory, passing it the name of the class we’re mocking. This returns a “wrapped” instance of Counter. Then, we add an expectation, with this line

$home_counter_mock->addExpectation( \Enhance\Expect::method('increment') );

Our expectation just says that we expect the increment method to be called.

After that, we go on to create the Scoreboard instance, and call score_home. Then, we verifyExpectations. If you run this, you’ll see that our test passes.

We could also state what parameters we want a method on the mock object to be called with, what value is returned, or how many times the method should be called, with something like this:

$home_counter_mock->addExpectation( \Enhance\Expect::method('increment')->with(10) );
$home_counter_mock->addExpectation( \Enhance\Expect::method('increment')->times(2) );
$home_counter_mock->addExpectation( \Enhance\Expect::method('increment')->returns(1) );
$home_counter_mock->addExpectation( \Enhance\Expect::method('increment')->with(3)->times(1) );
$home_counter_mock->addExpectation( \Enhance\Expect::method('increment')->with(2)->returns(2) );

I should mention that, while with and times will show failed tests if the expectations aren’t meant, returns doesn’t. You’ll have to store the return value and use an assertion to very that. I’m not sure why that’s the case, but every library has its quirks :) . (You can see an example of this in the library examples in Github.)

Stubs

Then, there are stubs. A stub fills in for a real object and method, returning exactly what you tell it to. So, let’s say we want to make sure that our Scoreboard instance is correctly using the value it receives from increment, we can stub a Counter instance so we can control what increment will return:

class ScoreboardTest extends \Enhance\TestFixture {
  public function score_home_calls_increment () {
    $home_counter_stub = \Enhance\StubFactory::createStub("Counter");
    $away_counter = new Counter();

    $home_counter_stub->addExpectation( \Enhance\Expect::method('increment')->returns(10) );

    $scoreboard = new Scoreboard($home_counter_stub, $away_counter);
    $result = $scoreboard->score_home();

    \Enhance\Assert::areIdentical($result, 10);

  }
}

\Enhance\Core::runTests();

Here, we’re using \Enhance\StubFactory::createStub to create our stub counter. Then, we add an expectation that the method increment will return 10. We can see that the result it what we’d expect, given our code.

For more examples of mocks and stub with the EnhancePHP library, check out the Github Repo.


Conclusion

Well, that’s a look at testing in PHP, using the EnhancePHP framework. It’s an incredibly simple framework, but it provides everything you need to do some simple unit testing on your PHP code. Even if you choose a different method/framework for testing your PHP (or perhaps roll your own!), I hope this tutorial has sparked an interest in testing your code, and how simple it can be.

But maybe you already test your PHP. Let us all know what you use in the comments; after all, we’re all here to learn from each other! Thank you so much for stopping by!


Go to Source

Embedding on WordPress For CMS Development

January 20th, 2012

This option is widely used by WordPress developers for their WordPress Development needs. Also companies and individuals prefer to outsource wordpress development to save time and money both. Hundreds of communities have successfully and voluntarily built the core software.

Go to Source

jQuery Mobile Framework Tutorials

January 20th, 2012

jQuery Mobile is a flexible jQuery/HTML5/CSS3-based framework that you can use to build web sites optimized for display on a large variety of mobile devices. jQuery Mobile is easy to use and develop due to its lightweight code. Multiple themes and designs allow you to change your site and appearance easily. This VTC course by jQuery Mobile expert, Trevor James, starts from the beginner level and uses practical examples to demonstrate the jQuery Mobile framework. You will learn how to build an entire web site that will display on a variety of mobile devices. Source code is included. To begin learning today, simply click on the movie links.

Go to Source