Quantcast
Channel: Nettuts+
Viewing all 502 articles
Browse latest View live

What They Didn’t Tell You About ES5′s Array Extras

$
0
0

Every new version of JavaScript adds some extra goodies that make programming easier. EcmaScript 5 added some much needed methods to the Array data type, and, while you can find resources which teach you how to use these methods, they typically omit a discussion on using them with anything other than a boring, custom function.

All of the array extras ignore holes in arrays.

The new array methods added in ES5 are usually referred to as Array Extras. They ease the process of working with arrays by providing methods to perform common operations. Here is an almost complete list of the new methods:

Array.prototype.indexOf and Array.prototype.lastIndexOf are also part of that list, but this tutorial will only discuss the above seven methods.


What They Told You

These methods are fairly simple to use. They execute a function that you supply as their first argument, for every element in the array. Typically, the supplied function should have three parameters: the element, the element’s index, and the whole array. Here are a few examples:

[1, 2, 3].map(function(elem, index, arr){
    return elem * elem;
});
//returns [1, 4, 9]
[1, 2, 3, 4, 5].filter(function(elem, index, arr){
    return elem % 2 === 0;
});
//returns [2, 4]
[1, 2, 3, 4, 5].some(function(elem, index, arr){
    return elem >= 3;
});
//returns true
[1, 2, 3, 4, 5].every(function(elem, index, arr){
    return elem >= 3;
});
//returns false

The reduce and reduceRight methods have a different parameter list. As their names suggest, they reduce an array to a single value. The initial value of the result defaults to the first element in the array, but you can pass a second argument to these methods to serve as the initial value.

The callback function for these methods accepts four arguments. The current state is the first argument, and the remaining arguments are the element, index, and array. The following snippets demonstrate the usage of these two methods:

[1, 2, 3, 4, 5].reduce(function(sum, elem, index, arr){
    return sum + elem;
});
//returns 15
[1, 2, 3, 4, 5].reduce(function(sum, elem, index, arr){
    return sum + elem;
}, 10);
//returns 25

But you probably already knew all of this, didn’t you? So let’s move onto something you may not be familiar with.


Functional Programming to the Rescue

It’s surprising that more people don’t know this: you don’t have to create a new function and pass it to .map() and friends. Even better, you can pass built-in functions, such as parseFloat with no wrapper required!

["1", "2", "3", "4"].map(parseFloat); //returns [1, 2, 3, 4]

Note that some functions won’t work as expected. For example, parseInt accepts a radix as a second argument. Now remember that the element’s index is passed to the function as a second argument. So what will the following return?

["1", "2", "3", "4"].map(parseInt);

Exactly: [1, NaN, NaN, NaN]. As an explanation: base 0 is ignored; so, the first value gets parsed as expected. The following bases don’t include the number passed as the first argument (eg. base 2 doesn’t include 3), which leads to NaNs. So make sure to check the Mozilla Developer Network upfront before using a function and you’ll be good to go.

Pro-tip: You can even use built-in constructors as arguments, as they aren’t required to be called with new. As a result, a simple conversion to a boolean value can be done using Boolean, like this:

["yes", 0, "no", "", "true", "false"].filter(Boolean); //returns ["yes", "no", "true", "false"]

A couple of other nice functions are encodeURIComponent, Date.parse (note that you can’t use the Date constructor as it always returns the current date when called without new), Array.isArray and JSON.parse.


Don’t Forget to .apply()

While using built-in functions as arguments for array methods may make for a nice syntax, you should also remember that you can pass an array as the second argument of Function.prototype.apply. This is handy, when calling methods, like Math.max or String.fromCharCode. Both functions accept a variable number of arguments, so you’ll need to wrap them in a function when using the array extras. So instead of:

var arr = [1, 2, 4, 5, 3];
var max = arr.reduce(function(a, b) {
    return Math.max(a, b);
});

You can write the following:

var arr = [1, 2, 4, 5, 3];
var max = Math.max.apply(null, arr);

This code also comes with a nice performance benefit. As a side-note: In EcmaScript 6, you’ll be able to simply write:

var arr = [1, 2, 4, 5, 3];
var max = Math.max(…arr); //THIS CURRENTLY DOESN'T WORK!

Hole-less Arrays

All of the array extras ignore holes in arrays. An example:

var a = ["hello", , , , , "world"]; //a[1] to a[4] aren't defined
var count = a.reduce(function(count){ return count + 1; }, 0);
console.log(count); // 2

This behavior probably comes with a performance benefit, but there are cases when it can be a real pain in the butt. One such example might be when you need an array of random numbers; it isn’t possible to simply write this:

var randomNums = new Array(5).map(Math.random);

But remember that you can call all native constructors without new. And another useful tidbit: Function.prototype.apply doesn’t ignore holes. Combining these, this code returns the correct result:

var randomNums = Array.apply(null, new Array(5)).map(Math.random);

The Unknown Second Argument

Most of the above is known and used by many programmers on a regular basis. What most of them don’t know (or at least don’t use) is the second argument of most of the array extras (only the reduce* functions don’t support it).

Using the second argument, you can pass a this value to the function. As a result, you’re able to use prototype-methods. For example, filtering an array with a regular expression becomes a one-liner:

["foo", "bar", "baz"].filter(RegExp.prototype.test, /^b/);
//returns ["bar", "baz"]

Also, checking if an object has certain properties becomes a cinch:

["foo", "isArray", "create"].some(Object.prototype.hasOwnProperty, Object);
//returns true (because of Object.create)

In the end, you can use every method you would like to:

//lets do something crazy
[
    function(a) { return a * a; },
    function(b) { return b * b * b; }
]
.map(Array.prototype.map, [1, 2, 3]);
//returns [[1, 4, 9], [1, 8, 27]]

This becomes insane when using Function.prototype.call. Watch this:

["  foo ", "\n\tbar", "\r\nbaz\t "].map(Function.prototype.call, String.prototype.trim);
//returns ["foo", "bar", "baz"]
[true, 0, null, []].map(Function.prototype.call, Object.prototype.toString);
//returns ["[object Boolean]", "[object Number]", "[object Null]", "[object Array]"]

Of course, to please your inner geek, you can also use Function.prototype.call as the second parameter. When doing so, every element of the array is called with its index as the first argument and the whole array as the second:

[function(index, arr){
    //whatever you might want to do with it
}].forEach(Function.prototype.call, Function.prototype.call);

Lets Build Something Useful

With all that said, let’s build a simple calculator. We only want to support the basic operators (+, -, *, /), and we need to respect operator procedure. So, multiplication (*) and division (/) need to be evaluated before addition (+) and subtraction (-).

Firstly, we define a function that accepts a string representing the calculation as the first and only argument.

function calculate (calculation) {

In the function body, we start converting the calculation into an array by using a regular expression. Then, we ensure that we parsed the whole calculation by joining the parts using Array.prototype.join and comparing the result with the original calculation.

var parts = calculation.match(
    //   digits    |operators|whitespace
    /(?:\-?[\d\.]+)|[-\+\*\/]|\s+/g
);
if( calculation !== parts.join("") ) {
    throw new Error("couldn't parse calculation")
}

After that, we call String.prototype.trim for each element to eliminate white-space. Then, we filter the array and remove falsey elements (ie:f empty strings).

parts = parts.map(Function.prototype.call, String.prototype.trim);
parts = parts.filter(Boolean);

Now, we build a separate array that contains parsed numbers.

var nums = parts.map(parseFloat);

You can pass built-in functions such as parseFloat with no wrapper required!

At this point, the easiest way to continue is a simple for-loop. Within it, we build another array (named processed) with multiplication and division already applied. The basic idea is to reduce every operation to an addition, so that the last step becomes pretty trivial.

We check every element of the nums array to ensure it’s not NaN; if it’s not a number, then it’s an operator. The easiest way to do this is by taking advantage of the fact that, in JavaScript, NaN !== NaN. When we find a number, we add it to the result array. When we find an operator, we apply it. We skip addition operations and only change the sign of the next number for subtraction.

Multiplication and division need to be calculated using the two surrounding numbers. Because we already appended the previous number to the array, it needs to be removed using Array.prototype.pop. The result of the calculation gets appended to the result array, ready to be added.

var processed = [];
for(var i = 0; i < parts.length; i++){
    if( nums[i] === nums[i] ){
        processed.push( nums[i] );
    } else {
        switch( parts[i] ) {
            case "+":
                continue; //ignore
            case "-":
                processed.push(nums[++i] * -1);
                break;
            case "*":
                processed.push(processed.pop() * nums[++i]);
                break;
            case "/":
                processed.push(processed.pop() / nums[++i]);
                break;
            default:
                throw new Error("unknown operation: " + parts[i]);
        }
    }
}

The last step is fairly easy: We just add all numbers and return our final result.

return processed.reduce(function(result, elem){
    return result + elem;
});

The completed function should look like so:

function calculate (calculation) {
    //build an array containing the individual parts
    var parts = calculation.match(
        //   digits    |operators|whitespace
        /(?:\-?[\d\.]+)|[-\+\*\/]|\s+/g
    );
    //test if everything was matched
    if( calculation !== parts.join("") ) {
        throw new Error("couldn't parse calculation")
    }
    //remove all whitespace
    parts = parts.map(Function.prototype.call, String.prototype.trim);
    parts = parts.filter(Boolean);
    //build a separate array containing parsed numbers
    var nums = parts.map(parseFloat);
    //build another array with all operations reduced to additions
    var processed = [];
    for(var i = 0; i < parts.length; i++){
        if( nums[i] === nums[i] ){ //nums[i] isn't NaN
            processed.push( nums[i] );
        } else {
            switch( parts[i] ) {
                case "+":
                    continue; //ignore
                case "-":
                    processed.push(nums[++i] * -1);
                    break;
                case "*":
                    processed.push(processed.pop() * nums[++i]);
                    break;
                case "/":
                    processed.push(processed.pop() / nums[++i]);
                    break;
                default:
                    throw new Error("unknown operation: " + parts[i]);
            }
        }
    }
    //add all numbers and return the result
    return processed.reduce(function(result, elem){
        return result + elem;
    });
}

Okay, so let’s test it:

calculate(" 2 + 2.5 * 2  ") // returns 7
calculate("12 / 6 + 4 * 3") // returns 14

It appears to be working! There are still some edge-cases that aren’t handled, such as operator-first calculations or numbers containing multiple dots. Support for parenthesis would be nice, but we won’t worry about digging into more details in this simple example.


Wrapping Up

While ES5′s array extras might, at first, appear to be fairly trivial, they reveal quite a bit of depth, once you give them a chance. Suddenly, functional programming in JavaScript becomes more than callback hell and spaghetti code. Realizing this out was a real eye-opener for me and influenced my way of writing programs.

Of course, as seen above, there are always cases where you’d want to instead use a regular loop. But, and that’s the nice part, you don’t need to.


Dependency Injection in PHP

$
0
0

Dependency injection has been a frequent subject of discussion among many corporate developers in the past few years. Many feared that they might sacrifice too much time building their application architecture without doing any real work. In this article, I’ll explain why PHP developers should consider taking advantage of dependency injection, when building large, scalable projects.


What is Dependency Injection?

Before digging into the subject, let’s precisely define what dependency injection is. Let’s imagine that you currently work on a “Question and Answers” website, similar to Stack Overflow. You would more than likely create a class, called Question, which would contain a member of type Author. In ‘ye olden days, programmers would have created the Author object directly in the Question constructor, like this:

class Author {
    private $firstName;
    private $lastName;
    public function __construct($firstName, $lastName) {
        $this->firstName = $firstName;
        $this->lastName = $lastName;
    }
    public function getFirstName() {
        return $this->firstName;
    }
    public function getLastName() {
        return $this->lastName;
    }
}
class Question {
    private $author;
    private $question;
    public function __construct($question, $authorFirstName, $authorLastName) {
        $this->author = new Author($authorFirstName, $authorLastName);
        $this->question = $question;
    }
    public function getAuthor() {
        return $this->author;
    }
    public function getQuestion() {
        return $this->question;
    }
}

While many programmers might call this good code, there are in fact many problems with it:

  • The author’s information passed to the Question constructor has nothing to do inside Question‘s scope. The name of an author should be inside the Author class because it has nothing to do with the question, itself.
  • The Author class is tightly coupled with the Question class. If we add a new parameter to Author‘s constructor, we then have to modify every class where we create an Author object – a tedious and long process, especially in large applications.
  • Unit testing the Question class creates the unwanted behavior of having to test the Author class as well.

Dependency injection alleviates these issues by inserting the dependencies through the dependent class’ constructor (“Constructor Injection”). The result is highly maintainable code, which might look like this:

class Author {
    private $firstName;
    private $lastName;
    public function __construct($firstName, $lastName) {
        $this->firstName = $firstName;
        $this->lastName = $lastName;
    }
    public function getFirstName() {
        return $this->firstName;
    }
    public function getLastName() {
        return $this->lastName;
    }
}
class Question {
    private $author;
    private $question;
    public function __construct($question, Author $author) {
        $this->author = $author;
        $this->question = $question;
    }
    public function getAuthor() {
        return $this->author;
    }
    public function getQuestion() {
        return $this->question;
    }
}

Advantages of Dependency Injection

You need to use Dependency Injection for long-term projects.

I have worked on many commercial projects in my career. Some of them are very well written; however, I must say that most of them have considerably poor code quality. I was recently assigned to work on such a code base…

A company requested the application in 2009. The project’s budget was properly planned, but the project manager wanted the application built very quickly to impress his boss. At least, this is what my co-worker told me. Writing an application quickly might sound great to reduce costs, but it also means that the developers jumped into the code without proper planning.

The developers wrote code quickly, creating classes necessary to perform the necessary functionality. The features changed as the project evolved, and because the project was poorly planned (and every class was tightly coupled), the project became difficult to develop.

Currently, it’s difficult to work on this project. Modifying a simple class results in a cascade of other modifications in other classes, because everything is coupled together – resulting in many bugs. Each time something is modified, the developer needs to chase down and fix bugs.

The application is also impossible to unit test, degrading the code’s quality.

Every feature must be manually tested, losing valuable time that could be spent elsewhere. In fact, to reduce the cost of manual testing, we created software to test the infrastructure of the application. Yes, we had to create new software in order to test the actual product.

The company learned that trying to quickly write software resulted in unexpected costs. At first, the company made a lot of money because they charged a lot for it, but after three years, they lost money on this application. The amount of money they pulled in doesn’t cover the continued, high expense of maintenance. They also lost many good, senior developers, who lost any desire to work on the project.

If the application used dependency injection, the developers would have been able to properly unit test the full application, leading to reduced maintenance costs and debugging. The company would have focused on creating new features that last, instead of losing software quality every time that a new feature was introduced. They would also have kept their senior team members and avoided losing money by finding and hiring new employees (which is difficult to begin with in my city).


Getting Started on a Limited Budget

While dependency injection helps assists you in writing better code, it can also require extra time and effort to do it correctly. This can prove to be an issue, if you need working code for a demo.

If all you need is a proof of concept, then I suggest that you don’t waste time with dependency injection and proper architecture.

Jump right in and start coding. You can do things correctly after the project is approved and you have the necessary funding. In fact, once you do have proper funding, throw away your demo and begin from scratch. Otherwise, your application will end up as a spaghetti-code-trash-can.


Messy Start-up Code

So, you’ve begun passing your dependencies in your class constructors, but as the project grows, you end up with many levels of objects that must be created when your application starts. Depending on your application’s size, creating all objects to launch your application can be a very long process and hurt your application’s performance (as well as result in messy code). Here’s an example:

/*
    Please note that the nature of the application is not important here. I only wanted to show how hard-to-maintain/awful such code can be:
*/
$filePath = "/path/to/file";
$fileBuilderFactory = new ConcreteFileBuilderFactory();
$filesXmlBuilderFactory = new ConcreteFilesXmlBuilderFactory($fileBuilderFactory);
$softwaresRetrieverCriteriaBuilderFactory = new ConcreteSoftwaresRetrieverCriteriaBuilderFactory($filesXmlBuilderFactory);
$softwareRetrieverCriteriaBuilderFactory = new ConcreteSoftwaresSoftwareRetrieverCriteriaBuilderFactory($filesXmlBuilderFactory);
$filesJsonBuilderFactory = new ConcreteFilesJsonBuilderFactory($fileBuilderFactory);
$objectBuildderFactory = new ConcreteSoftwaresSoftwareObjectBuilderFactory();
$softwaresSoftwareBuilderFactory = new ConcreteSoftwaresSoftwareBuilderFactory($objectBuildderFactory);
$xmlSoftwareRepository = new XmlSoftwareRepository($softwaresSoftwareBuilderFactory);
$softwaresBuilderFactory = new ConcreteSoftwaresBuilderFactory($xmlSoftwareRepository, $softwareRetrieverCriteriaBuilderFactory, $filesJsonBuilderFactory);
$xmlSoftwaresRepository = new XmlSoftwaresRepository($softwaresBuilderFactory);
$softwareToHashMap = new ConcreteSoftwareToHashMap();
$softwaresToHashMap = new ConcreteSoftwaresToHashMap($softwareToHashMap);
$jsonSoftwaresService = new JsonSoftwaresService($softwaresToHashMap);
$di = new DependencyInjection($softwaresRetrieverCriteriaBuilderFactory, $xmlSoftwaresRepository, $jsonSoftwaresService);

This start-up code is rather small. If you build a large application, your start-up code can become much heavier than this. Needless to say, this results in some difficult to maintain code.

To solve this problem, we need a dependency injection application that reads an XML file and creates all the necessary objects needed to launch the application. The objects would then be serialized and written to a file. The start-up code would then simply read that file and directly create the objects. This makes your start-up code as simple as:

$objectFilePath = "/path/to/serialized/object/file";
$di = unserialize(file_get_contents($objectFilePath));

Open Source Dependency Injection Software

Most companies do not have much budget to create tools, such as a dependency injection framework. You can, however, find many free and open source solutions around the web. Symfony2 uses a very solid DI component that is based on Java Spring. However, I will cover programming a dependency injection solution in the near future, if that interests you. Stay tuned!


PHP Devs and Dependency Injection

I don’t want to generalize, but, due to its popularity, many PHP developers are hobbyists, who love to mix PHP and HTML.

These developers normally don’t plan their project; they just want to write code quickly to “get things done.”

I believe that hiring these types of developers is the worst thing a manager can do. By stressing the importance of dependency injection, you can make these “hackers” disinterested in your company, while, at the same time, enticing good developers to work for you company. In other words, your project will attract good senior developers, which is the most important resource a software development company could acquire!


When to Use Dependency Injection

Dependency injection is most useful, when working on long-term projects.

From my experiences, dependency injection is most useful, when working on long-term projects – projects that are actively developed and maintained over a long period of time. This greatly reduces your costs and attracts the best developers. But, as I mentioned before, if you need a demo application to get a contract or some funding, I’d recommend digging right into the code. If you follow that path, however, be aware that the demo will need to be thrown away after you acquire contract and/or funding.


Story Time!

I love stories about developers who want to do the right thing, but their co-workers want to forego best practices and push a project out as fast as possible. What are your thoughts on dependency injection? An over-complication, or a requirement for any sustainable application?

Expressive Tests with Hamcrest

$
0
0

Hamcrest is a set of matchers for writing more expressive code. It just so happens that these matchers are especially useful when writing tests. In this article, we’ll look at Hamcrest for PHP.


What is Hamcrest?

Every Hamcrest matcher helps you write tests that read very naturally.

Hamcret’s expressiveness originated with JMock, but it wasn’t until the addition of the unique assertThat() method that it was refactored into a self-contained library and independently usable in testing frameworks.

After its initial Java adoption, Hamcrest implementations in several programming languages became available. JUnit, RSpec and other testing frameworks implement native Hamcrest syntax, removing the need to explicitly include any libraries. Due to Hamcret’s fast adoption, testing frameworks were re-categorized to the following:

  • First generation testing frameworks were very basic, having a single assert() method with usage like: assert(x==y). Programmers had difficulties writing expressive and well organized tests. It also required programming knowledge to understand more complex conditions and made writing more difficult.
  • Second generation testing frameworks, like PHPUnit, offer a large set of different assertions. These frameworks extracted the action or predicate from the parameters (x == y) into the names of the assertions, such as: assertEquals($expected, $actual). This made tests more expressive and made it easy to define custom assertion functions.
  • Third generation testing frameworks use a single assertion method (assertThat()) in conjunction with expressive matchers, making assertions read like English sentences: assertThat($calculatedResult, equalTo($expectedResult)) in contrast with assertEquals($expectedResult, $calculatedResult).

Using Hamcrest matchers can also help in other ways; you can write your custom matchers and use them inside the assertThat() function. Hamcret also provides much more information when something goes wrong. Instead of an obscure message like “Expected value is not True”, Hamcrest errors actually tells all values involved with the test–that is, both expected and actual values. The matchers also allow flexible assertions, so tests do not fail after making small modifications that should not break the test. In other words, fragile tests are more robust.


Installing Hamcrest for PHP

There are several ways to install Hamcrest. The two most common involve using PEAR or downloading the source code. At the time of this writing, Hamcrest for PHP is not yet available through Composer.

Use PEAR

Using PEAR to install Hamcrest is easy. Simply run the following commands:

pear channel-discover hamcrest.googlecode.com/svn/pear
pear install hamcrest/Hamcrest

Make sure to check that you have PEAR’s installation folder in you global path. This makes it easy to include Hamcrest in your tests.

Download Source Archive

You can always download the latest version of Hamcrest from the project’s download page and use it like any third party PHP library.


Our First Test

Let’s first ensure we have a working skeleton test with Hamcrest enabled. Create a project in your favorite IDE or code editor and create a test file. I just created a new project in NetBeans with a folder called Test as the main folder. Inside this folder is an empty file called HamcrestMatchersForPHPTest.php. This will be the test file, and its contents are the following:

require_once 'Hamcrest/Hamcrest.php';
class HamcrestMatchersForPHPTest extends PHPUnit_Framework_TestCase {
	function testHamcrestWorks() {
		assertThat('a', is(equalTo('a')));
	}
}

The first line includes the Hamcrest library. Please note that it is with capital “H” for both the folder and the file name. Hamcrest’s official readme file contains a typo.

Next, our only test, testHamcrestWorks(), asserts that a is equal to a. Obviously, this is a passing test.

Passing Test

This first simple example is natural to read. Assert that ‘a’ is equal to ‘a’. It almost needs no explanation.

The only assertion method we will use in our tests is assertThat(). The matcher is() is just syntactic sugar; it does nothing except construct your sentence. Finally the matcher equalTo() compares the first parameter to assertThat() with value supplied to equalTo(). This test effectively translates to 'a' == 'a'.


Comparing Numbers

Let’s start with a simple example:

function testNumbers() {
	assertThat(2, equalTo(2));
	assertThat(2, lessThan(3));
	assertThat(3, greaterThan(2));
	assertThat(2, is(identicalTo(2)));
	assertThat(2, comparesEqualTo(2));
	assertThat(2, is(closeTo(3, 1)));
	assertThat(2, is(not(3)));
}

You can write your custom matchers and use them inside the assertThat() function.

This code introduces new matchers; the first two are lessThan() and greaterThan(). These matchers are the equivalent to the “<” and “>” comparison operators.

The identicalTo() provides another means of checking equality. In fact, this is the equivalent of the === operator, whereas equalTo() is ==. Another new matcher in this code is comparesEqualTo(), effectively performing the equivalent of !($x < $y || $x > $y). In the above code, both $x and $y are the value 2 (so the test passes).

One of the most interesting matchers is closeTo(). It accepts two arguments: the target value and the allowed difference, respectively. This example checks if 2 is close to 3 by a maximum of 1. This is obviously correct, and the assertion passes.

Finally, the last assertion is just a simple negation combined with is(). This obviously asserts that 2 is not 3.

Combined Number Matchers

Hamcrest also provides matchers that equate to the <= and >= comparison operators. They’re aptly named lessThanOrEqualTo() and greaterThanOrEqualTo(), and they’re used like this:

function testNumbersComposed() {
	assertThat(2, lessThanOrEqualTo(2));
	assertThat(2, lessThanOrEqualTo(3));
	assertThat(3, greaterThanOrEqualTo(3));
	assertThat(3, greaterThanOrEqualTo(2));
	assertThat(2, is(atMost(2)));
	assertThat(2, is(atMost(3)));
	assertThat(3, is(atLeast(3)));
	assertThat(3, is(atLeast(2)));
}

Hamcrest also provides the atMost() and atLeast() matchers. The lessThanOrEqualTo() and atMost() matchers are identical. They both equate to $x <= $y. Naturally, the greaterThanOrEqualTo() and atLeast() perform the exact opposite, checking for $x >= $y.


Working with Strings

Hamcrest also provides several matchers for working with strings. Here are some examples:

function testStrings() {
	assertThat('this string', equalTo('this string'));
	assertThat('this string', equalToIgnoringCase('ThiS StrIng'));
	assertThat('this string', equalToIgnoringWhiteSpace('   this   string   '));
	//assertThat('this string', equalToIgnoringWhiteSpace('thisstring'));
	assertThat('this string', identicalTo('this string'));
	assertThat('this string', startsWith('th'));
	assertThat('this string', endsWith('ing'));
	assertThat('this string', containsString('str'));
	assertThat('this string', containsStringIgnoringCase('StR'));
	assertThat('this string', matchesPattern('/^this\s*/'));
}

I recommend you use the more expressive matchers whenever possible...

Obviously, the equalTo() and identicalTo() matchers work with strings, and they behave exactly as you would expect them to. But as you can see, Hamcrest provides other string-specific equality matchers. As their names imply, the equalToIgnoringCase() and equalToIgnoringWhiteSpace() matchers match strings by ignoring case and whitespace, respectively.

Other matchers, such as startsWith() and endsWith(), check if the specified sub-string is at the beginning or end of the actual string. The containsString() matcher checks if the string contains the supplied sub-string. The containsString() matcher can also be extended with containsStringIgnoringCase(), adding case insensitivity.

The matchesPattern() matcher incorporates regular expressions to find a match in the string. You can use any regular expression, and in many cases, this solution is necessary in more complex strings. In any case, I recommend you use the more expressive matchers whenever possible and only resort to regular expressions if absolutely necessary; doing so makes your code more readable by everyone.

Matching Empty Strings

It's common to test if a string is empty. Hamcrest has you covered.

function testStringEmptiness() {
	assertThat('', isEmptyString());
	assertThat('', emptyString());
	assertThat('', isEmptyOrNullString());
	assertThat(NULL, isEmptyOrNullString());
	assertThat('', nullOrEmptyString());
	assertThat(NULL, nullOrEmptyString());
	assertThat('this string', isNonEmptyString());
	assertThat('this string', nonEmptyString());
}

Yes, there are many matchers for checking if a string is empty. Each variant has a version with "is" in front of it. Essentially, emptyString() and isEmptyString() are identical, and the same is true for the other matchers. The nonEmptyString() and isNonEmptyString() matchers can also be written like this:

assertThat('this string', not(isEmptyString()));
assertThat('this string', is(not(emptyString())));
assertThat('this string', is(nonEmptyString()));

But of course, those variants can add extra verbosity, making it more difficult to understand the code at first glance.


Inclusions and Exclusions

Here are some nice approaches to determine whether or not a variable belongs to a group:

function testInclusionsExclusions() {
	assertThat('val', is(anyOf('some', 'list', 'of', 'val')));
	assertThat('val', is(noneOf('without', 'the', 'actual', 'value')));
	assertThat('this string', both(containsString('this'))->andAlso(containsString('string')));
	assertThat('this string', either(containsString('this'))->orElse(containsString('that')));
	assertThat('any value, string or object', is(anything()));
}

These examples use strings, but you can use these matchers with variables like objects, arrays, numbers, etc. The anyOf() and noneOf() matchers determines whether or not the expected variable resides in the provided list of values.

The other two matchers, both() and either(), are commonly used with the andAlso() and orElse() modifiers. These are equivalents of:

assertThat((strpos('this string', 'this') !== FALSE) && (strpos('this string', 'string') !== FALSE));
assertThat((strpos('this string', 'this') !== FALSE) || (strpos('this string', 'string') !== FALSE));

Finally, anything() matches... well, anything. It has an optional string parameter for meta data purposes, helping anyone reading the test to better understand why an assertion should always match.


Arrays

The array matchers are probably the most complex and useful matchers provided by Hamcrest. The code in this section provides a list of tricks to make complicated array-based assertions change into code that reads like well written prose.

Please Note: I make no difference between arrays and hashes in these examples. I only talk about arrays, but everything applies to hashes as well.

Array Equality

function testArrayEquality() {
	$actualArray = array(1,2,3);
	$expectedArray = $actualArray;
	assertThat($actualArray, is(anArray($expectedArray)));
	assertThat($actualArray, equalTo($expectedArray));
}

These methods highlight different ways to compare the equality of two arrays. The first version uses the misleadingly named anArray() matcher. It actually it compares the two arrays element by element. On failure, only the first set of unequal elements are displayed in the error message.

The second version, using equalTo(), also compares each element in the arrays, but it outputs both arrays in their entirety on failure. Naturally, the length of your arrays will determine which matcher you use. Reading large arrays can be difficult.

Partial Array Matches

In many cases, we simply want to check if an array contains certain elements. Hamcrest has us covered.

function testArrayPartials() {
	$actualArray = array(1,2,3);
	assertThat($actualArray, hasItemInArray(2));
	assertThat($actualArray, hasValue(2));
	assertThat($actualArray, arrayContaining(atLeast(0),2,3));
	assertThat($actualArray, contains(1,2,lessThan(4)));
	assertThat($actualArray, arrayContainingInAnyOrder(2,3,1));
	assertThat($actualArray, containsInAnyOrder(3,1,2));
}

The hasItemInArray() and hasValue() matchers are identical; they both check if the provided value or matcher result exists in the array. Providing a value as an argument is equivalent to using equalTo(). Therefore, these are identical: hasValue(2) and hasValue(equalTo(2)).

The next two matchers, arrayContaining() and contains(), are also identical. They check, in order, that every element of the array satisfies the matcher, or that every element is equal to the specified values.

Finally, as you can easily deduce from the above example, arrayContainingInAnyOrder() and containsInAnyOrder() are the same as the previous two matchers. The only difference is that they do not care about the order.

Matching Array Keys

function testArrayKeys() {
	$actualArray['one'] = 1;
	$actualArray['two'] = 2;
	$actualArray['three'] = 3;
	assertThat($actualArray, hasKeyInArray('two'));
	assertThat($actualArray, hasKey('two'));
	assertThat($actualArray, hasKeyValuePair('three', 3));
	assertThat($actualArray, hasEntry('one', 1));
}

The matchers hasKeyInArray() and hasKey() check if the given argument matches any keys in the array, while the last two matchers return true only if both key and value are found. So, a matcher like hasEntry('one', 2); would have failed our test because in our array, at key 'one' we have the value 1 and not 2.

Please Note: It is recommended to use the shorter version (hasKey) when it is obvious from the variable's name that it is an array. Whoever reads your code may be confused about the type of the variable, in which case, (hasKeyInArray) may be more helpful.

Array Sizes

You can easily check the size of an array with three matchers:

function testArraySizes() {
	$actualArray = array(1,2,3);
	assertThat($actualArray, arrayWithSize(3));
	assertThat($actualArray, nonEmptyArray());
	assertThat(array(), emptyArray());
}

The arrayWithSize() matcher checks for a specific size, nonEmtpyArray() checks if the array has at least one element, and emptyArray() verifies that the given array is empty.

Please Note: There are versions of these three matchers if you prefer iterable objects. Just replace "Array" with "Traversable" like this traversableWithSize().


Checking for Value Types

These are the last matchers. You can practically check for any data type in PHP.

function testTypeChecks() {
	assertThat(NULL, is(nullValue()));
	assertThat('', notNullValue());
	assertThat(TRUE, is(booleanValue()));
	assertThat(123.45, is(numericValue()));
	assertThat(123, is(integerValue()));
	assertThat(123.45, is(floatValue()));
	assertThat('aString', stringValue());
	assertThat(array(1,2,3), arrayValue());
	assertThat(new MyClass, objectValue());
	assertThat(new MyClass, is(anInstanceOf('MyClass')));
	// there are a few other more exotic value checkers you can discover on your own
}

These are self-explanatory. Simply provide a value or object, and use one of the easy-to-use matchers to determine its data type.


Conclusions

Hamcrest PHP is not extensively documented in the official documentation, and I hope this tutorial helped explain the matchers it provides. There are a few matchers not listed in this tutorial, but they are very exotic and rarely used.

Every Hamcrest matcher helps you write tests that read very naturally.

If they are not enough for you, you can add your own matchers for your whatever situation you need them for. I hope you enjoyed this tutorial, and thank you for reading.

Best of Tuts+ in November 2012

$
0
0

Each month, we bring together a selection of the best tutorials and articles from across the whole Tuts+ network. Whether you’d like to read the top posts from your favourite site, or would like to start learning something completely new, this is the best place to start!


Psdtuts+ — Photoshop Tutorials


Nettuts+ — Web Development Tutorials


Vectortuts+ — Illustrator Tutorials


Webdesigntuts+ — Web Design Tutorials


Phototuts+ — Photography Tutorials

  • The Basics of Better Moon Photography

    The Basics of Better Moon Photography

    It controls the tides and even some people’s moods. It watches over us at night and sometimes makes a guest appearance during the day. It’s our only non-man-made satellite and some people still think it is made of cheese.

    Visit Article

  • Your Guide to Stunning Surf Photography

    Your Guide to Stunning Surf Photography

    A surfer performing a maneuver on a beautiful wave is always a photographic inspiration. Every wave is different and every surfer has his or her own unique style. As a photographer, the elements of surfing make it both enjoyable and exciting to capture.

    Visit Article

  • How to Shoot a Professional, Creative Low-Key Self Portrait

    How to Shoot a Professional, Creative Low-Key Self Portrait

    Sometimes when looking at a beautiful black and white portrait, you think to yourself, “what a shot, I wish I could have one!” In fact, you do not have to be a professional photographer or use a professional service to have stunning shots. You can do it by yourself and all you need is some creativity, a little ingenuity and artistry.

    Visit Article


Cgtuts+ — Computer Graphics Tutorials

  • Modeling, Texturing & Rendering for Production: Part 1 Concept Design – Tuts+ Premium

    Modeling, Texturing & Rendering for Production: Part 1 Concept Design – Tuts+ Premium

    In production, speed is everything. Artists need to adapt tools and techniques that allow for a workflow that’s not only fast and efficient, but one that yields excellent results at the same time. In our latest Tut+ Premium series Modeling, Texturing & Rendering for Production you’ll follow profession CG artist Mile Eror as he shares his personal workflow and discusses the tools, techniques and general approach he takes when working on a project.

    Visit Article

  • Building a Steampunk Inspired Light Saber in 3ds Max, Part 1

    Building a Steampunk Inspired Light Saber in 3ds Max, Part 1

    In this tutorial we are going to create a stylized high poly model of a steampunk light saber. We are going to use a ton of different modeling techniques to create the different shapes of the model, as well as some techniques that will allow us to group and connect the different elements together into single pieces of geometry.

    Visit Article

  • Working with Advanced Reflections in UDK

    Working with Advanced Reflections in UDK

    In this tutorial we’ll learn how to setup both a Dynamic (realtime) and a Static reflection material in Unreal Development Kit, and create a Parameter Switch to switch from Dynamic to Static reflections, or vice versa in UDK. For the tutorial I’ll be using the February 2011 version of UDK.

    Visit Article


Aetuts+ — After Effects Tutorials


Audiotuts+ — Audio & Production Tutorials

  • Quick Tip: How To Sound Like Minimalist Composer Steve Reich

    Quick Tip: How To Sound Like Minimalist Composer Steve Reich

    This quick tip describes the common composing techniques, provides links to examples and gives suggestions on how you can do it yourself.

    Visit Article

  • Editing And Using .REX Files

    Editing And Using .REX Files

    Would you like to edit clean transients in a flexible, non-destructive way? In this video tutorial, Mo Volans teaches you how to use .REX files in Propellerhead’s ReCycle to do just that. You’ll also learn how easy it is to graphically edit your loops in Reason’s Dr.Octo Rex. Enjoy!

    Visit Article

  • Quick Tip: 10 Quick Editing Tips

    Quick Tip: 10 Quick Editing Tips

    Usually, editing is overlooked as a part of audio production. It’s not that engineers don’t know what it is, it’s just that it’s looked at the same way a chef would look at doing the dishes. It’s boring. It’s tedious and tiresome to go through each and every track to spot the glitches, pops and abnormal volume changes.

    Visit Article


Wptuts+ — WordPress Tutorials


Mobiletuts+ — Mobile Development Tutorials


Gamedevtuts+ — Game Development


Mactuts+ — Mac & OS X

  • How to Upgrade Your MacBook Pro to an SSD

    How to Upgrade Your MacBook Pro to an SSD

    Following on from the previous post on upgrading your MacBook Pros RAM, today we have a tutorial on how to fit your Mac with a speedy Solid-State Drive (SSD). Upgrading RAM was a relatively cheap way to increase the speed of your Mac – it did so by making your Mac run smoother if you have multiple applications open at the same time and generally allowing your Mac to do more without slowing it down – but adding an SSD will be make your laptop run faster than it ever has. The difference can be so large, youd be forgiven for thinking youve got a whole new machine.

    Visit Article

  • How to Own Apple Products Without Getting Screwed

    How to Own Apple Products Without Getting Screwed

    Have you ever purchased an awesome new Apple product only to find out almost immediately that there’s a newer and better version right around the corner, or worse, already announced? Doesn’t it make you want to pull your hair out when you fork over hundreds or even thousands of your hard earned dollars and still quickly find yourself a generation of technology behind? Today, we’re going to look at a few simple strategies that you can use to avoid that “screwed over” feeling that seems inherent in owning Apple products.

    Visit Article

  • How to Increase the Performance of Your Wireless Network

    How to Increase the Performance of Your Wireless Network

    Wireless networks are so ubiquitous that many of us rarely pay any attention to their setup. For a lot of us, as long as we can get on the Internet, then thats all we need. However, its likely that your wireless network isnt anywhere near as good as it can be. With some simple tweaking, and some great utilities from the Mac App Store, we can make sure it’s the best in the neighborhood!

    Visit Article


Crafttuts+ — Craft & Handmade

  • Knitting Fundamentals: How to Cast-On

    Knitting Fundamentals: How to Cast-On

    Knitting has been gaining quite a bit popularity over the past few years. Knitting enthusiasts are no longer just grandmothers who make sweaters for Christmas (although those gals are out there too, love you Granny!). It’s true, knitting is now common amongst women and men of almost all age ranges, and many of those who don’t know how to knit are starting to express an interest in learning.

    Visit Article

  • Make Your Own Hobbiton Miniature Garden

    Make Your Own Hobbiton Miniature Garden

    Lord of the Rings fans rejoice; the world premiere of The Hobbit: An Unexpected Journey screened in Wellington today and its only a matter of weeks before the rest of us get to see it for ourselves. Ive always wanted to make a themed miniature garden, so I thought I might get my Tolkien geek on for Craftuts+ and make a Hobbiton-themed miniature garden.

    Visit Article

  • Make a Colourful Christmas Wreath and Garland With Fabric Strips

    Make a Colourful Christmas Wreath and Garland With Fabric Strips

    Here’s a Christmas craft where you can use all those tiny bits of fabric you have left over from other craft projects. Gather all your pieces together and use them to make a festive wreath and garland decoration for your home.

    Visit Article


FreelanceSwitch — Freelance Jobs & Information

  • Facebook for Freelancers: Groups, Pages or Profiles?

    Once you’ve decided Facebook is right for you as a freelancer, you’re ready to put together an action plan on how you’ll use it to promote your business and market your services.
    Your next step is to decide whether to promote your business with a Profile, a Group or a Page. These are the three set-ups Facebook offers, and each has its advantages and disadvantages.

    Visit Article

  • 15 Ways New Freelancers Can Use Social Media to Boost Business

    Social media is a great way to connect with new people, including potential freelance clients. Having a presence on one of the hugely trafficked social-media platforms can also help your own freelancer website rank better in search and help you get found by prospects.

    Visit Article

  • How to Craft Your Portfolio to Your Target Market

    Your portfolio may be the first introduction potential clients have to you: it tells them what type of projects you do well at and what kind of work you want to land — even if that’s not the message you intended to convey. At the most basic level, the people who view your portfolio will assume that you don’t do anything beyond what is included in that portfolio.

    Visit Article

A Peek At Brackets

$
0
0

Brackets is an interesting new editor on the scene that leverages HTML, CSS, and JavaScript to the max: it’s built with those very technologies! What this means is that, particular for frontend developers, the sky’s the limit, when it comes to configuration and extensibility.

In this video, I’ll go over some of what I consider to be the most innovate features in this new editor, including live previews, CSS highlighting, and quick edits.


Choose 720p for best clarity, or Download the video.

Best Practices When Working With JavaScript Templates

$
0
0

Maybe you don't need them for simple web apps, but it doesn't take too much complexity before embracing JavaScript templates becomes a good decision. Like any other tool or technique, there are a few best practices that you should keep in mind, when using templates. We’ll take a look at a handful of these practices in this tutorial.


1. Underscore for Simple, Handlebars for Complex

If you need something with a bit more zest, might I recommend Handlebars?

First things first: unless you're John Resig, you most likely want to choose a well-tested library to offer your template functionality. While the options are nearly endless, there are two really good options, depending on the complexity of your project.

If the project is relatively simple, you can use Underscore.js. For the most part, this library offers functional programming utilities, but it does have a _.template method that couldn't make things easier. By default, it uses the ERB-esque <%= %> delimiters, but that can easily be modified. The beauty of this solution is that any project that requires templates will likely have Underscore loaded already, simply due to its sheer general usefulness. To learn more about Underscore, check out Siddharth's comprehensive tutorial right here on Nettuts+.

If you need something with a bit more zest, might I recommend Handlebars? With many useful block expressions (such as #each for looping and #if for conditionals) and the ability to register your own helper functions, Handlebars will give you everything you need to create even the most complex of templates.

If you're not familiar with Handlebars, Gabriel Manricks has got you covered in this tutorial.

Of course, there are other template libraries out there; feel free to check them out! I only recommend these two because I enjoy and use them myself. They also tend to be the most popular offerings in the community.

Handlebars
Handlebars is an excellent JavaScript templating engine.

2. Create Template Helper Functions

Most template libraries will make the data object that you pass into the template function the context.

There will be times, when the data that you are inserting into a template won't quite be formatted in the way you prefer. In these situations, you'll need to create custom functions to format it. If you're using something like Handlebars, you can easily register a helper function; but other solutions, like Underscore, don’t offer that functionality. You'll have to roll your own.

The reason why this isn't as simple as it might sound is because most template libraries will make the data object that you pass into the template function the context, or the value of this. Therefore, the function needs to be part of this object. There are a couple of ways to do this. The primary way is to to add the function to the data object before passing it to the template function. Here’s an example:

// assume data object and template function
data.formatPrice = function (priceInCents) {
    return "$" + (priceInCents / 100).toFixed(2);
}
var html = template(data);

This is great for one-off situations, but it's possible that you'll have multiple sets of templates, each which needs its own set of helper functions. What I like to do in these cases is wrap the template function in another function that will apply the helpers to the data object.

var productTemplate = function (data) {
    var template = _.template("the template string");
    data.helperFunction1 = function () { return "whatever" };
    return template(data);
};

There are several ways to improve this (you might start with caching the "raw" template function outside this function, probably via a closure), but that's the basic idea. Now, you can simply pass your data to that productTemplate and have access to your helper functions.


3. Store Templates in Their Own File

There are several alternate solutions that might be better, especially in more complex scenarios.

All JavaScript templates obviously start out as text. The most popular (and natural) place to store them is within your HTML document – usually in a script tag with an alternate type attribute, so that the browser doesn't attempt to execute them. It's fairly easy to grab the innerHTML attribute of the script tag and pass it to the template-creating function, when you're ready.

However, this isn't the only way to do it; in fact, it might not be the optimal way. There are several alternate solutions that might be better, especially in more complex scenarios.

The first alternative is to store them all within a JavaScript file. Of course, this means that your templates will be stored as strings instead of the more readable indented HTML, but stick with me for a second! First, for templates that are longer than a single line (most templates), you don't have to use an unwieldy, wrapping string. Instead, try something like this:

Templates = {};
Templates.contactEntry = ["<h1> {{fullName}} </h1>","<ul>","<li> Email: {{email}} </li>","<li> Phone: {{tel}} </li>","</ul>"
].join("\n");

Storing a template in an array like this makes it much easier to handle. Using syntax like this, you can easily store all your templates in their own JavaScript file, and have that file loaded onto the page before you need the templates. And of course, you don't have to keep them all within a single Template object, but it keeps things organized. That Templates object could even be a property on your global application object (as in, MyApp.Templates).

But wait, there's more (to coin a phrase). You can convert all of your templates to their respective template functions in a single loop:

for (var tmpl in Templates) {
    if (Templates.hasOwnProperty(tmpl) {
        Templates[t] = _.template(Templates[t]); // Underscore example
    }
}

If you're using AMD in your application, this method will still work; just put that in a templates module that returns that Templates object. However, many AMD solutions have a text plugin that lets you load plain text files; instead of the normal module object, you'll get a string in return. If you're using the RequireJS library, you'll have to include the text.js plugin in the same directory as the require.js file. Then, you can do something along the lines of:

require(["text!templates/document.html"], function (documentTemplate) {
});

That documentTemplate parameter will be a string containing whatever contents is in that templates/document.html file. When doing it this way, you won't be able to put multiple templates into one file, unless you want to manipulate that string.


4. Precompile Your Templates

If using the Asset Pipeline in a Rails app, take advantage of Sprockets to pre-compile template functions.

If you think about it for a second, there's some extra work done by the browser every time you create a template. Usually, that template starts out as a string that you pass to a template-creating function. That function returns another function, which you can pass the data to and receive HTML from. The extra work is the “creating-the-template-function” part; there's no reason why this can’t be done before the JavaScript is sent to the client. Preferably, you could put add this work to your build process, along with minifying your CSS and concatenating your JS.

Unfortunately, pre-compiling JavaScript templates isn't quite as simple as minifying or concatenating… at least, not just yet, probably due to the many ways to create templates. If you're using Grunt or Yeoman, you can look up plugins (like this one) on the Grunt website. If you're using the Asset Pipeline in a Rails app, you can take advantage of Sprockets to pre-compile your template functions.

Oh, and if you're adventurous (and a Tuts+ Premium subscriber), you can join me as I precompile templates from scratch in my Advanced Backbone Patterns and Techniques course.


5. No Evaluation in Templates

No evaluation in templates.

Not too long ago, while researching for another project, I came across an interesting idea regarding JavaScript templates in the excellent book Recipes with Backbone. It’s since become a best practice in the community: no evaluation in templates. Of course, interpolating variables is, strictly speaking, evaluation, but what I'm more referring to here is logic code. You can put whatever JavaScript you'd like inside of the delimiting tags, but it can easily get out of hand. We all know that it’s considered a best practice to keep your HTML, CSS, and JavaScript separate; this makes it easier to keep track of the code and spot errors, when necessary. The same is true for templates: they should be a place for interpolating values only. Any logic or data transformation should be performed outside the template.

Of course, how far you go with this idea is up to you. You might decide that looping inside your templates is okay; you might have a template like this:

<h1> My List </h1><ul id="myList"><% list.forEach(function (item) { %><li> <%= item.name %> </li><% }); %></ul>

Or, you might instead choose to loop outside your templates by creating a wrapper template, and then looping over items, rendering a sub-templates, and inserting them into the wrapper template. You might end up with two templates like this:

The wrapper template:

<h1> My List </h1><ul id="myList"></ul>

The sub-template:

<li> <%= name %> </li>

Of course, this separated method makes for a bit more code, but you’ll find it worth the effort in the long run.

Along these lines, it's a good practice follow the lead of the framework or library you're using. For example, I've found that, when using Backbone with Underscore templates, it is easier to use outside loops and sub-templates: Underscore's minimal template functionality doesn't offer any looping syntax, and Backbone's render method is a great place to do that looping and inserting the sub-templates. However, when using Meteor, which builds in Handlebars templates, it's much easier to loop inside the templates with an #each block; (and use sub-templates, too, if you want).


6. Bind Data to the Templates

Learn more about Backbone.stickit at Tuts+ Premium.

This won't always be applicable, but, in some cases, it can be really helpful to make your templates update automatically, when the data they are displaying changes. I like this idea a lot, because it allows even the UI of your application to be completely data-driven: when a model attribute updates, the UI updates with it. This is the basic principle behind tools, like Knockout.

While you could probably roll this functionality on your own without too much trouble, all the popular frameworks have it built in. For example, in Backbone, a template's initialize function might include some custom event listeners, like so:

this.model.on('change', this.render, this);

This way, whenever a model attribute changes, the template's render function will be called and the template re-rendered. Alternatively, you can use a plugin, like backbone.stickit, which will manage the bindings for you. If you're working with Meteor and using one of its reactive data sources, you'll get this binding for free – no extra work necessary. I'm not familiar enough with any other framework to know exactly how they do it, but any framework worth using should have a similar feature.


7. Simplify Your Templates

Very quickly, your templates can get out of hand and become unwieldy.

If you aren't careful, very quickly, your templates can get out of hand and become unwieldy. This is why it's always a good idea to limit your templates to a reasonable size. If you make them too large, they'll be more difficult to update, and won't allow for a good separation of the code. On the other hand, if they’re too small, they'll cost too much for what they bring, and will subsequently slow down your app.

This is why it’s important to find a happy medium. Approach your templates in the same way that you write your JavaScript or CSS code: make it modular. Yes, each UI "chunk" or widget should have it's own template, but don't forget about sub-templates. They're useful, when smaller units of a widget have complex layouts or states, as well as when they have multiple events, but remember that they can be a double-edged sword. Don't use them unless you have a good reason to.


8. Don't Use 'em if You Don't Need 'em

Finally, remember that JavaScript templates is just one more tool in your box; and, sometimes, it simply isn’t the right one for the job. Don't use templates where you don't need them. Use your head: there may be other situations, when a template is not the best tool.


Conclusion

We'll, those are my best tips for using JavaScript templates, but perhaps you can think of a few more! If so, please share them in the comments below, so that we can continue the discussion.

How to Make Nettuts+ Your Full-Time Job

$
0
0

Though it’s getting better, there’s no denying the fact that the global economy has been in a slump for some time now. As a result, many businesses have folded or drastically cut down on costs. Well, if you happen to be in need of work, there’s a variety of ways that you can make a healthy income helping us teach, here at Nettuts+. More details after the jump.


$800 - Write Tutorials

As you may know, we post new content daily at Nettuts+. This means, virtually at all times, we’re in need of new, energetic writers to dig into the latest technologies and brain-dump their findings for our readers!

We pay regular writers $200 per article. So, if you sit down for a few hours each week and write one article, you can expect to earn an extra $800 a month, U.S.


$900– Premium Articles

In addition to Nettuts+, we also offer a Premium program, where we publish exclusive and much more in depth content for the subscribers who help support Tuts+. In general, we pay double for this sort of content.

Again, if you write one Premium tutorial every other week, it’s possible to earn, give or take, an extra $900 per month.

View an example of an in depth, Premium tutorial.


$3500 – Record Courses

Finally, at Tuts+ Premium, we’re bumping up to releasing a minimum of fifteen full courses every month. To handle that kind of publishing schedule requires a great deal of instructors.

A course is a set of screencasts on one subject. If a Nettuts+ tutorial is akin to a magazine article, then a Premium course would be the textbook. Here’s a recent example of one of our courses on Backbone.

If you’re worried about screencasting, don’t: we can teach you! As long as you’re willing to learn how (it’s fairly easy), and feel that you have a solid understanding of how to teach others, this would be a fantastic way to make an additional $3500 each month, as one of our staff instructors.


A Full-Time Gig

Assuming that you take each of the jobs listed above (like I, and some of the other staff writers here do), you’ll make $5200 per month. Don’t think that’s all doable in one month? It absolutely is; in fact, in addition to being the editor of Nettuts+ and a producer for Tuts+ Premium, I do all three of the jobs noted above. You can too – just as long as you enjoy it.


How to Apply

Firstly, it’s important for me to note that, when opportunities like this come up, folks tend to assume that there will be hundreds upon hundreds of applications. That simply isn’t the truth. In reality, I’m expecting less than fifteen usable applications. We’re hiring multiple people, not just one.

If you’d like to apply, here’s what I need:

  • Email Me: Send me a short email (jeffrey[at]envato[dot]com), and set the subject to “Application.” Who are you? What’s your area of expertise? Are you on Twitter? A few sentences will do.
  • Sample(s): Provide me with a sample of your writing. It can be a link to your personal blog, or an article that you’ve written for a different website.
  • Screencast: If you’d also like to record courses for Tuts+ Premium, I’ll need a screencast sample as well. If you’ve never done this before, for now, visit Screenr.com, and record (through your computer’s built in mic is fine) a 3-5 minute screencast on any web development topic of your choice. I care much less about the content, and more about listening to how you explain a particular concept. If you can do that well, we can help with quality/sound improvements! Include a link to this video with your introductory email to me.

And that’s it! We’ll get back to you as soon as we can. Please note that special attention will be given to those who:

  • Speak and write English well. This is the single most important piece of your application.
  • Know how to explain complicated concepts. Some of the most intelligent developers I know don’t have the first clue as to how to teach effectively. Do you?
  • Have prior experience. Do you frequently write on your blog? Have you contributed to Smashing Magazine, or another similar community? If so, you’ll move to the top of our list!
  • Have lots of experience! If your skill-set ends with HTML, CSS, and basic JavaScript, you might not be the best fit. We’re looking for developers who have years of experience, and enjoy spending their free time learning about (or deciding) what’s next in the industry!

If you have any questions, let me know below, and I’ll do my best to answer them. Otherwise, if you’re hired, you’ll be spending your days transforming yourself into a better developer, and teaching the latest tricks and techniques to millions of readers every month.

So You Want to Accept Credit Cards Online?

$
0
0

Until recently, accepting credit cards on a website was expensive and complicated. But that was before Stripe: a radically different and insanely awesome credit card processing company. Today, I’ll show you how to start accepting cards in 30 minutes or less – without spending a dime.

June, 2012

The Way Things Used To Be:

Without Stripe, accepting credit cards on a website is a massive undertaking. First, you need to open a “merchant account”, which is like a regular bank account, but with more fees. Then, you need a “payment gateway” – because credit card processing apparently takes place in a separate dimension where bankers rule with an iron fist and Lindsey Lohan has a successful acting career. And then come the leeches: $25 monthly fee. $99 setup fee. $50 annual fee. $0.35 failed transaction fee (YOU pay when your customer’s card fails to go through!). $0.25 + 2.0% successful transaction fee. $2.00 batch fee. $5.00 daddy-needs-a-new-porsche fee. It’s ridiculous. The most popular card processor is Authorize.net, and the folks at that company (and its many resellers) spend every day thinking of new, ridiculous ways to take your money.


Enter Stripe

Setup takes about five minutes.

Unfortunately, it is illegal to kidnap the CEO of Authorize.net, slather him in barbecue sauce and drop him into a pit of honey badgers. But, you can do the next best thing: don’t use his service. Switch to Stripe. You won’t need a merchant account or payment gateway. Stripe will deposit money into any bank account you like. There are zero fees. Setup takes about five minutes. (Yes, seriously.) And you pay exactly one thing: 2.9% + $0.30 on each successful card transaction. (So, if you’re selling something for $30, you keep $28.83, and Stripe gets $1.17.) The website is simple and intuitive and the staff are super helpful. The only drawback is that Stripe is currently unavailable outside of the United States. (Note: Stripe DOES accept credit cards from overseas; it’s just that you can’t sign up for a Stripe account outside of the U.S.) They’re working on expanding to other countries.

The rest of this tutorial will detail how to implement Stripe on your website with PHP and Javascript (jQuery). The service also has APIs for Ruby, Python, Java and other platforms. Although it might look like there’s a lot of work ahead, there really isn’t; you’ll be up and running in no time. Let’s get started:


Step 0: Install an SSL Certificate

We’re dealing with credit card information, so of course we have to secure the user’s connection to our server. We do this using an SSL certificate and it’s not optional. Not only do users expect to see the “https://” protocol on an order page, Stripe requires it. But don’t worry: implementing SSL is very simple. Almost all hosting providers offer automatic SSL certificate installation. You simply buy the certificate through your provider and they automatically install and configure it for you. You don’t need to do anything else to your site. If your order form is at http://mydomain.com/order.php, you simply send the customer to https://mydomain.com/order.php instead and the connection will be secured with your new SSL certificate. That’s it!

Note: there is one exception. If your order page loads resources such as stylesheets, scripts or images using an absolute (as opposed to relative) URL, you’ll need to make sure those URLs use the “https://” protocol. For example, if you include an image on your secure order page like this, you’ll get a warning in the browser that the page contains both secure and insecure elements:

<img src="http://someremotedomain.com/someImage.jpg">

To fix this, load the image from a secure URL, like this:

<img src="https://someremotedomain.com/someImage.jpg">

You don’t need to worry about this issue for relative urls (such as “../images/someImage.jpg”) because your server will automatically load these items securely.


Step 1: Create an Account

Visit Stripe.com and create a new account. Once you’re past the initial username/password prompt, click the “Your Account” menu in the top right and open the “Account Settings” pane, which is pictured below. First, make sure you set a good “Statement Descriptor”. This is what customers will see on their credit card statements. A good descriptor helps the customer remember what they bought so that they don’t mistake your transaction for fraud and cancel the charge. (When this happens, it’s called a “chargeback” and you’ll pay a $15 fee on top of losing the sale, so make sure your descriptor is set!) Next, specify the bank account to which you’d like your money deposited. You are welcome to use mine. And finally, take a look at the “API Keys” tab. We’ll be using these shortly, so keep them handy.


Step 2: Create Your Payment Form

The next thing we need is a form that our customers fill out to place a credit card order with us. Today, we’ll use this vastly over-simplified PHP page, called “buy.php”:

<!DOCTYPE html><html><head><script src="scripts/jquery.js"></script></head><body><h2>Payment Form</h2><form id="buy-form" method="post" action="javascript:"><p class="form-label">First Name:</p><input class="text" id="first-name" spellcheck="false"></input><p class="form-label">Last Name:</p><input class="text" id="last-name" spellcheck="false"></input><p class="form-label">Email Address:</p><input class="text" id="email" spellcheck="false"></input><p class="form-label">Credit Card Number:</p><input class="text" id="card-number" autocomplete="off"></input><p class="form-label">Expiration Date:</p><select id="expiration-month"><option value="1">January</option><option value="2">February</option><option value="3">March</option><option value="4">April</option><option value="5">May</option><option value="6">June</option><option value="7">July</option><option value="8">August</option><option value="9">September</option><option value="10">October</option><option value="11">November</option><option value="12">December</option></select><select id="expiration-year"><?php
					$yearRange = 20;
					$thisYear = date('Y');
					$startYear = ($thisYear + $yearRange);
					foreach (range($thisYear, $startYear) as $year)
					{
						if ( $year == $thisYear) {
							print '<option value="'.$year.'" selected="selected">' . $year . '</option>';
						} else {
							print '<option value="'.$year.'">' . $year . '</option>';
						}
					}
				?></select><p class="form-label">CVC:</p><input class="text" id="card-security-code" autocomplete="off"></input><input id="buy-submit-button" type="submit" value="Place This Order »"></input></form></body></html>

There are three things to note about the code snippet above.

  1. First, we’ve set the form’s action to “javascript:” rather than providing a path to a server-side script. (You’ll see why in just a minute.)
  2. Secondly, there’s a short snippet of PHP that automatically populates our expiration-year field with the next 20 years so that we don’t have to update that manually in the future.
  3. Thirdly, none of the form fields have a “name” parameter set. This is crucial because it will prevent the value of the field (such as the credit card number) from being sent to our server when the form is submitted. We’ll talk about why this is important in just a minute.

How Much Info Should I Collect?

The only things you absolutely must have to charge a credit card are the card number and the expiration date. But you should always collect at least some additional information. Here’s why: if a customer disputes the charge on their card, you’ll be required to prove that they did, in fact, place an order with you.

The more information you collect, the easier it will be to prove that the customer (as opposed to an identity thief) placed the order on your site.


What’s Next: The Big Picture

Okay, we’ve got SSL installed and a payment form ready to go. Let’s assume we’re going to charge the customer $20.00 for this order. (In reality you’d calculate the total based on what the customer ordered, etc. That’s up to you.) When he fills out the form and presses the submit button, three things happen in this order:

  1. Using Javascript (jQuery), we collect each form field’s value. We pass this information directly to Stripe’s server, using Stripe.js.
  2. Stripe’s server will ensure that the credit card data is well-formed, prepare a transaction and send us back a “single-use token”.
  3. We pass the token to a server-side script on our own server, which contacts Stripe again and triggers the actual charge to the credit card. That’s it!

Why Do It This Way?

Security. The user’s credit card information never touches our own server. We pass it directly to Stripe on the client-side using Javascript. Stripe’s server takes that information and prepares a transaction. The “token” that it sends back to us does NOT contain the credit card details, but DOES contain an ID that lets us trigger the transaction that Stripe has prepared on their end. Thus, we can safely pass the token to our own server without risking the security of the user’s credit card details.

Note: while you can use Stripe without the token process, I strongly discourage it. If you pass the raw credit card details to your own server, you have to be insanely careful to protect them and there are many ways to screw up. For example, server error logs could easily record sensitive information, so you have to scrub them securely and regularly. If you’re on a shared hosting plan, you probably don’t have the control required to do that. Plus, if your server is ever hacked, you might be sued into oblivion by ticked-off customers. And if you do something really stupid like store unencrypted card information in a database, I will personally drive to your house and beat you with a cactus. Play it safe; use the token process.


Step 3: Collect The Form Values

Create a new Javascript file, called “buy-controller.js”. Let’s start coding that file with some basic validation checks:

function showErrorDialogWithMessage(message)
{
	// For the tutorial, we'll just do an alert. You should customize this function to
	// present "pretty" error messages on your page.
	alert(message);
	// Re-enable the order button so the user can try again
	$('#buy-submit-button').removeAttr("disabled");
}
$(document).ready(function()
{
	$('#buy-form').submit(function(event)
	{
		// immediately disable the submit button to prevent double submits
		$('#buy-submit-button').attr("disabled", "disabled");
		var fName = $('#first-name').val();
		var lName = $('#last-name').val();
		var email = $('#email').val();
		var cardNumber = $('#card-number').val();
		var cardCVC = $('#card-security-code').val();
		// First and last name fields: make sure they're not blank
		if (fName === "") {
			showErrorDialogWithMessage("Please enter your first name.");
			return;
		}
		if (lName === "") {
			showErrorDialogWithMessage("Please enter your last name.");
			return;
		}
		// Validate the email address:
		var emailFilter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		if (email === "") {
			showErrorDialogWithMessage("Please enter your email address.");
			return;
		} else if (!emailFilter.test(email)) {
			showErrorDialogWithMessage("Your email address is not valid.");
			return;
		}
		// Stripe will validate the card number and CVC for us, so just make sure they're not blank
		if (cardNumber === "") {
			showErrorDialogWithMessage("Please enter your card number.");
			return;
		}
		if (cardCVC === "") {
			showErrorDialogWithMessage("Please enter your card security code.");
			return;
		}
		// Boom! We passed the basic validation, so we're ready to send the info to
		// Stripe to create a token! (We'll add this code soon.)
	});
});

Next, we need to add this new JavaScript file to the <head> element of our “buy.php” page. We’re also going to add “Stripe.js”, which is a file hosted on Stripe’s server that allows us to contact Stripe from the client-side to pass credit card details and receive our token. (Note that we load Stripe.js using the “https://” protocol!) Modify the <head> element of “buy.php” to look like this:

<head><script src="scripts/jquery.js"></script><script src="https://js.stripe.com/v1/"></script><script src="scripts/buy-controller.js"></script></head>

API Keys

Before we can submit information to Stripe, we have to somehow tell Stripe who we are. To do that, we use a pair of “keys”, which are unique strings that identify our account. To locate these keys, go to your Stripe account settings pane and pull up the API Keys tab, pictured here:

As you can see, there are a total of four keys in two sets: “Test” and “Live”. You use the test set during development so that you can verify your code without actually charging any cards. When you’re ready to deploy a website, simply replace the test keys with the live ones. There are two keys in each set: “publishable” and “secret”. (We’ll use the “secret” key in our server-side script once we’ve received a token from Stripe.) For now, take the publishable test key and add it to the HEAD element of “buy.php” like this:

<head><script src="scripts/jquery.js"></script><script src="https://js.stripe.com/v1/"></script><script>
		Stripe.setPublishableKey('pk_0xT4IHiAt1NxoBDJlE2jfLnG5xWQv');	// Test key!</script><script src="scripts/buy-controller.js"></script></head>

Warning: You MUST include Stripe.js BEFORE you set the publishable key. Additionally, be very careful that you don’t take a website live without switching to the “live” keys! And finally, be absolutely sure to keep your secret keys safe and secret!


Step 4: Request a Token

Back at the bottom of “buy-controller.js”, we’re ready to add the code that requests a token from Stripe. It’s just a few lines:

	// Boom! We passed the basic validation, so request a token from Stripe:
	Stripe.createToken({
		number: cardNumber,
		cvc: cardCVC,
		exp_month: $('#expiration-month').val(),
		exp_year: $('#expiration-year').val()
	}, stripeResponseHandler);
	// Prevent the default submit action on the form
	return false;

The “createToken” function (which is defined in Stripe.js) accepts two parameters. The first is an object with the credit card details. The second is the name of the callback function that will be invoked when Stripe’s server finishes preparing the transaction and returns the token. In this case, our callback function is called “stripeResponseHandler”. Let’s add that function to the top of “buy-controller.js”:

function stripeResponseHandler(status, response)
{
	if (response.error)
	{
		// Stripe.js failed to generate a token. The error message will explain why.
		// Usually, it's because the customer mistyped their card info.
		// You should customize this to present the message in a pretty manner:
		alert(response.error.message);
	}
	else
	{
		// Stripe.js generated a token successfully. We're ready to charge the card!
		var token = response.id;
		var firstName = $("#first-name").val();
		var lastName = $("#last-name").val();
		var email = $("#email").val();
		// We need to know what amount to charge. Assume $20.00 for the tutorial.
		// You would obviously calculate this on your own:
		var price = 20;
		// Make the call to the server-script to process the order.
		// Pass the token and non-sensitive form information.
		var request = $.ajax ({
			type: "POST",
			url: "pay.php",
			dataType: "json",
			data: {"stripeToken" : token,"firstName" : firstName,"lastName" : lastName,"email" : email,"price" : price
				}
		});
		request.done(function(msg)
		{
			if (msg.result === 0)
			{
				// Customize this section to present a success message and display whatever
				// should be displayed to the user.
				alert("The credit card was charged successfully!");
			}
			else
			{
				// The card was NOT charged successfully, but we interfaced with Stripe
				// just fine. There's likely an issue with the user's credit card.
				// Customize this section to present an error explanation
				alert("The user's credit card failed.");
			}
		});
		request.fail(function(jqXHR, textStatus)
		{
			// We failed to make the AJAX call to pay.php. Something's wrong on our end.
			// This should not normally happen, but we need to handle it if it does.
			alert("Error: failed to call pay.php to process the transaction.");
		});
	}
}

This function first checks to see if there was an error creating the token. If Stripe.js fails to return a valid token, it’s usually because the customer entered some of their credit card information incorrectly. They may have mistyped a number or selected the wrong expiration date. Fortunately, the error message that comes along with the response will tell you exactly why the token-creation failed. Stripe guarantees that this error message is suitable for display, but it’s not verbose. Expect to see strings like “invalid expiration date” or “incorrect CVC” rather than full sentences.

If, on the other hand, everything validated and Stripe created a token, we’re ready to hand that token to our server-side script and actually place the charge. In the code above, we’re using jQuery’s Ajax function to do that. We pass the token as well as some information we might want to record in a database: the customer’s name and email. Finally, we need to know how much money to charge the card. We’re assuming $20.00 today, but you’d pass a calculated value from your shopping cart, etc. We throw all of that information into a JSON object and make the Ajax call to our server-side script, “pay.php” (which we’ll create below). Then, we simply look at the response and present the user with a success or error message. You would obviously customize this code to fit your site’s design.


Step 5: Create a Server-Side Script

The only thing left to do is create the server-side PHP script that actually triggers the charge on our customer’s card. First, we’ll need Stripe’s PHP library. To download it, go to Stripe’s website, click the “Documentation” link in the upper right, and then choose the “API Libraries” section. (Or you can go straight there by clicking here.) Scroll down the page until you see the PHP section, which looks like this:

Download the latest version and unzip it. You’ll see two items: “Stripe.php” and a folder named “Stripe” that contains a bunch of other PHP files. Drop both these items into your website’s folder.

Now, create a new file called “pay.php”. We’ll start coding this file with some basic stuff:

<?php
// Helper Function: used to post an error message back to our caller
function returnErrorWithMessage($message)
{
	$a = array('result' => 1, 'errorMessage' => $message);
	echo json_encode($a);
}
// Credit Card Billing
require_once('Stripe.php');	 // change this path to wherever you put the Stripe PHP library!
$trialAPIKey = "oRU5rYklVzp94Ab0RbBTP0soVdlaEtvm";	// These are the SECRET keys!
$liveAPIKey = "4BYrmtvwLb8iiiq9KIdbnRh5KCeSfPsX";
Stripe::setApiKey($trialAPIKey);  // Switch to change between live and test environments
// Get all the values from the form
$token = $_POST['stripeToken'];
$email = $_POST['email'];
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$price = $_POST['price'];
$priceInCents = $price * 100;	// Stripe requires the amount to be expressed in cents

At the top, we have a simple function that we’ll call whenever our script hits an error. It returns a JSON object with two items: “result” and “errorMessage”. This JSON object is sent back to “buy-controller.js” (where we used jQuery’s AJAX function to call this server-side script). There, we can inspect the value of “result” to see what happened. If it’s 0, the payment script completed successfully. If it’s 1, the script hit an error and we can use the “errorMessage” item to report what happened to the user.

Next, we bring in Stripe’s PHP library that we downloaded earlier. There’s nothing too complicated here; just make sure you update the path in the require statement to the relative location of the Stripe PHP library. After that, we have both of our SECRET API keys. We call the “setApiKey” function (which is part of Stripe’s PHP library) and pass it our trial key. Combined with the “publishable” key that we set earlier, Stripe now has all the information it needs to verify our identity and associate this transaction with our account. Of course, when we take the website live, we would switch this statement to use $liveAPIKey!

Warning: Don’t forget to switch to the LIVE API keys when you publish your site! You must switch both the “publishable” key in the HEAD element of “buy.php” and the “secret” key, which appears in “pay.php”, above.

And finally, we grab all the data that we passed from the AJAX call in “buy-controller.js”. Note that Stripe requires us to specify the charge amount in cents. Here, we passed the value in dollars, so we multiply by 100 to convert it to cents.

Actually Charge The Card

Here’s the rest of the code for pay.php:

try
{
	// We must have all of this information to proceed. If it's missing, balk.
	if (!isset($token)) throw new Exception("Website Error: The Stripe token was not generated correctly or passed to the payment handler script. Your credit card was NOT charged. Please report this problem to the webmaster.");
	if (!isset($email)) throw new Exception("Website Error: The email address was NULL in the payment handler script. Your credit card was NOT charged. Please report this problem to the webmaster.");
	if (!isset($firstName)) throw new Exception("Website Error: FirstName was NULL in the payment handler script. Your credit card was NOT charged. Please report this problem to the webmaster.");
	if (!isset($lastName)) throw new Exception("Website Error: LastName was NULL in the payment handler script. Your credit card was NOT charged. Please report this problem to the webmaster.");
	if (!isset($priceInCents)) throw new Exception("Website Error: Price was NULL in the payment handler script. Your credit card was NOT charged. Please report this problem to the webmaster.");
	try
	{
		// create the charge on Stripe's servers. THIS WILL CHARGE THE CARD!
		$charge = Stripe_Charge::create(array("amount" => $priceInCents,"currency" => "usd","card" => $token,"description" => $email)
		);
		// If no exception was thrown, the charge was successful!
		// Here, you might record the user's info in a database, email a receipt, etc.
		// Return a result code of '0' and whatever other information you'd like.
		// This is accessible to the jQuery Ajax call return-handler in "buy-controller.js"
		$array = array('result' => 0, 'email' => $email, 'price' => $price, 'message' => 'Thank you; your transaction was successful!');
		echo json_encode($array);
	}
	catch (Stripe_Error $e)
	{
		// The charge failed for some reason. Stripe's message will explain why.
		$message = $e->getMessage();
		returnErrorWithMessage($message);
	}
}
catch (Exception $e)
{
	// One or more variables was NULL
	$message = $e->getMessage();
	returnErrorWithMessage($message);
}
?>

Surprisingly simple, no? First, we verify that none of our variables are null. Although we don’t need all of them to charge the card, we might want to record this information in a database or use it to email the customer a receipt, so we don’t want to proceed if it’s not available.

Then, we use the “Stripe_Charge::create()” method, which is part of the Stripe PHP library. This is the line that actually charges the user’s card (or attempts to, anyway). The first two items in the array are self-explanatory. The third, “card”, is where we pass the token that we requested from Stripe earlier. The fourth item, “description” is vitally important. Whatever we pass here is what WE will see when we log into Stripe and view our transactions. You should choose something short that identifies the customer who placed this order. An email address is your best bet, as many customers might have the same name.

Why Might The Charge Fail At This Point?

If we were able to successfully get a token from Stripe, why would the charge fail at this point? The answer is that the validation Stripe performed earlier checked only that the credit card data was well-formed; it did not run a transaction through the credit card networks. It may be the case that the customer’s card is over its limit. Or, if it’s a debit card, there may not be enough money in the customer’s account to cover this purchase. It could also be that the credit card company simply flags the transaction as unusual and requires the customer’s approval to let it through (this has happened to me with American Express cardholders). In situations like these, the card will validate correctly when we request a token, but fail when we attempt to actually charge it. Fortunately, Stripe makes it really easy to handle these failures. We simply use try/catch blocks, as you see above.

Charge The Card Last!

If that customer is me, you’re in for a cactus beating.

If your website needs to do things, such as generating a serial number for a software license, you should do that BEFORE you charge the customer’s card. If you charge the card first and then your site fails to generate a serial for any reason, your customer is going to be ticked off. (If that customer is me, you’re in for a cactus beating.) They might even call their credit card company to cancel the charge, which results in a $15 fee to you and the loss of a sale. So play it safe: be sure you have everything ready to go BEFORE you charge the customer!

That’s it! That’s all the code you need to charge a credit card on your website. The rest of the article covers some additional details about using Stripe that you might find handy:


Testing & Debugging

When we’re using the “test” API keys, we can use special credit card numbers that force Stripe to return a certain type of response so that we can thoroughly test our code. Here’s the special numbers:

  • 4242-4242-4242-4242: Simulate a successful card transaction
  • 4000-0000-0000-0002: Force a “card declined” response
  • 4242-4242-4242-4241: Force an “invalid card number” response

In test mode, any 3 or 4-digit CVC number is considered valid. Any expiration date that is in the future is valid. You can pass a two-digit CVC number to test that error case. Likewise, you can pass any date in the past to test the invalid expiration date response. And finally, if you’d like to test the “invalid amount” response, simply pass any non-integer (such as 1.35) as the amount to charge.

For exhaustive information on testing Stripe, you can visit their documentation page.


Subscriptions, Storing Card Info & More

Stripe allows you to do more than one-time charges to a customer’s card. You can set up a subscription that will charge the card a specified amount at an interval of your choosing. The APIs you need to do this are part of Stripe’s PHP library and the website contains excellent documentation that will walk you through the process.

What if you want to store credit card information so that customers don’t have to enter it every time they visit your site? Stripe lets you do that too! You simply create a “customer” object in much the same way that we created a token. This object contains all the sensitive data that pertains to a particular customer. Stripe will securely store this information on their end (which means you don’t have to risk a cactus beating) and you can bill the user whenever you like simply by requesting the appropriate “customer” object, just like we did with the token. Again, all the APIs are part of Stripe’s PHP library and the website will walk you through it.


See it in Action

So that’s it: Stripe in a nutshell! If you’d like to see a working example of what we’ve just covered with a bit more complexity and design, swing by this page and inspect the source. (Hint: it will look familiar.) Otherwise, if you’ve got questions leave a comment below, check out the Stripe Support Page or find me on Twitter: @bdkjones. Thanks and good luck!


PrestaShop Theming Explained

$
0
0

Prestashop is arguably the #1 open-source e-Commerce solution on the web. It offers countless features, add-ons, and themes, but its lack of good documentation has given newcomers the perception that it’s unapproachable. In this article, I’ll walk you through the process of building your own custom theme, as well as creating and customizing Prestashop modules.

Prestashop runs on PHP and mySQL, and relies on the Smarty engine for its “Templates” (pages). Don’t worry, if you’re not familiar with Smarty. You basically use it to create pages with placeholder sections, and Prestashop fills in the info when the page loads. It’s easy to transition to, if you’ve used something like Handlebars or Underscore templates.

I’m going to assume that you have already downloaded and installed Prestashop. If not, you can download the latest version; they have an instructional video you can watch to learn how to set it up.

Prestashop Website

Registering Your Theme

Your site should look something like the following image, if you set up Prestashop with the default settings.

The process of building your own theme begins with creating a folder. In your file browser of choice, navigate to the root Prestashop directory and you’ll find a folder, called themes. Inside the themes folder, create a new directory with the name of your theme. I’m going to call mine, “Demo.”

If you add a picture of your template to this folder and name it preview.jpg, Prestashop should automatically find and add your template to the back-end. If it doesn’t, or you prefer to add the picture later, you can manually add the theme. To do this, go to the Themes option under the Preferences menu, and click Add New at the top. Once completed, you will see your theme in the center of the page. Enable it by simply clicking on it and pressing the Save button.

Add your logo(s) while you’re here; you can find this option at the bottom of the page. You may need to increase the file upload limit in Prestashop (or maybe even PHP’s config file) if you have a very large image.


Crash Course in Prestashop

Smarty is a template engine for PHP, facilitating the separation of presentation from application logic.

As I mentioned earlier, Prestashop uses Smarty for generating the pages; so, all the template files have a .tpl extension. There are many pages you must create in order to have a complete theme; take a moment and view the file list.

Ultimately, your theme’s functionality determines which pages you should implement. These page are based on the files in the controllers folder, and you can override the default controllers or add your own custom controllers to fit your theme. But that’s beyond the scope of this article. Among the controllers in controllers\front directory are two template files that automatically load: header.tpl and footer.tpl.

The major content of your site will be loaded by modules with the help of “Hooks”.

There are two types of hooks in Prestashop: action and display hooks. These both function the same way, but they differ in purpose. A hook basically gives the user a means to attach custom code to an outside source. In the case of an action hook, any code attached to the hook runs when the hook is called. For example, Prestashop comes with a default hook called actionProductAdd that runs when adding a product. So you could attach a module to this hook if you wanted to send an email newsletter every time a new product is added.

A display hook is very similar, but instead of connecting a function to an event, you connect a function to a specific place on the template. In other words, Prestashop will call your module by a specific point (e.g. right sidebar), and anything returned is placed into the page. You can view all the currently registered hooks by going to the Modules > Positions page in the back admin.

Personally, I find it best to start with a standard HTML theme. This isn’t a requirement, but I highly recommend it for a number of reasons:

  • It allows you to immediately see which hooks you need and how to divide your content.
  • It gives you a clear direction of which template files you have to create, as well as giving you an idea of what will be static content and what should be a module. It also allows you to add preview.jpg file right away.

The following image is a picture of my example HTML template:

And here you can see how I will split it up into Prestashop hooks:


Creating the Template Partials

Now let’s create the header.tpl file in your themes directory, and fill it with your themes header. This includes the doctype, area, and everything in the body that you want displayed on all pages. Here is an example header.tpl file:

<!DOCTYPE HTML><html><head><title>Prestashop Site</title><link rel="stylesheet" type="text/css" href="{$css_dir}bootstrap.min.css">
    {if isset($css_files)}
      {foreach from=$css_files key=css_uri item=media}<link rel="stylesheet" type="text/css" href="{$css_uri}">
      {/foreach}
    {/if}
    {if isset($js_files)}
      {foreach from=$js_files item=js_uri}<script src="{$js_uri}"></script>
      {/foreach}
    {/if}</head><body><div id="head"><div id="menu">
        {$HOOK_TOP}</div><div id="banner"><img src="http://d2o0t5hpnwv4c1.cloudfront.net/2169_prestashop/{$logo_url}" alt="Header Image"></div></div>

There are a few things to point out in this code. I preprended the CSS file name with {$css_dir}. This is a Smarty variable that points to a folder, called css inside your theme’s directory, where all you CSS files should go.

The next line uses Smarty’s foreach loop to add all the CSS files of the enabled modules. It’s worth noting that, if you create a CSS file called global.css in the css directory, the loop automatically adds that file to the page.

A few lines later, another foreach loop processes the JavaScript files in the js directory and adds them to the page. In the last section, I open the body element and define a hook for the menu module. Lastly, I finish off by displaying the site’s logo.

Unless you’re a Prestashop veteran, you’re probably wondering where I’m coming up with these variables. As I said earlier, unfortunately Prestashop’s documentation is lacking, but they do provide a debugging tool that you can launch by adding {debug} to any of the template files. When you open the corresponding page in your browser, you will get a pop-up containing a list of all variables for that specific template. This allows you to quickly (using ctrl/cmd-F dramatically helps) identify what variables are defined, as well as their values.

Now let’s create the footer.tpl template. I’m going to keep this simple and just close the <body/> and <html/> elements, but feel free to add anything you want to display on the bottom of every page. This can include anything from hooks to custom JavaScript; there are no limits to what you could put here.

The last file I want to implement is the index.tpl file. This is the “home page” file that displays when a user accesses the root of your site. In the default Prestashop theme, the sidebars are loaded in the header.tpl file, and the actual index template only contains a call to the displayHome hook. This is fine if you want the sidebars to be on all pages, but again, I would like to stress that hooks are implemented at your own convenience. You don’t have to implement any hook, and you can add your own custom hooks if you need more than the standard functionality.

When creating your index page, you have to decide which parts are static and which parts should be dynamically loaded through modules. I removed the main menu from the header because that is something I wanted to control with a module. So I placed a hook where I wanted the menu and I can create a module that attaches to this hook. You can load multiple items with the same hook. There is no reason to add multiple hooks together, and you can manage the order of a hook’s modules in the back-end under Modules > Positions.

Localization

The last Prestashop-specific feature you should consider is Prestashop’s localization tools. Prestashop allows you to easily translate your site into multiple languages by using a Smarty function, named l. You use it by replacing a standard string with the l function, passing the string as a parameter. Here is an example of an <h1/> element, both with and without translation:

{* Without Translation Tool *}<h1>Subscribe to us!</h1>
{* With Translation Tool *}<h1>{l s='Subscribe to us!'}</h1>

Even if you don’t currently plan on translating your site, it’s a small change that allows you to easily translate your pages if you later decide to do so. Once you make these changes to your templates, you can go to the Localization > Translations page in the back-end and click on the nationality you want to translate to.

Adding non-default languages is simple, and I cover it in the second section on the page (aptly named “Add/Update a Language”).

Another benefit to using Prestashop’s localization is the list of the phrases Prestashop gives you. Instead of going through your entire site, you can simply hand the list of phrases to a native speaker of your desired language and quickly input the values, while never touching your theme.

Now enter your home page’s specific HTML to the index.tpl, and be sure to supply the hooks you want to use. Remember to use the {debug} Smarty function, if you need to see the variables are available to your template.

Now you can open a browser and navigate to your sites root. Mine looks like this:

It may not look like much, but you have built your template’s outer shell. If your template looks like a mess of objects, it’s probably because you have a lot of modules installed. By default, Prestashop enables many modules; I recommend going to the modules page and uninstalling all modules. Don’t worry about losing them because you can reinstall them by clicking the install button next to the desired module.

When creating a Prestashop theme, you will notice that modules are responsible for approximately 90% of the content. There are modules that display the products, modules for the shopping cart, etc. A major part of being a Prestashop themer includes, at the very least, a working knowledge on how to customize the look of modules.


Modules

Modules in Prestashop are not the same as WordPress widgets.

Modules in Prestashop are not the same as WordPress widgets; Prestashop’s modules can only be attached to hooks that the module creator specifies. For example, if you create a module that displays a “subscribe to newsletter” block and you set it up to go in either of the sidebars, you cannot then place it in the footer area.

This may seem cumbersome, but there is a very good reason for this: when you create a module, you provide a separate function for each of the hooks you want to use. For example, if a menu module can behave differently based upon its location in the template.

This gives you a lot of room to customize a module.

This practice makes a lot more sense if you consider other kind of hooks: action hooks. You obviously don’t want the function that executes when you add a new product to execute when a user buys a product from you. The same applies to display hooks; each hook has its own function, letting you do whatever you want with it.

When building a theme, there are two ways you can go about adding modules. The first option is to create your own module. This is the more tedious option, but you do get a lot more control in the final product. On the other hand, there are over 2000 modules in the official modules catalog (and even more on third-party sites). Chances are good you can find something that matches your needs.

Your second option is to install a ready-made module; Prestashop gives you the option of customizing its appearance by overriding the template files. This is the better option, if you don’t really want to start coding your own module, and it allows you to focus on the graphical side. I’m going to cover both options; so let’s start with the first one.


Creating your own Module

We’ll build a module that displays a configurable number of products on the home page. This is loosely based on the stock module, but my module will go a little more into Prestashop’s underlying classes to hopefully give you a more in-depth look at the process.

First, create a folder in the modules directory, and then create a PHP file inside of it with the same name as the folder. When you open the modules folder, you will see a naming convention, where all the modules that solely display content start with the word “block”. This, of course, is not a requirement, but it makes sense. I’ll name my folder blockdisplayproducts, and, within it, I’ll create the PHP file with the same name.

Open up the PHP file and define the modules class:

<?php
if (!defined('_PS_VERSION_'))
exit;
class BlockDisplayProducts extends Module
{
	public function __construct()
	{
		$this->name = 'blockdisplayproducts';
		$this->tab = 'front_office_features';
		$this->version = 1.0;
		$this->author = 'Gabriel Manricks';
		$this->need_instance = 0;
		parent::__construct();
		$this->displayName = $this->l('Display Products Module');
		$this->description = $this->l('Displays a configurable amount of products for the home page.');
	}
}

Prestashop modules are object-oriented; therefore, you have to create a class for your module. The name of your class should be the camel-cased version of your folder’s name.

At the top of the file, you can see an if statement. This ensures that the file isn’t loaded directly through the browser. Next, your class either has to directly subclass the Module class or subclass a decedent of the Module class.

Inside the constructor, we setup the module’s properties. Prestashop uses this information to display in the back-end:

  • name is a unique “code name”, and it’s not the actual name shown in the back-end.
  • tab tells Prestashop the module’s category. You can find a complete list of categories by opening the Controllers\Admin\AdminModuleController.php file.
  • author, name and version are self-explanitory.
  • needs_instance tells Prestashop to create an instance of your variable when accessing the modules page. This is usually not required, but if your module needs to show a message or log something when the modules page is active, then you should change this to a 1.

The last two lines setup the actual display name and description for your module, and they use the same localization method in order to allow translating them to different languages. These two lines have to go after the parent’s initialization as per Prestashop’s preferred order used by their official modules.

The next step is to override the install method. This is where we can specify the hooks we need, as well as the default options for our module. If any of the settings fail, then the installation will fail.

This module is intended for the home page, so I’ll connect it to the home hook. We also want to add a CSS file to the header, meaning we’ll need to add the header hook as well. If you go to the back-end under the Modules > Positions page, you can find the hooks’ technical names (which is what we will specify here).

Right after the __construct() function, add the following:

public function install()
	{
			if (parent::install() == false || $this->registerHook('displayHome') == false || $this->registerHook('displayHeader') == false || Configuration::updateValue('DP_Number_of_Products', 6) == false)
					return false;
			return true;
	}

This adds the two hooks and sets the default number of products to six. You should name the property something unique so that other modules don’t interfere with your values. A simple approach adds your module’s name or initials to the beginning of the name.

You can now install your module in the modules page, and it should successfully install if everything is set up correctly. Go to the positions page, and it will display as registered under the the two hooks.

Implementing hooks is quite simple; create a public function with the word “hook” followed by the name of the hook. Let’s start with the header hook. We just want it to add a CSS file to our theme. Here is the complete function:

public function hookdisplayHeader($params)
	{
		$this->context->controller->addCSS(($this->_path).'blockdisplayproducts.css', 'all');
	}

Create that CSS file in your themes directory, and your template should load it in the header.

The next hook is a bit more complicated. It should retrieve a certain number of products from the database and load them into a template file. The function to retrieve the products doesn’t return the products’ images or links, so we have to call a few different functions and ‘build’ an array of products. Here is the complete function:

public function hookdisplayHome($params)
	{
		$languageId = (int)($params['cookie']->id_lang);
		$numberOfProducts = (int)(Configuration::get("DP_Number_of_Products"));
		$productsData = Product::getProducts($languageId, 0, $numberOfProducts, "id_product", "ASC");
		if (!$productsData)
			return "error";
		$products = array();
		$link = new Link(null, "http://");
		foreach($productsData as $product){
			$tmp = Product::getCover($product['id_product']);
			array_push($products, array(
				'name' => $product['name'],
				'author' => $product['manufacturer_name'],
				'desc' => $product['description_short'],
				'price' => $product['price'],
				'link' => $link->getProductLink(new Product($product['id_product'])),
				'image' => $link->getImageLink($product['link_rewrite'], $tmp['id_image'])
			));
		}
		$this->smarty->assign(array(
			'products' => $products
		));
		return $this->display(__FILE__, 'blockdisplayproducts.tpl');
	}

It begins by getting the number of products to display and the user’s language id. We then make a call to get the assigned number of products starting from the first product registered. After that, we make sure that there were no problems getting the products exiting if there was. The next block is the part I mentioned earlier, which builds up an array with all the properties we will need when displaying the item. This includes the picture and the link which were not returned with the rest of the product data. The last section adds the products array to Smarty and loads the template file of your choosing. I named the template file and the CSS files with the same name as the module, but this is not a requirement; you can name it whatever you wish.

If you open your site right now, you will only see a message, noting “No template found for module blockdisplayproducts.” So let’s create the template file inside our module’s directory, naming it the same as you just specified in the hook function. This part really depends on your specific themes layout, but here is my template file:

{if $products !== false}<div id="home_products_title"><h1>{l s='OUR BOOKS' mod='blockdisplayproducts'}</h1></div>
	{foreach from=$products item=product name=productLoop}<div class="home_products_book"><div class="home_products_picture"><img src="http://d2o0t5hpnwv4c1.cloudfront.net/2169_prestashop/{$product.image}" alt="{$product.name|strip_tags|escape:html:'UTF-8'}" /></div><div class="home_products_author">{$product.author|upper|strip_tags|escape:html:'UTF-8'}</div><div class="home_products_info"><div class="home_products_title">{$product.name|strip_tags|escape:html:'UTF-8'}</div><div class="home_products_description">{$product.desc}</div><div class="home_products_price">${$product.price|string_format:"%.2f"}</div><div class="home_products_openButton"><a href="{$product.link}" class="btn btn-inverse">{l s='View' mod='blockdisplayproducts'}</a></div></div></div>
	{/foreach}
{/if}

Since Prestashop uses Smarty templates, you have a number of helper functions that you can use when displaying your data. We start off with an if function to make sure that the products array is okay. If it is, we go into a for loop, generating the specified HTML for each one. We are using Smarty’s built in helper functions to strip HTML tags and covert the authors name to uppercase, and we are using another method to format the price to the desired number of decimal places. To see a full list of modifiers, see here.

Also, notice that, when translating strings here, you have to enter your module’s name. This is because the translation is not tied to a theme, but to the module itself. On the other hand, the l function is template specific; so, in order for it to find your translation file, it requires the module’s name.

You can now view your site in the browser; if you’ve added any products, they should be displayed on the home page now.

Now, our module is fully functional, but there is no way to adjust the number of products returned. To do this, we need to add a function, called getContents. If your module has this function, then Prestashop will automatically add a configure button on the “modules” page. Anything returned by this function will be displayed on the config page. To begin, add the function to the module’s class and fill it with the following:

public function getContent(){
		$html  = '<div style="width:400px; margin:auto">';
		$html .= '	<h2>' . $this->displayName . ' Settings</h2>';
		$html .= '	<form action="'. Tools::safeOutput($_SERVER['REQUEST_URI']). '" method="post"><fieldset>';
		$html .= '		' . $this->l('Number of Products to Display') . ': <input type="number" name="numProds" value="' . (int)(Configuration::get('DP_Number_of_Products')) . '" />';
		$html .= ' 		<input type="submit" value="' . $this->l('Save') . '" />';
		$html .= '	</fieldset></form>';
		$html .= '</div>';
		return $html;
	}

This function simply builds up the HTML necessary to display a form with a number box and save button. Again, I’m using the $this->l() method so that you can translate the module into other languages in the future, should you need to do so. I’ve used a number field in the HTML form, but be careful, if you are making a commercial module. It’s still not supported by all browsers. That said, if it’s for your own personal use, then feel free!

The only other thing that might seem cryptic is the Tools::safeOutput() function that we are calling on the URL. I’m honestly not 100% sure how crucial this call is, but what it’s doing is it’s striping all HTML tags and converting the necessary characters to html entities.

Next, go to the modules page and click the configure button on your module. You will be greeted with the form we just made.

You can adjust the number and press save, but we haven’t written in the saving functionality yet, so it will keep resetting to 6 (the value that is already saved).

Back in the function, add the following code to the beginning of the function:

if (Tools::isSubmit('numProds')){
  Configuration::updateValue('DP_Number_of_Products', (int)(Tools::getValue('numProds')));
}

This checks to see if the value was submitted – i.e., if the value numProds exists as a $_GET or $_POST variable. We then update the property where we stored the value. The method Tools::getValue accepts the name of a form field and optionally a second string of what to return if the form field was not found; it then returns a formatted string with the value that was submitted. It’s important to put this before you generate the HTML form; otherwise, the form will contain the old values as apposed to the updated ones.

With that final bit of code, we’ve completed the module. The only other thing you should do is add a 16×16 GIF icon to your modules folder.

We are now ready to move on to the next option for integrating modules with your theme.


Overriding Existing Modules

The second option is to use an existing module and re-theme it according to your likings. This option is considerably simpler as you only need to re-create the “.tpl” file(s) from the module.

My example theme is still missing a top navigation menu, so let’s customize that module. To get started, enable/install the module in the ‘modules’ page, called ‘Top horizontal menu’. The next step is to create a folder in your themes directory, called modules. Within it, create another folder with the actual name of the module – in our case, this is blocktopmenu. When loading a module’s tpl files, Prestashop first checks to see if there is a file in the activated themes module-override directory with the same name. If so, it will load the themes version instead of the stock one. The menu module’s tpl file is named blocktopmenu.tpl, so you have to create a file with the same name in the new folder we just created.

The easiest way to figure out what kind of data a module offers is to either take a look at their tpl file and see what data they use, or load up the {debug} tool. To speed things up, I can tell you that this plugin only offers a single variable, named MENU, which contains a string with all the menu items combined together inside

  • tags. Now, by itself, this doesn’t give you a lot of wiggle room, when it comes to customizing the appearance. But, what if you’d like to add something else besides just a li tag for each item? Well, luckily, Smarty to the rescue! This is not an article on Smarty so I’ll keep this part short, but, basically, we will use a combination of the string replace function and PHP’s explode function to isolate the individual elements. Following that, we can build the HTML code with a foreach loop. Here is my completed template file for this module:

    <div id="menuItems" class="divcollapse"><ul>
    		{assign var=tmpMenu value=$MENU|replace:'<li>':''}
    		{assign var=items value='</li>'|explode:$tmpMenu}
    		{foreach $items as $item}
    			{if !$item@last}<li>{$item}</li>
    		    	{if ($item@index + 2) != $item@total}<div class="divcollapse logo"><img src="http://d2o0t5hpnwv4c1.cloudfront.net/2169_prestashop/{$img_dir}icon.png" alt="logo"/></div>
    		    	{/if}
    		    {/if}
    		{/foreach}</ul></div>

    Now this is a lot of new code, so I’ll go through it line by line. It begins by opening div and ul tags; these are purely for aesthetic reasons. Next, we use a Smarty command, called assign. This does exactly what it sounds like: it assigns a value to a variable. In the first assign statement, we’re removing the opening li tags, and, in the second one, we explode the string by the closing li tag. The result is an array containing a list of menu item links. We then move onto a foreach loop, where we display each item inside

  • tags – except, this time, we’ve added an icon image after each menu item except for the last menu item. Also, you may have noticed that I’m avoiding the last value in the array all together. This is because the last value is just a newline character.

    If you’ve executed everything correctly so far, you can now theme it to your liking and add some pages to the menu from the module’s “configure” page. Once finished, you should be able to go to your site and see the menu working as expected!


    Conclusion

    This has been a very brief but thorough review of the techniques required to create PrestaShop themes. Over the course of the tutorial, I’ve gone through the necessary steps to create a full multi-lingual theme, and two different ways to put themed modules into your template.

    Moving forward, I suggest that you dive a bit deeper into Smarty, as it offers a number of hidden features that can really help you out. As for a good place to learn more about Prestashop, well, there’s not much; I recommend reading the source. At the time of this writing, Prestashop’s documentation is somewhat spotty in its coverage of topics; however, their source code is very well documented. Another excellent option is to examine other modules and themes to gain a deeper understanding of what Prestashop is capable of.

    I hope you’ve enjoyed reading this article. If you have any questions regarding the article itself, or Prestashop in general, feel free to leave a comment below!

    In need of premium, ready-to-go PrestaShop themes? Check out ThemeForest!

  • Writing Hubot Plugins with CoffeeScript

    $
    0
    0

    In case you’ve been hiding under a rock, Campfire is a real-time chat application, written by our friends at 37 Signals. Campfire has a robust API, giving you the ability to bolt on tools to better the team environment.

    Campfire is widely used by companies with remote workers and allows quick collaboration between distributed teams. Keep in mind that, in some cases, such as at my job at Emma, Inc., remote could mean “in the next room.” At Emma, we can check the status of our systems, quickly retrieve customer data, and many other useful tasks that makes our work easier. Many of these tasks are made possible with the implementation of Hubot.


    What’s Hubot?

    Plugins are fun to write and even more fun to use.

    Hubot is a scriptable framework created by the folks at Github; they describe it as “a customizable, kegerator-powered life embetterment robot”. Hubot is open source, written in CoffeeScript on Node.js, and easily deployed on platforms like Heroku. While Hubot can run within many different environments, I’ll focus on running Hubot within the confines of a Campfire chat room.

    In addition to releasing the source for Hubot, Github created a small number of pre-built scripts that ship with the Hubot source. These scripts allow Hubot to do things such as easily import images /img cute kittens:

    image

    Or you can import videos /youtube breakdancing:

    image

    Github also created a Hubot plugin repository where users can submit new plugins. As of this writing, there are 294 plugins in the public repository, covering all sorts of functionality ranging from the useful: checking the status of an AWS service, interacting with a Travis-CI server or base64 encoding; to the humorous: playing a rimshot audio clip; to the absurd: add a mustache to a photograph. You can even check out the nickname generator plugin that I wrote!

    The sky’s the limit with Hubot. If something can be done from within Node.js, then it can be automated using Hubot. With just a little bit of CoffeeScript knowledge, you can write the next great Hubot plugin. Speaking of, let’s take a quick refresher course in CoffeeScript before we write our first Hubot plugin. If you’re already familiar with CoffeeScript then feel free to jump ahead to the next section.


    What’s CoffeeScript?

    CofeeeScript describes itself as a “little language that compiles into JavaScript” and “an attempt to expose the good parts of JavaScript in a simple way”. CoffeeScript’s goal is to remove the tedium of boilerplate (all those pesky curly braces, semicolons, and parentheses) from the life of developers and distill JavaScript down to its bare essence. As a result, your code becomes easier to read, and there’s less of it to boot. Let’s take a look at a few simple examples and compare the resulting JavaScript you compile CoffeeScript.

    Oh wait, did I say “compile”?

    I sure did, and how do you do that? I’m glad you asked… there’s a number of tools that offer this service. My personal favorite is CodeKit, but be sure to check out the command line driven Yeoman. You can also directly compile CoffeeScript if you’ve installed Node.js, and you can even use a real-time conversion tool like JS2Coffee, which lets you convert back and forth between CoffeeScript and JavaScript.

    Strings

    So, what does CoffeeScript look like? Let’s start with a line of JavaScript:

    var author = 'Ernest Cline';

    The CofeeScript equivalent is:

    author = 'Ernest Cline'

    Objects

    That’s a simple example, but it starts to show what CoffeeScript does for you… removing verbosity. Note the abscence of the var keyword and the semicolon. You’ll never need those when you write in CoffeScript. How about an object reference in JavaScript?

    book = {
        title: 'Ready Player One',
        date: '10/16/2011',
        references: {
            games: ['Street Fighter', 'Pac-Man'],
            music: ['Oingo Boingo', 'Men Without Hats'],
            movies: ['Back To The Future', 'The Last Starfighter']
        }
    }

    Here’s the CoffeeScript version:

    book =
      title: "Ready Player One"
      date: "10/16/2011"
      references:
        games: ["Street Fighter", "Pac-Man"]
        music: ["Oingo Boingo", "Men Without Hats"]
        movies: ["Back To The Future", "The Last Starfighter"]

    A key thing to remember about CoffeeScript is that your code is still there, but the extra fluff of some delimiters, terminators, and keywords are gone. CoffeeScript goes an extra step (or three) and assumes those characters for you.

    Functions

    What about functions you might ask? They’re similarly neat and tidy, removing braces and the return keyword. Like before, here’s the JavaScript:

    function openGate(key) {
        var gates = {
            'Copper': 'You opened the Copper Gate',
            'Jade': 'You opened the Jade Gate',
            'Crystal': 'You opened the Crystal Gate'
        };
        return gates[key] | 'Your key is invalid'
    }
    openGate('Jade')

    And here’s the same thing in CoffeeScript:

    openGate = (key) ->
      gates =
        Copper: "You opened the Copper Gate"
        Jade: "You opened the Jade Gate"
        Crystal: "You opened the Crystal Gate"
      gates[key] | "Your key is invalid"
    openGate "Jade"

    CoffeeScript has a number of other extremely useful features that make it a compelling choice. Features like comprehensions (basically single line loops), “true” classes, handy string replacement, chained comparisons and more. You can read more about CoffeeScript on its website at CoffeeScript.org.


    Setting the Stage

    We’ll need to install a few items before we can start working on our plugin. We’ll need Node.js, NPM, and Hubot–along with their various dependencies.

    Installation

    The sky’s the limit with Hubot.

    Let’s first install Node.js. Open a terminal window and type which node. If you get back a file system path, then you can skip this section. If you see node not found or something similar, then you’ll need to install it. Head over to the Node.js website and download (and install) the appropriate binary for your operating system. Unless you’ve recently installed Node, it’s probably a good idea to go ahead and install the most recent version. Newer versions of Node ship with NPM (or Node Package Manager) which we’ll use to install our software.

    Next up we’ll need to install Hubot. Type npm install hubot -g into your terminal window and let NPM do its work. I prefer to install plugins like this globally, thus the -g flag.

    Using Hubot Locally

    After the installation completes, we’ll cd to the hubot install directory and run it for the first time. That directory can differ depending upon your paricular machine, but it is at /usr/local/lib/node_modules/hubot on my machine. Fire up hubot with the following command . bin/hubot. Then test it out with the command hubot ping. Hubot should immediately respond with PONG. Let’s take a quick look at that plugin before writing our own. Its three lines of code are the guts of almost every other Hubot plugin. Here it is in all its glory:

    module.exports = (robot) ->
        robot.respond /ping$/i, (msg) ->
            msg.send "ping"

    When Hubot first starts up, it runs through every plugin in the scripts directory. Each plugin is written using the common module.exports Node pattern, which allows the plugin to identify itself to Hubot, and it also allows Hubot access to the plugin’s inner workings. Also found in a plugin are one or more respond function calls. Each of these calls correlates to a an event listener that waits to hear a specific keyword or pattern. Lastly, this plugin sends back a value using msg.send, returning any arbitrary msg you prefer.

    By the way, if you’re curious (like I was) to see just what the robot, or msg, arguments contain, simply add a console.log statement anywhere in the code. For example, adding console.log(robot) immediately after the module.exports statements displays the following information:

    {
          name: 'Hubot',
          commands: [],
          version: '2.3.4',
          server: {}
          documentation: {},
          listeners:
          [
                {
                      robot: [Circular],
                      regex: /^Hubot[:,]?\s*(?:PING$)/i,
                      callback: [Function],
                      matcher: [Function]
                }
          ],
          [more stuff]
    }

    Now you’re ready to start working on our first Hubot plugin.


    Your First Hubot Plugin

    Okay, enough already. I know you’re ready to write your own plugin, so lets do a quick one of our own. Create a new file within the scr/scripts directory of your Hubot install. Name it deepthoughts.coffee, open it in your editor of choice, and then input the following lines:

    # Configures the plugin
    module.exports = (robot) ->
        # waits for the string "hubot deep" to occur
        robot.respond /deep/i, (msg) ->
            # Configures the url of a remote server
            msg.http('http://andymatthews.net/code/deepthoughts/get.cfm')
                # and makes an http get call
                .get() (error, response, body) ->
                    # passes back the complete reponse
                    msg.send body

    You’re already familiar with the first two lines so we won’t review them. The third line begins the set up of an HTTP request; in this case, it’s a GET that sends no parameters to the remote site. The fourth line executes the HTTP request and sets up a callback function that receives any errors, the raw response, and the body of the returned page. In this case, the loaded page’s body doesn’t even have any HTML…it’s simply a string. This allows us to return it directly to the user by way of msg.send. Save that file, restart Hubot with a hubot die and a bin/hubot, and then get yourself a random deep thought with a hubot deep. Hopefully, it’s something profound, deeply thought provoking and not the one about the trampoline salesman or the golden skunk.

    Your Hubot Homework

    Now that you’ve written your first plugin, here’s the code for another one. See if you can figure out what it does and how to use it.

    QS = require 'querystring'
    module.exports = (robot) ->
        robot.respond /post (.+)/i, (msg) ->
            url = 'http://httpbin.org/post'
            data = QS.stringify({'hubot-post': msg.match[1]})
            msg.http(url)
                .post(data) (err, res, body) ->
                    msg.send body
    • Notice the import happening at the top.
    • What’s the respond method listening for?
    • What is msg.match?
    • See that the plugin can also do post requests?

    Go Forth and do Likewise

    As you can see from these few examples, writing Hubot plugins is a fairly straightforward task. Plugins can be useful or whimsical, but they’re fun to write and even more fun to use. What sort of plugin will you create for the world?

    The one unfortunate thing about writing Hubot plugins is that the documentation isn’t super clear on some subjects, and you might sometimes spin your wheels trying to figure out what part belongs to what app if you’re unfamiliar with Node, CoffeeScript, or Hubot. But with a little perseverence, and this article, you’ll be on your way.

    Publishers: Don’t Restrict Writers

    $
    0
    0

    Today, I'd like to take a few moments to focus on something that affects us all, but isn't specifically code related. What I'm referring to is the people who commission the traditional books and magazine articles that you read and learn from every day.

    What you might not realize is that publishers have a tendency to enforce surprisingly strict guidelines upon writers.

    For those of you who haven't yet contributed to a technical book or magazine – or even some commercial blogs – what you might not realize is that publishers have a tendency to enforce surprisingly strict guidelines upon writers.

    • Your article must be this number of words.
    • You must provide a total of X images with your article – regardless of whether the content merits imagery.
    • Your introduction should be three hundred words.
    • Each section of your article must amount to one hundred words, and contain two code samples.
    • If writing a book, the full chapter outline must be provided at the beginning of the process, before you've had any time to live with the book, and determine when and how to discuss each topic.
    • Worst of all, you must use our ridiculous, unintuitive Word document and template, when preparing your article or book.

    The items noted above represent but a small portion of the restrictions that rest upon a technical writer's shoulders. What this translates to is: in addition to deciphering how to best explain considerably complex technologies, a technical writer must also somehow manage to fit their content within the boundaries of a publisher's confusing predetermined guidelines.

    For the icing on the case – and to apply yet more pressure upon the writer – a variety of (fairly intense) deadlines will be set, in order to ensure that the book is completed on time. While this is certainly understandable, many times, publishers tend to be too ambitious in the dates they choose, which don’t account for the writer’s full time job and other responsibilities.

    This model is out-dated, and quickly nearing extinction, if it’s not addressed and modernized.


    Why Do They Do This?

    Teaching code is, in many ways, an art.

    Before we continue picking on traditional publishers, it's important to first understand why they do this. Consider a magazine with a finite number of pages available for a particular piece of content – say, five pages. If this were the only restriction, it would still prove difficult for the writer. Teaching code is, in many ways, an art. It requires both an understanding of the technology, as well as the ability to explain it in such a way so that everyone can comprehend it. How do you place an abitrary word count on art and explanation? Well, the answer is that you can't – at least not without considerable sacrifice and editing.

    Let's continue on; now that we've established that Magazine X may only have room for five pages, the next restriction comes in the form of finding a way to cram your article into a pre-defined layout template, that is, needless to say, not conducive in any way, shape or form to the writing process. This is where the image and per-section word count requirements come into play.

    Imagine being told that you need to describe how this piece of code works in 25-35 words. Done? Now, imagine the sacrifices that you'd have to make, in order to wrangle your explanation enough to fit that requirement! Who benefits from this?


    It's About Automation – Not the Writer

    The rub lies in the fact that these templates and macros don't take the writing process into consideration.

    From a non-writer's perspective, it's perfectly understandable why it might be necessary to set these restrictions. Consider the publishers who organize and edit hundreds of books per year. In these cases, it quickly becomes essential – for their own sanity – to prepare templates, and significantly complex Word documents and macros to automate as much as possible.

    The rub lies in the fact that these templates and macros don't even begin to take the writing process into consideration. Now, rather than focusing on what's most important (explaining complicated code), the writer is instead forced to place considerable effort and time into deciphering how to use a particular Word macro, or format their document, per the publisher's guidelines.

    One of three outcomes can result from a publisher imposing pages of requirements upon a writer, who wants nothing more than to teach a particular technology to others – and, perhaps, pay the mortgage in the process. (If you think the writers of your favorite technical books do it for the money, think again.)

    • Acceptance: The writer agrees to the limitations, and does their best to work their way through the process, like a maze.
    • Abandonment: After significant investment, the writer ultimately pulls out of the project, due to the effects of an unnatural writing process and deadlines.
    • Refusal: Upon receiving the various forms and guidelines, the writer quickly becomes overwhelmed and refuses the contract.

    I’m sure you can guess which option above tends to be the most popular.


    What's Ideal?

    At one point, I had similar requirements for Nettuts+ contributors.

    I must admit, at one point, I had similar requirements for Nettuts+ contributors and staff writers. Luckily, the format of a blog naturally makes for less stringent requirements. A per-section word count requirement is silly and meaningless for a blog. That said, I still emphasized word counts, providing images, and using our special Nettuts-specific HTML template, when preparing new tutorials.

    Why? Well, for the same reason as why traditional publishers do: my job is easiest, when the article fits my pre-determined layout for a Nettuts+ article.

    What I didn't take into consideration was the number of potential writers that I inadvertently pushed away, by setting these requirements. Who honestly has the time to work within the confines of somebody else's template? When time is a precious commodity (especially for those with existing full time jobs and families), these confines serve to be nothing more than a deterrent.

    These days, my only goal, when commissioning new content, is to make the writing process for the author as effortless and natural as possible.

    • Don't worry about using Microsoft Word, or our custom templates. Use whatever writing tool you feel most comfortable in.
    • Don't learn how to make your code fit our special syntax highlighter. We take care of that.
    • Don't even think about word counts or image requirements. Certainly, I can't accept articles that are only 400 words, but, in my experience, writers are most effective, when they're far less concerned with meeting arbitrary word count requirements, and more with teaching the content as well as they're capable. If that means the article is 1500 words, or three times that number, I don't care. Just teach it right!

    Now that I’ve matured as editor of Nettuts+, when working with new authors, I only request a Markdown file, which, for those unfamiliar, is a pseudo-language that developers in particular tend to prefer. Markdown takes the visuals and formatting completely out of the writing process, as should be the case – especially in our industry. Alternatively, if they don’t feel comfortable with Markdown, they’re free to use anything else to get the job done.

    Now that I’ve matured as editor of Nettuts+, when working with new authors, I only request a Markdown file.

    Perhaps this method may make for slightly more work on my part, but it absolutely and positively is worth the trade-off. I want our writers to focus on nothing other than explaining complicated technologies as effectively as possible. We’ll take care of the rest. If only all publishers adopted a similar model.

    What to Expect From PHP 5.5

    $
    0
    0

    The first PHP 5.5 alpha has been publicly released. After having some time to test and experiment with it, we can now bring you our in-depth overview of what to look forward for!


    Installation

    If you’d like to follow along with this article, you’ll need to install PHP 5.5 for yourself. You can find the link to the source bundle here. Additionally, if you need the Windows binary file, you can grab it from the same page.

    Once you have the source code downloaded, extract everything into a folder and navigate to it with your favorite Terminal program. You can install PHP to wherever you like, but, for convenience, I’m going to create a directory in the root of my drive, called PHP5.5. To create a new folder and then make your user the owner of said folder, type the following into your terminal:

    sudo mkdir /PHP5.5
    sudo chown username /PHP5.5

    Next, you have to decide which extensions and features you want installed with your copy of PHP. Since this is an Alpha version, meant for testing only, I’m not going to worry about making it fully featured. For this tutorial, I am only going to install cURL, but there might be other things that you’d want to add, such as MySQL or zip support. To view a full list of configuration options, run:

    ./configure -h

    Besides the option to install cURL, there are two other properties that we need to set: the prefix and with-config-file-path option. These two properties set up the location of the PHP installation and the .ini file, respectively. So in the terminal, type:

    ./configure --prefix=/PHP5.5 --with-config-file-path=/PHP5.5 --with-curl=ext/curl
    make
    make install

    The first line configures PHP with cURL, and sets the location to the folder we made earlier. The next two lines build PHP and move the files to the specified directory. The next step is to copy the sample php.ini file to the PHP folder. To do this, run:

    cp php.ini-development /PHP5.5/php.ini

    You should now have everything installed correctly. The easiest way to test this new version out is to run its built in web server. Navigate to the bin folder inside the PHP5.5 directory (cd /PHP5.5/bin), and type ./php -t /Path/To/Directory -S 0.0.0.0:4444.

    • The -t option sets the server’s root directory (i.e. the location where you will place your PHP files)
    • The -S property sets the IP address and port number where the server should bind to. Using 0.0.0.0 for the IP address tells the server to listen on all IP addresses (e.g. localhost, 127.0.0.1, 192.168.0.100, etc.).

    If all goes well, you should be greeted with a message telling you that the server is listening on the IP/port specified, and it will tell you the document root where it’s serving from. We can now start toying with the new features!


    Generators

    Generators allow you to create custom functions, which retain state between runs.

    The biggest addition to PHP 5.5 has got to be generators. Generators allow you to create custom functions, which retain state between runs. It works off a new keyword, called yield, which can be used in a function for both inputting and outputting data.

    Essentially, when the function gets to a line that contains the yield command, PHP will freeze the function’s execution and go back to running the rest of your program. When you call for the function to continue – either by telling it to move on or by sending it data – PHP will go back to the function and pick up where it left off, preserving the values of any local variables that were defined up to there.

    This may sound somewhat cool at first, but if you give it some thought, this opens doors to a lot of interesting design options. Firstly, it simulates the effects of other programming languages that have “Lazy Evaluation,” like Haskell. This alone allows you to define infinite data sets and model math functions after their actual definition. Besides that, you don’t have to create as many global variables; if a variable is only meant for a specific function, you can include it in a generator, and things like counters happen automatically by the generator itself in the form of the returned object’s key.

    Well that’s enough theory for now; let’s take a look at a generator in action. To start off, navigate to the document root you defined when running the PHP server, and create a file, called “index.php”. Now, open up the file and type in the following:

    function fibonacci(){
        $a = 0;
        $b = 1;
        while(true)
        {
            $a = $a + $b;
            $b = $a - $b;
            yield $a;
        }
    }

    This is the “Hello World” function of infinite datasets. It’s a function that will output all fibonacci numbers. To use the generator, all you have to do is type:

    $fib = fibonacci();
    $fib->current();
    $fib->next();
    $fib->current();
    //...

    What’s happening here is we’re making $fib a generator object, and then you have access to the underlying commands, like current() and next(). The current() function returns the current value of the generator; this is the value of whatever you yielded in the function – in our case, $a. You can call this function multiple times and you will always get the same value, because the current() function doesn’t tell the generator to continue evaluating its code. That’s where the next() function comes in; next() is used to unfreeze the iterator and continue on with the function. Since our function is inside an infinite while loop, it will just freeze again by the next yield command, and we can get the next value with another call to current().

    The benefit to generators is that the local variables are persistent.

    If you needed to do accomplish something like this in the past, you would have to put some kind of for loop which pre-calculates the values into an array, and halts after a certain number of iterations (e.g. 100), so as not to overload PHP. The benefit to generators is that the local variables are persistent, and you can just write what the function is supposed to do, as apposed to how it should do it. What I mean by this is that you simply write the task and don’t worry about global variables, and how many iterations should be performed.

    The other way yield can be used is to receive data. It works in the same way as before: when the function gets to a line with the yield keyword, it will stop, but, instead of reading data with current(), we will give it data with the send() function. Here is an example of this in action:

    function Logger(){
        $log_num = 1;
        while(true){
            $f = yield;
            echo "Log #" . $log_num++ . ": " . $f;
        }
    }
    $logger = Logger();
    for($i = 0; $i<10; $i++){
        $logger->send($i*2);
    }

    This is a simple generator for displaying a log message. All generators start off in a paused state; a call to send (or even current) will start the generator and continue until it hits a yield command. The send command will then enter the sent data and continue to process the function until it comes to the next yield. Every subsequent call to send will process one loop; it will enter the sent data into $f, and then continue until it loops back to the next yield.

    So why not just put this into a regular function? Well, you could, but, then, you would either need a separate global variable to keep track of the log number, or you would need to create a custom class.

    Don’t think of generators as a way to do something that was never possible, but rather as a tool to do things faster and more efficiently.

    Even infinite sets were possible, but it would need to reprocess the list from the beginning each time (i.e. go through the math until it gets to the current index), or store all of its data within global variables. With generators, your code is much cleaner and more precise.


    Lists in foreach Statements

    The next update that I found to be quite helpful is the ability to break a nested array into a local variable in a foreach statement. The list construct has been around for a while (since PHP4); it maps a list of variables to an array. So, instead of writing something like:

    $data = array("John", "Smith", "032-234-4923");
    $fName = $data[0];
    $lName = $data[1];
    $cell = $data[2];

    You could just write:

    $data = array("John", "Smith", "032-234-4923");
    list($fName, $lName, $cell) = $data;

    The only problem was that, if you had an array of arrays (a nested array) of info you wanted to map, you weren’t able to cycle through them with a foreach loop. Instead, you would have to assign the foreach result to a local variable, and then map it with a list construct only inside the loop.

    As of version 5.5, you can cut out the middle man and clean up your code. Here’s an example of the old way, versus the new:

    //--Old Method--//
    foreach($parentArr as $childArr){
    	list($one, $two) = $childArr;
    	//Continue with loop
    }
    //--New Method--//
    foreach($parentArr as list($one, $two)){
    	//Continue with loop
    }

    The old way might not seem like too much trouble, but it’s messy and makes the code less readable.


    Easy Password API

    On my Mac’s built in graphics card, I was able to go through over 200 million hashes a second!

    Now this one requires a little knowledge of hashes and encryption to fully appreciate.

    The easiest way to hash a password in PHP has been to use something like MD5 or a SHA algorithm. The problem with hash functions like these are that they are incredibly easy to compute. They aren’t useful anymore for security. Nowadays, they should only be used for verifying a file’s integrity. I installed a GPU hasher on my computer to test out this claim. On my Mac’s built in graphics card, I was able to go through over 200 million hashes a second! If you were dedicated, and invested in a top of the line multi-graphics card setup, you could potentially go through billions of hashes a second.

    The technology for these methods were not meant to last.

    So how do you fix this problem? The answer is you pose an adjustable burden on the algorithm. What I mean by this is that you make it hard to process. Not that it should take a couple of seconds per hash, as that would ruin the user’s experience. But, imagine that you made it take half a second to generate. Then, a user likely wouldn’t even realize the delay, but someone attempting to bruteforce it would have to run through millions of tries – if not more – and all the half seconds would add up to decades and centuries. What about the problem of computers getting faster over time? That is where the “adjustable” part comes in: every so often, you would raise the complexity to generate a hash. This way, you can ensure that it always takes the same amount of time. This is what the developers of PHP are trying to encourage people to do.

    The new PHP library is a hashing “workflow,” where people are able to easily encrypt, verify and upgrade hashes and their respective complexities over time. It currently only ships with the bcrypt algorithm, but the PHP team have added an option, named default, which you can use. It will automatically update your hashes to the most secure algorithm, when they add new ones.

    The way bcrypt works is it runs your password through blowfish encryption x amount of times, but instead of using blowfish with a key so that you could reverse it later, it passes the previous run as the key to the next iteration. According to Wikipedia, it runs your password through 2 to the x amount. That’s the part that you could adjust. Say, right now, you want to use a cost level of 5: bcrypt will run your hash 2 to the 5, or 32 times. This may seem like a low number, but, since the cost parameter adjusts the function exponentially, if you changed it to 15, then the function would run it through 32768 times. The default cost level is 10, but this is configurable in the source code.

    With the theory out of the way, let’s take a look at a complete example.

     $pass = "Secret_Password";
     $hash = password_hash($pass, PASSWORD_BCRYPT, array('cost' => 12, 'salt' => "twenty.two.letter.salt"));
     if(password_verify($pass, $hash)){
     	if(password_needs_rehash($hash, PASSWORD_DEFAULT, array('cost' => 15))){
     		$hash = password_hash($pass, PASSWORD_DEFAULT, array('cost' => 15));
     	}
     	//Do something with hash here.
     }

    The password_hash function accepts three parameters: the word to hash, a constant for the hashing algorithm, and an optional list of settings, which include the salt and cost. The next function, password_verify, makes sure that a string matches the hash after encryption, and, finally, the password_needs_rehash function makes sure that a hash follows the parameters given. For example, in our case, we set the hash cost to twelve, but, here, we are specifying fifteen, so the function will return true, meaning that it needs to be rehashed.

    You may have noticed that, in the password_verify and password_needs_rehash functions, you don’t have to specify the hashing method used, the salt, or the cost. This is because those details are prepended to the hash string.

    Salts are used to prevent hashes from being precomputed into rainbow table.

    The reason why it’s okay to bundle the cost and salt along with the hash and not keep it secret, is because of how the system puts its strengths together. The cost doesn’t need to be a secret, because it is meant to be a number which provides a big enough burden on the server. What I mean by this is that, even if someone gets your hash and determines that your cost level requires 1/2 a second to compute, he will know what level to bruteforce at, but it will take him too long to crack (e.g. decades).

    Salts are used to prevent hashes from being precomputed into a rainbow table.

    A rainbow table is basically a key-value store with a “dictionary” of words with their corresponding hashes as their keys.

    All someone has to do is precompute enough common words – or, worse, all string possibilities – and then they can look up the word for a given hash instantly. Here’s an example of how salts can be of help: let’s say that your password is the word, “password.” Normally, this is a fairly common word; it would likely be in their rainbow table. What a salt does is it adds a random string to your password; so, instead of hashing “password,” it’s really hashing “passwordRandomSalt524%#$&.” This is considerably less likely to be pre-computed.

    So, why are salts usually considered to be private information? Traditionally, with things like MD5 and the likes, once someone knows your salt, they can return to performing their bruteforce techniques, except they will add your salt to the end. This means, instead of bruteforcing your random password string, they are bruteforcing a much shorter standard password and just adding the salt. But, luckily, since we have the cost factor setup, it would take too long to compute every hash over with the new salt.

    To recap: salts ensure that the precomputing of one hash cannot be used again on another hash, and the cost parameter makes sure that it isn’t feasible to compute every hash from scratch. Both are needed, but neither of them have to be secret.

    That is why the function attaches them to the hash.

    Remember, it doesn’t matter what your salt is, as long as it’s unique.

    Now, if you understood what the salt is doing, then you should know that it’s better to let the function randomly generate one, than to enter your own word. Although this feature is provided, you don’t want all of your hashes to have the same salt. If they do, then, if someone managed to break into your database, all they’d have to do is compute the table once. Since they will have the salt and cost level, it might take a while, but, with enough computers, once they process it, they will have unlocked all of your hashes. As such, it’s much better to not assign one and instead let PHP randomly generate one.


    cURL Additions

    Up until now, there was no easy way to send mail through SMTP.

    cURL is another area, where the PHP team have added some exciting new additions and updates. As of version 5.5, we now have support for the FTP directives, directives to set cookies, directives for SSL and accounts, and directives for the SMTP and RTSP protocols, among others. It would take too long to discuss all of them, but, to view the full list, you can refer to the NEWS page.

    I do, however, want to talk about one set in particular that interested me most: the SMTP set of directives. Up until now, there was no easy way to send mail through SMTP. You would either have to modify your server’s sendmail program to send messages via an SMTP server, or you would have to download a third party library – neither of which is the best option. With the new CURL directives, you are able to talk directly with a SMTP server, such as Gmail, in just a few short lines.

    To better understand how the code works, it’s worth learning a bit about the SMTP protocol. What happens is, your script connects to the mail server, the mail server acknowledges your connection and returns to you its information (e.g. domain, software). You then have to reply to the server with your address. Being a chatty (but polite) protocol, SMTP will greet you so that you know it was received.

    At this point, you are ready to send commands. The commands needed are the MAIL FROM and the RCPT TO; these map directly to the cURL directives, CURLOPT_MAIL_FROM and CURLOPT_MAIL_RCPT, respectively. You only have one from address, but you are able to specify multiple to addresses. Once this is done, you can simply call the command, DATA, and start sending the actual message and message headers. To end the transmission, you have to send a blank line, followed by a period, followed by another blank line. These last two parts (i.e. DATA command and the ending sequence) are taken care of by cURL, so we don’t have to worry about it.

    So, in PHP, all we have to do is specify the mail from and to directives, and then send the actual message – all within cURL. To make things really simple, I’m going to create a class, called Gmail, which will accept a username/password and the message details, and it will send emails through your Gmail account.

    I’ll paste the entire class below, and then we’ll go through it line by line, as most of it is boilerplate.

    class Gmail{
            private $mail;
            private $email;
            private $pass;
            public function __construct($email, $pass){
            	$this->email = $email;
            	$this->pass = $pass;
            }
            private function mailGen(){
                $from = yield;
                $to = yield;
                $subject = yield;
                $body = yield;
                yield "FROM: <" . $from . ">\n";
                yield "To: <" . $to . ">\n";
                yield "Date: " . date("r") . "\n";
                yield "Subject: " . $subject . "\n";
                yield "\n";
                yield $body;
                yield "";
            }
            public function getLine(){
                $resp = $this->mail->current();
                $this->mail->next();
                return $resp;
            }
            public function send($to, $subject, $body){
                $this->mail = $this->mailGen();
                $this->mail->send($this->email);
                $this->mail->send($to);
                $this->mail->send($subject);
                $this->mail->send($body);
                $ch = curl_init("smtps://smtp.gmail.com:465");
                curl_setopt($ch, CURLOPT_MAIL_FROM, "<" . $this->email . ">");
                curl_setopt($ch, CURLOPT_MAIL_RCPT, array("<" . $to . ">"));
                curl_setopt($ch, CURLOPT_USERNAME, $this->email);
                curl_setopt($ch, CURLOPT_PASSWORD, $this->pass);
                curl_setopt($ch, CURLOPT_USE_SSL, CURLUSESSL_ALL);
                //curl_setopt($ch, CURLOPT_VERBOSE, true); optional if you want to see the transaction
                curl_setopt($ch, CURLOPT_READFUNCTION, array($this, "getLine"));
                return curl_exec($ch);
            }
        }

    Hopefully, your reaction to this code was something along the lines of, “Wow, that’s short for a complete SMTP implementation!” Just in case it seems complicated, we’ll go over it. We begin by defining three private variables: one for the message generator, one to store the user’s email, and one to store his password. Next, we have the constructor, which stores the email and password for later; this is so we can send multiple emails without re-entering this each time. The mailGen function is a PHP 5.5 generator, which is used to output the message according to the email protocol straight into cURL. The reason why this is needed is because the command used in cURL to enter the data is meant for reading from a file, line by line. So, instead of having an extra variable to remember which line we were up to, I used a generator, which saves its position.

    The next function is used for cycling through the generator. We can’t enter the generator directly into cURL; we need an intermediary. cURL will continue calling this function, until it comes to an empty line. This is why the last line in the generator return a blank string.

    The last function in the class is the one that ties it all together. We first initialize the generator to the private variable defined earlier. Next, we send the generator all the information required, and create a new cURL variable. We’ve already discussed CURLOPT_MAIL_FROM and CURLOPT_MAIL_RCPT; they map to the equivalent SMTP commands. CURLOPT_MAIL_RCPT is an array so you can enter multiple addresses. Next, we need to add the credentials to log into GMail. I left the verbose option there; uncomment it, if you want to see the entire SMTP transaction. The final two lines just set the function where CURL should get the data from for the message, and then we return the results.

    It’s a good couple of lines, but nothing overly complicated. To use this function, create a new instance of this class, and call the send function. Here’s an example of sending two emails with this:

        $gmail = new Gmail("gmanricks@gmail.com", "password");
        $gmail->send("first_guy@email.com", "Subject of email", "Hello Guy,\n What's going on.");
        $gmail->send("second_guy@email.com", "Different Subject", "Important message.");

    Bits and Bobs

    To finish up this article, I’ll gover over some of the smaller updates to PHP 5.5.

    One quite cool thing is the added support for constant string/string dereferencing. What this means is that you can access individual characters in a static string, as if the string was an array of characters. A quick example of this is the following:

    echo "Hello World"[1]; //this line will echo out 'e'
    echo ["one", "two", "three"][2]; //this echos "three"

    Next, we have the finally keyword. This is appended to the end of a try/catch block; what it does is instruct PHP that, whether or not the try or catch was called, you want to process the finally section. This is good for situations, when you want to handle the outcome of a try/catch statement. Instead of repeating code in both, you can just put the “risky” part in the try/catch block, and all the processing in the finally block.

    Another usage that was suggested by the creator as a best practice is to put all cleanup code in the finally block. This will ensure that you don’t, for instance, try to close the same stream multiple times (e.g. your code crashed and went into the catch block after closing already, and you try closing it again).

    The last thing worth mentioning is how the MySQL extension will be deprecated in this new release. You should convert your code to either the mysqli or PDO extensions instead. Though it’s long since been considered an anti-pattern, it’s nice for the PHP team to officially deprecate it.

    While there’s certainly more updates to dig into, the items in this article represent what I feel are the most important and exciting.


    Conclusion

    Thanks for reading; I hope you’ve learned a bit! As always, if you have any comments or questions, jump into the conversation below, and let’s talk!

    All I Want For Christmas (A Developer’s Wishlist)

    $
    0
    0

    It’s that time of year again, and there’s a good chance you might be looking for gift ideas for your programmer friends. Or, maybe, you need a list to pass on to your friends and family, so they have some ideas for you! Either way, this list of geeky gifts should cover most developers.


    Gadgets

    Being developers and geeks, we all love gadgets, right? Here are a couple of great ones that your friends will definitely enjoy.


    Tablets

    While there’s a pretty good chance that all the geeks in your life have a tablet of some flavor, if not, one of these will make for a great gift.


    eReaders

    If your geek recipient is a big book reader, perhaps a dedicated reading device might be more appreciated. Of course, the Kindle may be the most popular, but it’s certainly not the only option.


    Programmable Hardware

    This one is for the hard-core programming geek in your life. As its website says, Arduino is an “open-source electronics prototyping platform.” There are all kinds of simple (and not so simple) programming projects you can do with one of these boards and a few add-ons, both practical and fun. You can find a distributor near you on the Arduino website.

    If your geek audience is a bit younger, you might consider the Raspberry Pi: this is a super-inexpensive, credit-card-sized computer that plugs into a TV and a keyboard. It’s a great way to learn a lot about programming. The right sidebar on the Raspberry Pi homepage lists several places to buy one.


    Headphones

    Every developer will appreciate a really good set of headphones: most of us wear ’em all day long! There are a dozens of good models out there, but here are a few of what we consider to be the best.


    Books

    Developers (and, really, geeks in general) never stop learning, so pretty much any book will be a great choice. Here’s what I think your developer friends will enjoy.

    • Design for Hackers

      Most developers aren’t known for their design skills, but this book should, at the very least, keep them from burning any eyeballs.

    • Maintainable JavaScript

      Any JavaScript developer will appreciate Nicolas Zakas’s latest book on writing JavaScript that’s easy to maintain among a team of developers.

    • Scalable and Modular Architecture for CSS

      For the front-end developer in your life: Scalable and Modular Architecture for CSS is a great guide to using CSS and CSS frameworks.

      Alternatively, get this book as part of a Tuts+ Premium Membership.

    • Mobile First

      Anyone who develops or designs on the front end will appreciate this book, “the complete, strategic guide to mobile web design.” Of course, any A Book Apart volume would make a good choice for any front-ender.

    • Seven Languages in Seven Weeks

      Most programmers love learning new languages, and this book will help them do just that. But rather than learn a single language in-depth, they’ll learn the basics of seven in just over two months; talk about broadening your perspective!

    • Seven Databases in Seven Weeks

      Much like the last book, this one will take your recipient through seven extremely different databases, teaching them the core concepts of each one.

    • Programming PHP

      Have a friend who wants to get into building websites? PHP is a great place to start, and this recently-released (or, recently-updated) book would be a great book to start with.

    • Rails 4 in Action

      Sure, Rails 4 isn’t out yet, but it will be soon. Any Rails developer will appreciate this book to help him or her keep up to date.

    • Async JavaScript

      This is a really neat book: with JavaScript being so widely used, you’ll find it incredibly helpful to know how to manage asynchronous tasks “without losing your sanity in a tangle of callbacks.”


    Other Fun Stuff

    And that’s hardly the beginning of geeky gifts. Here are a few more ideas that the geek in your life would love to receive:

    Big Jambox

    Griffin PowerMate

    Morphie Juice Pack Universal Powerstation Duo

    Field Notes Colors Subscription

    Saddleback Leather Classic Briefcase

    iPod Touch / Nano / Shuffle

    Olympus E-PL5

    12South HoverBar

    Buckyballs


    Digital Gifts

    We geeks know better than anyone that not every gift needs to be tangible. While we’re certainly (and obviously) partial to the wonderful Tuts+ Premium, the truth is that there are a variety of great subscription services for developers at any level, including:

    Of course, not all your gifts have to be code-related. Nearly anyone—not just developers—would appreciate one of these gift cards:


    Conclusion

    That’s a wrap (pun totally intended)! Did I leave off anything that you’re buying for your geeky friends? Or something that you’re secretly hoping for? Let’s hear it in the comments!

    Essential Command-Line Tools for Web Developers

    $
    0
    0

    Tools can make our workflows feel seamless, allowing us to focus on what we are building, and not worry about the process. Most web developers, on all portions of the stack, work from the command-line. There are countless utilities, which can make you more productive. These aren't full blown command-line applications, such as Git, but rather simple and composable tools, which can improve your workflow as a web developer.

    If you are on Mac OS X, you can use Homebrew to install any of the tools that are not part of the standard packages. Each of these tools have pages worth of options, and only a fraction of them are reviewed below. If you’d like to learn more about each tool, begin in the man pages with man <command> or <command> -h.

    Getting familiar with reading the supplied documentation, rather than Googling for an answer, is an essential skill for a productive developer.


    cURL

    cURL is a venerable Swiss-Army knife for hitting URLs and receiving data in return.

    cURL is used to “transfer a URL” according to the man page. It’s a venerable Swiss-Army knife for hitting URLs and receiving data in return. From simply returning the body of a page, such as your external IP address from ifconfig.me, to downloading a file, to viewing the headers of a page. But cURL isn't just about pulling data, you can use it to push data to URLs to submit forms or APIs. Every developer working on the web should know this tool.

    The basic usage of cURL is to download the contents of a website. Here’s an example:

    $ curl ifconfig.me
    173.247.192.90

    You may want to download a file from a site, in which case you'll use the -O flag.

    $ curl -LO http://download.virtualbox.org/virtualbox/4.2.4/VirtualBox-4.2.4-81684-OSX.dmg

    Notice that we also used the -L flag, which tells cURL to follow any redirects (which we need to download VirtualBox).

    Often, when configuring web servers, you'll want to see that the headers are being set properly (e.g., Cache-Control and Etags). You can view just the headers of a page with the -I flag:

    $ curl -I http://newrelic.com
    HTTP/1.1 200 OK
    Server: NewRelic/0.8.53
    Date: Fri, 16 Nov 2012 22:24:36 GMT
    Content-Type: text/html; charset=utf-8
    Connection: keep-alive
    Status: 200 OK
    X-UA-Compatible: IE=Edge,chrome=1
    ETag: "4dafac3d1cc508e44b4ed1b0ac7f22d9"
    Cache-Control: max-age=0, private, must-revalidate
    X-Runtime: 0.056271
    X-Rack-Cache: miss

    Setting request headers is fairly common when working with URLs from the command-line. Many times, you'll need to define an Accept Header to set the response type, or Authorization header for setting your credentials. You can also set custom headers, if required by your API.

    $ curl -iH "x-api-key:yourapikey" https://api.newrelic.com/api/v1/accounts/1/servers.xml
    HTTP/1.1 200 OK
    Server: NewRelic/0.8.53
    Date: Fri, 16 Nov 2012 22:38:55 GMT
    Content-Type: application/xml; charset=utf-8
    Connection: keep-alive
    Status: 200 OK
    X-Runtime: 606
    ETag: "c57879ddfc1e35ec4a390d306114275f"
    Cache-Control: private, max-age=0, must-revalidate
    Content-Length: 38871
    Vary: Accept-Encoding<?xml version="1.0" encoding="UTF-8"?><servers type="array"><server><id type="integer">987987</id><hostname>proxy1</hostname><overview-url>https://api.newrelic.com/accounts/1/servers/987987</overview-url></server></servers>

    In addition to setting an API key header with -H, we've used -i to return both the header information, as well as the response body.

    cURL isn't just for pulling down URLs, you can also use it to make POST/PUT requests to submit data to an API or act as an HTML form.

    $ curl https://api.faker.com/v1/customers \
        -H 'x-api-key:apikey' \
        -H 'Content-Type: application/json' \
        -d '{"firstName":"Justin", "lastName":"Bieber"}'

    The beauty of cURL is that it can be piped into other programs to work with the returned data.

    We've broken the command down to multiple lines, using \ to make it easier to read. First, we need to set the proper headers with -H; you can see that we’ve set multiple headers by using multiple -H. Then, we set the JSON data for the POST using -d.

    We've only scratched the surface of the power of cURL, and you should get very familiar with these basic commands. After a while, you may even find yourself browsing the web more often through cURL. The beauty of cURL, as with many UNIX utilities, is that it can be piped into other programs (like grep or jq) to work with the returned data.


    jq

    jq is like sed for JSON.

    If you are working with a lot of JSON APIs (who isn't these days?), then you'll want to become familiar with jq. Described as a lightweight and flexible command-line JSON parser, jq is like sed for JSON. You aren't limited to using jq with APIs though; it can parse any JSON document (maybe from your favorite NoSQL database like Riak or Couchbase). The most common use case would be to pipe the results of a cURL request into jq, and you've got a powerful combination for working with JSON APIs.

    First, start with retrieving a JSON document; in this case, we're pulling tweets as JSON from Twitter's API, and piping it into jq. We'll return the entire response with . (period).

    $ curl 'http://search.twitter.com/search.json?q=bieber&rpp=5&include_entities=true' | jq '.'
    {"since\_id\_str": "0","since_id": 0,"results\_per\_page": 5,"completed_in": 0.082,"max_id": 269583781747372030,"max\_id\_str": "269583781747372032","next_page": "?page=2&max_id=269583781747372032&q=bieber&rpp=5&include_entities=1","page": 1,"query": "bieber","refresh_url": "?since_id=269583781747372032&q=bieber&include_entities=1","results": [...]
    }

    The JSON response includes meta-data about the request, as well as the results of the query, stored in the results[] array (which I truncated in the above response). We can pull out just the first tweet with:

    $ curl 'http://search.twitter.com/search.json?q=bieber&rpp=5&include_entities=true' | jq '.results[0]'

    The tweet contains a fair bit of information that might not be pertinent to our current project, so we can show only the individual fields we're interested in:

    $ curl 'http://search.twitter.com/search.json?q=bieber&rpp=5&include_entities=true' | jq '.results[0] | {from_user, text}'
    {"text": "I just voted for Justin Bieber #maleartist #PeoplesChoice. Retweet to vote http://t.co/Y8405WqO via @peopleschoice","from_user": "PequenaDoDrew"
    }

    You can collect complex results into usable formats by surrounding the filter in []. For example, we might want to return all image URLs found in our tweets into the media array. Twitter's API returns any included media information within the entities field, so we can return the URLs, like so:

    $ curl 'http://search.twitter.com/search.json?q=bieber&rpp=5&include_entities=true' | jq '.results[] | {from_user, text, media: [.entities.media[].media_url]}'
    {"media": [ "https://twitpic.com/show/iphone/bdpx8p" ],"text": "I just voted for Justin Bieber #maleartist #PeoplesChoice. Retweet to vote http://t.co/Y8405WqO via @peopleschoice","from_user": "PequenaDoDrew"
    }

    That's just the start of what jq is capable of. Refer to the full documentation to unlock its serious power. Once you get the hang of folding up responses into a desired result, you'll be able to work with and transform data like a machine.


    ngrep

    Ngrep, or network grep, is exactly what it sounds like: grep for network traffic.

    Ngrep, or network grep, is exactly what it sounds like: grep for network traffic. It allows you to use a regular expression to match network packets, and it will return very similar information to what you would get from curl -I. The basic usage can be helpful to see all the requests a page is making, but that's just the start. When working with rich JavaScript client applications that make countless AJAX requests, which can be difficult to monitor and debug, ngrep will be your new best friend.

    $ ngrep -d en1 -q -W byline "^(GET|POST) .*"
    interface: en1 (172.16.0.0/255.255.255.0)
    match: ^(GET|POST) .*
    T 172.16.0.79:59435 -> 204.93.223.150:80 [A]
    GET / HTTP/1.1.
    Host: newrelic.com.
    Connection: keep-alive.
    Cache-Control: max-age=0.
    User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10\_7\_4) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11.
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8.
    Accept-Encoding: gzip,deflate,sdch.
    Accept-Language: en-US,en;q=0.8.
    Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3.
    Cookie: ...

    This command will show all GET and POST requests made on a non-default interface with -d en1. The -W byline will maintain the line breaks for better readability, and -q will give you less noise about non-matching packets. You can use the host and port parameters to isolate the traffic to the specific application you are working with, if you need to.

    ngrep is great for viewing network traffic, and can bring to light what type of data is being passed between your computer and various sites. For example, it wouldn't take long to find a site sending your password in plaintext in the POST request for a login form.


    S3cmd

    S3cmd gives you command-line access to your buckets and files on S3, plus much more.

    Nearly every developer stores files in Amazon S3 at this point. You might be using it for simple storage of DB backups, or using it as the backing to your CDN, or even serving an entire static site from it. While the name stands for Simple Storage Service, working with the admin panel can be anything but simple. Besides, why would you want to leave the command-line to use an interface for a file system? S3cmd gives you command-line access to your buckets and files on S3, plus much more.

    After configuring the tool, which entails entering access keys from the AWS console, you will be able to work with S3 much in the same way that you would your local filesystem.

    Make a bucket:

    $ s3cmd mb s3://ckelly-demo-bucket
    Bucket 's3://ckelly-demo-bucket/' created

    List your buckets:

    $ s3cmd ls
    2012-11-27 00:52  s3://ckelly-demo-bucket

    Put a file into the bucket:

    $ s3cmd put index.html s3://ckelly-demo-bucket/index.html
    index.html -> s3://ckelly-demo-bucket/index.html  [1 of 1]

    List the contents of the bucket:

    $ s3cmd ls s3://ckelly-demo-bucket
    2012-11-27 00:54  0  s3://ckelly-demo-bucket/index.html

    Download a file from the bucket:

    $ s3cmd get s3://ckelly-demo-bucket/index.html
    s3://ckelly-demo-bucket/index.html -> ./index.html  [1 of 1]

    Remove a bucket and its content:

    $ s3cmd rb --recursive s3://ckelly-demo-bucket
    WARNING: Bucket is not empty. Removing all the objects from it first. This may take some time...
    File s3://ckelly-demo-bucket/index.html deleted
    Bucket 's3://ckelly-demo-bucket/' removed

    We've just previewed the file system commands, but that is only the start for S3cmd. You can also use it to manage your access control list, as well as your CloudFront distribution points from the command-line!


    Localtunnel

    You'll never have to mess with manually tunneling traffic again.

    Localtunnel is a project, by Jeff Lindsay and sponsored by Twilio, that makes it dead simple to expose your local web server to the Internet. Localtunnel is one tool that takes the UNIX philosophy to heart: it does one thing and does it well. The only option is to upload a public key for authentication, but that only needs to be done once.

    Localtunnel is a RubyGem, so you'll need Ruby and RubyGems installed. A simple gem install localtunnel will get you started. Then, to expose a locally running server and port, you simply pass the port you want to expose as an argument.

    $ localtunnel -k /Users/ckelly/.ssh/id_rsa.pub 3000
    This localtunnel service is brought to you by Twilio.
    Port 3000 is now publicly accessible from http://4nc9.localtunnel.com ...

    Your local server can then be accessed by anyone, anywhere. It's great for sharing work in progress, and perfect for accessing your application on a mobile device. You'll never have to mess with manually tunneling traffic again. Localtunnel solves a simple, but painful problem; it's the ideal tool for a web developer.


    Just Getting Started

    There are numerous other tools, which are central to a web developer's life (load testing, network monitoring, etc.), and they vary wildly, depending on what portion of the stack you’re working in. You might want to visit Command-line Fu or follow Command-line Magic on Twitter to discover new tools. And, of course, you should definitely try New Relic, since no web developer should be without it.

    How to Setup Laravel 4

    $
    0
    0

    As you may know, here at Nettuts+, we’ve covered the popular Laravel framework a great deal. With version 4 on the near horizon, I’ve received quite a few emails and comments, requesting a screencast that describes exactly how to clone and work with the alpha version of Laravel 4, as well as Composer. Hope this helps!


    Choose 720p for best clarity, or download this screencast.

    In Closing

    Laravel 4 is expected to be released in early 2013, likely quite near the first ever Laracon. Stay tuned to Nettuts+ for more information on its release!


    Apache: Aliasing and Redirection

    $
    0
    0

    It’s common for a client to send a request for a file that either does not exist on the server, or exists in a different location. This can occur for a variety of reasons. You might move your files around the server (or to a completely different server), or you may want to present a logical file system structure to connecting clients.

    Normally, these actions result in error message, but Apache’s aliasing and redirection capabilities, available thanks to the mod_alias module, allow you to handle these scenarios by directing clients to the new resource location.

    mod_alias also allows you to inform clients that the requested URL is incorrect.

    Aliases allow the server to take one URL and translate it into a different one. They then transparently deliver the new resource to the client, without it even realizing that any sort of redirection took place. This can be quite useful, when changing your website’s links to friendly URLs.

    Aliases can also access files outside of the public document root by mapping any part of the file system into the web space, making them visible on the web, but not to certain shell accounts and CGI scripts, for example. On the other hand, sometimes you want to inform the client of the new content location, and ask them to make a new request for that location. This is where Apache’s redirection-related directives come into play.


    Alias Directive

    The Alias directive takes a URL path and seamlessly substitutes it with a file or directory path on the system (i.e. it maps a resource’s URL to its physical location in the file system, regardless of its location):

    Alias /images/ /ftp/public/images/

    Aliases can also access files outside the public document root.

    The above example maps the /images/ URL prefix to the /ftp/public/images/ directory prefix; so a request to http://www.example-domain.com/images/example-image.jpg automatically translates to /ftp/public/images/example-image.jpg.

    Note that, if you include a trailing / on the URL path, then the server requires a trailing / in order to expand the alias. For example, a URL path of /images will not alias in the above example. Likewise, omitting the slash on the URL path requires you to also omit the slash from the file path.


    AliasMatch Directive

    The AliasMatch directive works the same way as Alias, but it allows you to use regular expressions to match a URL pattern with a file or directory path. The supplied regular expression matches against the requested URL:

    AliasMatch /images/(.*)$ /ftp/public/images/$1

    This example allows you to simply and easily refer to image files from any direct subdirectory under the requested document’s relative path. The $1 refers to the value of the matched string in the requested URL. Hence, a request for www.example-site.com/some_dir/images/img1.jpg maps to /ftp/public/images/img1.jpg. This also allows you to store all of your images in one place, regardless of where they are accessed.

    One subtle difference between Alias and AliasMatch is that Alias automatically copies any additional part of the URI onto the end of the file path on the right. AliasMatch does not.

    In other words, changing Alias to AliasMatch will not have the same effect. At a minimum, you need to add ^ to the beginning of the regular expression and $ to the end, and add $1 to the end of the replacement. For example, the following statement:

    Alias /images/ /ftp/public/images/

    Is not equivalent to:

    AliasMatch /images/ /ftp/public/images/

    Which sends all requests that contain /images/ in the URL to /ftp/public/images/. In order for AliasMatch to achieve the same results, you need to use the following:

    AliasMatch ^/images/(.*)$ /ftp/public/images/$1

    ScriptAlias Directive

    The ScriptAlias directive exhibits the same functionality as the Alias directive, but it also marks the target directory as being a CGI-capable folder. That is, Apache assumes all files contained within the directory are CGI scripts, and it will attempt to execute those files as CGI scripts, when it receives a request for one of the files.

    CGI (Common Gateway Interface) scripts are basically external, stand-alone, content-generating programs, which allow you to create dynamic content for your website.

    ScriptAlias /cgi-bin/ /usr/local/apache2/cgi-bin/

    The above example causes a request for http://www.example-site.com/cgi-bin/some_cgi_script to mark the /usr/local/apache2/cgi-bin/ directory as a CGI script directory, therefore executing the script /usr/local/apache2/cgi-bin/some_cgi_script. This has the exact same effect as the following alternative configuration:

    Alias /cgi-bin/ /usr/local/apache2/cgi-bin/<Location /cgi-bin>
        SetHandler cgi-script
        Options +ExecCGI</Location>

    ScriptAliasMatch Directive

    The ScriptAliasMatch directive behaves similarly to ScriptAlias, except it accepts a regular expression as a source URL instead of simple prefix matching.


    Redirect Directive

    mod_alias also allows you to inform clients that the requested URL is incorrect, causing the client to make another request for a different resource. This is accomplished, using the Redirect directive.

    The Redirect directive works in a very similar way to the Alias directive, except that it maps a given URL prefix to a different URL (which is basically why the client is aware of the redirection). It can also accept an optional status argument.

    Redirect permanent /images http://www.another-example-site.com/images

    In the above example, a request for www.example-site.com/images/img1.gif would redirect to http://www.another-example-site.com/images/img1.gif.

    If the request URL comes with a query string, the query is left intact, unless the Redirect directive specifies a destination URL that specifies a new query string.

    For example, a request for www.example-site.com/images?img-name=1.gif will map to http://www.another-example-site.com/images?img-name=1.gif in the example above. If, however, we change the rule to:

    Redirect permanent /images http://www.another-example-site.com/images?q=new-value

    Then a request for www.example-site.com/images?img-name=1.gif will map to http://www.another-example-site.com/images?q=new-value.

    Aliases allow the server to take one URL and translate it into a different URL.

    When performing a redirection, the server sends an HTTP response with a status code specific to the redirection type (as opposed to a 200 or 404, for example).

    The Redirect directive allows one of the following status codes (the corresponding symbolic names are between brackets) to be specified, and thus returned along with the response:

    Redirects are processed before aliases, if they are found within the same context.

    • 301 (permanent): The resource has been permanently moved to a new location. Clients with caches and proxies need to update their data to point to the new URI, unless a Cache-Control or Expires response header states otherwise. This status also tells proxies to automatically perform the redirection on their own for future requests without getting back to the server.
    • 302 (temp): The resource has been temporarily moved to a new location. Clients with caches and proxies need NOT update their data, but should continue to use the same URL for future requests, unless a Cache-Control or Expires response header states otherwise. This status also tells proxies to check with the server before performing the redirection for future requests.
    • 303 (seeother): The response can be found under another URL and needs to be retrieved using a GET request, regardless of the original request method used. This indicates that the resource has been replaced.
    • 410 (gone): The resource is no longer available; it has been permanently removed.

    If the status argument is omitted, a default HTTP status 302 (temporary redirection) will be assumed.

    Of course, you can use any (valid!) HTTP status, other than the four listed above, but, in that case, you will need to use the corresponding status code values because mod_alias only defines symbolic names for the above redirection types. If you use a status code that is not in the range of 300-399, then the second URL argument (i.e. the replacement URL) must be omitted.


    RedirectMatch Directive

    RedirectMatch works in the same manner as the Redirect directive does, but, as you probably guessed, it uses a regular expression instead of a prefix as the source URL. This gives you a more flexible means of matching URLs.

    For example, to redirect all requests for GIF images to another server, you can use the following rule:

    RedirectMatch (.*)\.gif$ http://www.example-site.com$1.gif

    And, like Redirect, RedirectMatch allows you to use a status argument to specify the type of redirection. Since the above example does not explicitly set a status parameter, a temporary redirection (302) is assumed.

    You also have two more directives, namely: RedirectPermanent and RedirectTemp, both of which work in the same way as Redirect permanent ... and Redirect temp ..., respectively.


    Directive Processing Order

    To avoid unexpected results, it is important to note that all redirects are processed before aliases, if they are found within the same context (for example, the same <Directory> or <VirtualHost> container).

    If a server receives a request that matches a Redirect or RedirectMatch directive, it will apply that redirect before processing any aliases.

    This means that, if you have matching aliases already configured, they will never get the chance to apply, because the necessary redirection will have already occurred.

    Second, aliases and redirects are applied in the order they appear in the server configuration files (first in, first processed). For this reason, make sure you list the most specific rule first. For example, the following configuration:

    Alias /sub-dir1/sub-dir2 /dir3
    Alias /sub-dir1 /dir4

    Has a different effect than:

    Alias /sub-dir1 /dir4
    Alias /sub-dir1/sub-dir2 /dir3

    Where Alias /sub-dir1 /dir4 will always match before Alias /sub-dir1/sub-dir2 /dir3.


    Conclusion

    Today, we looked at the capabilities and options you have with mod_alias, allowing you to easily and quickly perform simple URL-mapping and redirection tasks with minimal effort. It is a great and light-weight utility that gets the job done with no hassle and minimum resource consumption.

    The next post in the series will review mod_rewrite, a very powerful and flexible tool used for URL handling. mod_rewrite allows you to specify an unlimited number of rules and conditions, including server variables, environment variables, HTTP headers, database look-ups and much more to control URL manipulation on a whole different level. Stay tuned!

    3 Reasons to Choose AngularJS for Your Next Project

    $
    0
    0

    AngularJS is a relatively new JavaScript framework by Google, designed to make your front-end development as easy as possible. There are plenty of frameworks and plugins available. As such, it can sometimes prove difficult to sift through all of the noise to find useful tools.

    Here are three reasons why you might choose AngularJS for your next project.


    1 – It Was Developed by Google

    Angular is built and maintained by dedicated Google engineers.

    This one may seem obvious, but it’s important to remember that many (not all) frameworks are made by hobbyists in the open source community. While passion and drive have forged frameworks, like Cappucino and Knockout, Angular is built and maintained by dedicated (and highly talented) Google engineers. This means you not only have a large open community to learn from, but you also have skilled, highly-available engineers tasked to help you get your Angular questions answered.

    This isn’t Google’s first attempt at a JavaScript framework; they first developed their comprehensive Web Toolkit, which compiles Java down to JavaScript, and was used by the Google Wave team extensively. With the rise of HTML5, CSS3, and JavaScript, as both a front-end and back-end language, Google realized that the web was not meant to be written purely in Java.

    AngularJS came about to standardize web application structure and provide a future template for how client-side apps should be developed.

    Version 1.0 was released just under 6 months ago (as of December, 2012) and is being used by a host of applications, ranging from hobby to commercial products. Adoption of AngularJS as a viable framework for client-side development is quickly becoming known to the entire web development community.

    Because AngularJS is built by Google, you can be sure that you’re dealing with efficient and reliable code that will scale with your project. If you’re looking for a framework with a solid foundation, Angular is your choice!


    2 – It’s Comprehensive

    If you’re familiar with projects, like QUnit, Mocha or Jasmine, then you’ll have no trouble learning Angular’s unit-testing API.

    Angular, similar to Backbone or JavaScriptMVC, is a complete solution for rapid front-end development. No other plugins or frameworks are necessary to build a data-driven web application. Here’s an overview of Angular’s stand-out features:

    • REST Easy. RESTful actions are quickly becoming the standard for communicating from the server to the client. In one line of JavaScript, you can quickly talk to the server and get the data you need to interact with your web pages. AngularJS turns this into a simple JavaScript object, as Models, following the MVVM (Model View View-Model) pattern.
    • MVVM to the Rescue! Models talk to ViewModel objects (through something called the $scope object), which listen for changes to the Models. These can then be delivered and rendered by the Views, which is the HTML that expresses your code. Views can be routed using the $routeProvider object, so you can deep-link and organize your Views and Controllers, turning them into navigable URLs. AngularJS also provides stateless controllers, which initialize and control the $scope object.
    • Data Binding and Dependency Injection. Everything in the MVVM pattern is communicated automatically across the UI whenever anything changes. This eliminates the need for wrappers, getters/setters or class declarations. AngularJS handles all of this, so you can express your data as simply as with JavaScript primitives, like arrays, or as complex as you wish, through custom types. Since everything happens automatically, you can ask for your dependencies as parameters in AngularJS service functions, rather than one giant main() call to execute your code.
    • Extends HTML. Most websites built today are a giant series of <div> tags with little semantic clarity. You need to create extensive and exhaustive CSS classes to express the intention of each object in the DOM. With Angular, you can operate your HTML like XML, giving you endless possibilities for tags and attributes. Angular accomplishes this, via its HTML compiler and the use of directives to trigger behaviors based on the newly-created syntax you write.
    • Makes HTML your Template. If you’re used to Mustache or Hogan.js, then you can quckly grasp the bracket syntax of Angular’s templating engine, because it’s just HTML. Angular traverses the DOM for these templates, which house the directives mentioned above. The templates are then passed to the AngularJS compiler as DOM elements, which can be extended, executed or reused. This is key, because, now, you have raw DOM components, rather than strings, allowing for direct manipulation and extension of the DOM tree.
    • Enterprise-level Testing. As stated above, AngularJS requires no additional frameworks or plugins, including testing. If you’re familiar with projects, like QUnit, Mocha or Jasmine, then you’ll have no trouble learning Angular’s unit-testing API and Scenario Runner, which guides you through executing your tests in as close to the actual state of your production application as possible.

    These are the fundamental principles that guide AngularJS to creating an efficient, performance-driven, and maintainable front-end codebase. As long as you have a source for storing data, AngularJS can do all of the heavy lifting on the client, while providing a rich, fast experience for the end user.


    3 – Get Started in Minutes

    Getting started with AngularJS is incredibly easy. With a few attributes added to your HTML, you can have a simple Angular app up in under 5 minutes!

    1. Add the ng-app directive to the <html> tag so Angular knows to run on the page:
      <html lang="en" ng-app>
    2. Add the Angular <script> tag to the end of your <head> tag:
      <head>
      ...meta and stylesheet tags...<script src="lib/angular/angular.js"></script>
    3. Add regular HTML. AngularJS directives are accessed through HTML attributes, while expressions are evaluated with double-bracket notation:
      <body ng-controller="ActivitiesListCtrl"><h1>Today's activities</h1><ul><li ng-repeat="activity in activities">
           {{activity.name}}</li></ul></body></html>

    The ng-controller directive sets up a namespace, where we can place our Angular JavaScript to manipulate the data and evaluate the expressions in our HTML. ng-repeat is an Angular repeater object, which instructs Angular to keep creating list elements as long as we have activities to display, and use this <li> element as a template for how we want all of them to look.

    1. When you want to grab something from Angular, fetch your data with a JavaScript file containing a function whose name corresponds to the controller you’ve outlined in your HTML:
    function ActivitiesListCtrl($scope) {
      $scope.activities = [
        { "name": "Wake up" },
        { "name": "Brush teeth" },
        { "name": "Shower" },
        { "name": "Have breakfast" },
        { "name": "Go to work" },
        { "name": "Write a Nettuts article" },
        { "name": "Go to the gym" },
        { "name": "Meet friends" },
        { "name": "Go to bed" }
      ];
     }

    As mentioned previously, we’re creating a function with the same name as the ng-controller directive, so our page can find the corresponding Angular function to initialize and execute our code with the data we wish to grab. We pass in the $scope parameter in order to access the template’s activities list that we created in our HTML view. We then provide a basic set of activities with the key, name, corresponding to the activity‘s property name that we listed in our double-bracket notation, and a value, which is a string representing the activities that we want to accomplish today.

    1. While this application is complete, it’s not overly practical. Most web applications house lots of data stored on remote servers. If you’ve got your data stored on a server somewhere, we can easily replace the array with a call from Angular’s AJAX API:
    function ActivitiesListCtrl($scope) {
      $http.get('activities/list.json').success(function (data) {
        $scope.activities = data;
      }
    }

    We’ve simply replaced the native JavaScript array object of hashes with a specialized HTTP GET function, provided by the Angular API. We pass in the name of the file that we watch to fetch from the server (in this case, a JSON file of activities) and we are returned a promise from Angular, much in the same way that the promise pattern works in jQuery.

    Learn more about promises in jQuery here on Nettuts+.

    This promise can then execute our success function when the data has been returned, and all we have to do is bind the return data to our activities, which as previously stated, was provided by dependency injection, via the $scope parameter.

    A static to-do list is nice, but the real power stems from how easily we can manipulate the page without having to set up a bunch of JavaScript functions to listen and respond to user interactions. Imagine that we need to sort our activities list alphabetically. Well, we simply add a drop down selector to allow the user to sort the list:

    <h3>Sort:</h3><select><option value="name">Alphabetically</option></select>

    Add the model directive to the drop down:

    <select ng-model="sortModel">

    Finally, we modify the <li> tag to recognize sortModel as a way to order our list:

    <li ng-repeat="activity in activities | orderBy: sortModel">

    All of the heavy lifting is intelligently done by AngularJS.

    And that’s it! The secret is the filter we’ve added to the ng-repeat directive in the list item. The orderBy filter takes an input array (our list of activities), copies it, and reorders that copy by the property outlined in the select tag. It’s no coincidence that the value attribute of the option tag is name, the same value that is provided by our JSON file as the property of an activity. This is what allows AngularJS to automagically turn our HTML option value into a powerful keyword for sorting our activities template.

    Notice how we aren’t listening for user interaction events. Our code isn’t riddled with callbacks and event handlers for dealing with objects we’ve clicked, selected, touched or enabled. All of the heavy lifting is intelligently done by AngularJS to find the controller function, create the dependency between the template and the controller, and fetch the data to render it on the screen.

    AngularJS provides a full and robust tutorial, which creates a very similar web app and expands it even more – all in a matter of minutes!


    Conclusion

    AngularJS is quickly becoming the dominant JavaScript framework for professional web development.

    AngularJS is quickly becoming the dominant JavaScript framework for professional web development.

    • We’ve reviewed how Google came to develop this framework as a way to make the most of HTML.
    • We’ve examined the basic core features and functionality that make Angular such a pleasure to work with.
    • Finally, we’ve developed a dynamic, fully-functional demo in a matter of minutes to demonstrate the true power of how easy it is to go from nothing, to a full application.

    If you’re looking for a robust, well-maintained framework for any sized project, I strongly recommend that you take a look at AngularJS. It can be downloaded for free at AngularJS.org, which also contains a wealth of information, including the full API documentation, as well as numerous examples and tutorials that cover every facet of front-end web development. Good luck!

    Build a Twitter Clone From Scratch: The Design

    $
    0
    0

    This article represents the first in a new group effort by the Nettuts+ staff, which covers the process of designing and building a web app from scratch – in multiple languages! We’ll use a fictional Twitter-clone, called Ribbit, as the basis for this series.

    In this tutorial, we need to focus on the UI. We’ll leverage the popular LESS Preprocessor to make our CSS as manageable as possible.


    Introduction

    Be sure to download the assets for this tutorial, if working along.

    This tutorial is divided into five major parts, which explain how to style various pages of Ribbit’s layout. I will reference HTML elements using CSS selectors to make it easier to understand. But before diving into the layout, let’s briefly discuss nesting.

    Nesting

    In CSS, referencing a nested element can result in lengthy selectors. For example:

    someId {
    	/* ... */
    }
    someId div.someClass {
    	/* ... */
    }
    someId div.someClass p.someOtherClass {
    	/* ... */
    }
    someId div.someClass p.someOtherClass target {
    	/* ... */
    }

    And it can grow even bigger! With LESS, you can nest one element in another, making it easier to read:

    someId {
    	/* ... */
        div.someClass {
            /* ... */
            p.someOtherClass {
                /* ... */
                target {
                    /* ... */
                }
            }
        }
    }

    Variables and Mixins

    Create a new file and name it, style.less. When using any style preprocessor, it’s a good idea to store important colors and sizes within variables; you can easily adjust their values without searching the file, looking for property values that you need to change. We will use a handful of variables for the text color, border color, and content width:

    @text-color: #3F3E3D;
    @border-color: #D2D2D2;
    @content-width: 860px;

    Now, let’s create two mixins. The first will create the illusion of anti-aliased text, and the second will allow for cross-browser gradients. The former is rather simple:

    .antialiased (@color) {
        color: @color;
        text-shadow: @color 0 0 1px;
    }

    The trick is to create a shadow underneath the text with the same color and a one-pixel spread, making the browser display a nice shade around the text.

    Now for the gradient; this is more complicated than the anti-aliased text because every browser implements gradients differently. Once we’ve compensated for the various vendor prefixes, here is the code:

    .gradient4f (@p1, @c1, @p2, @c2, @p3, @c3, @p4, @c4) {
        background: @c1;
        background: -moz-linear-gradient(top,  @c1 @p1,  @c2 @p2,  @c3 @p3,  @c4 @p4);
        background: -webkit-gradient(linear, left top, left bottom, color-stop(@p1, @c1), color-stop(@p2, @c2), color-stop(@p3, @c3), color-stop(@p4, @c4));
        background: -webkit-linear-gradient(top, @c1 @p1, @c2 @p2, @c3 @p3, @c4 @p4);
        background: -o-linear-gradient(top, @c1 @p1, @c2 @p2, @c3 @p3, @c4 @p4);
        background: -ms-linear-gradient(top, @c1 @p1, @c2 @p2, @c3 @p3, @c4 @p4);
        background: linear-gradient(to bottom, @c1 @p1, @c2 @p2, @c3 @p3, @c4 @p4);
    }

    Every browser has a prefix: -moz- for Firefox, -webkit- for Chrome, etc. The last line uses the W3C recommended version for gradients. If a browser supports it, it will override the previous properties because it’s the last background property declaration in the rule. The linear-gradient function accepts eight parameters: four pairs of percent-color values. It creates the gradient with four color steps.


    Global Styles

    Let’s next style some global elements, such as for buttons and links. We want all elements to use the Helvetica or Arial fonts with the text color defined earlier:

    * {
        font-family: sans-serif;
        color: @text-color;
    }

    Body

    The body is pretty easy; we need a white background with an image-based pattern. There are no margins and padding:

    body {
        background: white url(gfx/bg.png);
        margin: 0;
        padding: 0;
    }

    Inputs

    We’ll also provide a default style for all <input/> elements in the page:

    input {
        width: 236px;
        height: 38px;
        border: 1px solid @border-color;
        padding: 0 10px;
        outline: none;
        font-size: 17px;&:focus {
            background: #FFFDF2;
        }
    }

    We set the default size and padding, and we use the @border-color variable to remove the annoying blue outline when the element is focused. You should notice another bit of LESS sugar: we can add CSS pseudo-classes (and normal classes too) using the & character (parent reference), as shown here:

    &:focus {
        background: #FFFDF2;
    }

    This causes the input to have a light yellow background, when focused.

    Submits

    Submit buttons will use both the previously defined mixin and the border-radius to create nice effect:

    input[type="submit"] {
        height: 36px;
        border: 1px solid #7BC574;
        border-radius: 2px;
        color: white;
        font-size: 12px;
        font-weight: bold;
        padding: 0 20px;
        cursor: pointer;
        .gradient4f(0%, #8CD585, 23%, #82CD7A, 86%, #55AD4C, 100%, #4FA945);
    }

    Links

    The links should have a different color than normal text. We’ll also underline them on hover:

    a {
        text-decoration: none;
        .antialiased(#58B84E);&:hover {
            text-decoration: underline;
        }
    }

    Basic Template

    We will begin with the portion of the layout that remains the same in every page. Here is the HTML code, which I will explain below:

    <!DOCTYPE HTML><html><head><link rel="stylesheet/less" href="style.less"><script src="less.js"></script></head><body><header><div class="wrapper"><img src="gfx/logo.png"><span>Twitter Clone</span></p></div></header><div id="content"><div class="wrapper"></div></div><footer><div class="wrapper">
    			Ribbit - A Twitter Clone Tutorial<img src="gfx/logo-nettuts.png"></div></footer></body></html>

    We start with a normal doctype definition and document head. You can use the less.js library and include the style.less in the development stage (as I did in this code). Later, you can compile the LESS file into CSS, if you don’t wish to use less.js. As you’ve probably noticed by now, the layout is divided into three parts: header, #content, and footer. You should save this HTML to see if you are styling everything correctly.

    Header

    Let’s tackle the header. It contains Ribbit’s logo and the two words: ‘Twitter Clone’. It’s wrapped in a wrapper, the width of which is controlled by the @content-width variable. There are several wrappers in the layout, and all are @content-width wide with auto margin:

    .wrapper {
        width: @content-width;
        margin: auto;
    }

    The header itself is 85px tall and page wide:

    header {
    	background: url(gfx/bg-header.png);
    	height: 85px;
    	width: 100%;
    }

    After the width, add div.wrapper‘s style with vertical padding:

    div.wrapper {
        padding: 11px 0;
    }

    So the header should look like:

    header {
        background: url(gfx/bg-header.png);
        height: 85px;
        width: 100%;
        div.wrapper {
            padding: 11px 0;
        }

    Images in the wrapper need to be 10px lower, in order to be nicely centered:

    img {
        position: relative;
        top: 10px;
        margin: 0 15px 0 0;
    }

    Also, the font in <span/> elements must be larger than the default size:

    span {
        font-size: 18px;
        margin: 0 42px 0 0;
    }

    Here’s how our design should look at this point.

    Header in basic template.

    Content

    There’s not much we can do with #content at this time. We’ll add some margin to the bottom and a minimum height; the layout will look funky if it’s not tall enough:

    #content {
    	margin-bottom: 15px;
    	min-height: 560px;
    }

    Inside, the wrapper needs to have some vertical margin with an automatic horizontal margin:

    div.wrapper {
        margin: 38px auto;
    }

    Footer

    Like the header, the footer is the same for all pages. We’ll use a background image and a smaller font size. We’ll also need to clear: both, because we’ll use floats in the content. Without clearing, the footer will not adjust in accordance with the content:

    footer {
    	background: url(gfx/bg-footer.png);
    	height: 251px;
    	font-size: 14px;
    	clear: both;
    }

    Let’s now add some padding to the wrapper, and images within it should float to the right:

    div.wrapper {
        padding: 15px;
        img {
            float: right;
        }
    }

    Here’s our footer:

    Completed footer.

    The Home Page

    This page displays for users not logged in to Ribbit. Therefore, it will need to present the login form in the header and a register form, with a big frog image in the content. Let’s start with a basic template.

    Login Boxes

    Add this login form to the div.wrapper of the header, after the <span/> element:

    <form><input type="text"><input type="password"></form>

    These inputs are already styled, but we do need to add the margins and make the form display as inline. Append this after span in div.wrapper of header:

    form {
        display: inline;
        input {
            margin: 0 0 0 14px;
        }
    }

    Register Form

    Here is the HTML for the registration form:

    <img src="gfx/frog.jpg"><div class="panel right"><h1>New to Ribbit?</h1><form><input name="email" type="text"><input name="password" type="text"><input name="password2" type="password"><input type="submit" value="Create Account"></form></div>

    Add this HTML within div.wrapper of #content. We want the image to have rounded corners and to be floated to the left (add this after margin in div.wrapper of #content):

    img {
        border-radius: 6px;
        float: left;
    }

    Now, we can style the registration form. It will also be a panel that we’ll use later; that’s why we will style the .panel:

    div.panel {
        border: 1px solid @border-color;
        background: white;
        margin: 0;
        margin-bottom: 29px;
        border-radius: 6px;
        font-size: 14px;
    }

    For now, though, we will only style the right panel. It’s narrower and sticks to the right side of the panel. Naturally, insert the following into div.panel:

    &.right {
        width: 303px;
        height: 313px;
        float: right;
    }

    Also, we need to take care of the header and content of the panel. We use <h1/> elements for the header and <p/> elements for content. Notice that you can use the * wildcard inside of another element:

    * {
        margin: 6px 0;
    }
    form {
        padding: 0 23px;
    }
    h1 {
        border-bottom: 1px solid @border-color;
        margin: 5px 0;
        font-weight: normal;
        font-size: 18px;
        padding: 13px 23px;
        height: 23px;
    }
    p {
        padding: 0 24px;
        margin: 18px 0;
    }

    Here is how div.panel‘s style should look:

    div.panel {
        border: 1px solid @border-color;
        background: white;
        margin: 0;
        margin-bottom: 29px;
        border-radius: 6px;
        font-size: 14px;&.right {
            width: 303px;
            height: 313px;
            float: right;
        }
        * {
    		margin: 6px 0;
    	}
    	h1 {
    		border-bottom: 1px solid @border-color;
    		margin: 5px 0;
    		font-weight: normal;
    		font-size: 18px;
    		padding: 13px 23px;
    		height: 23px;
    	}
    	p {
    		padding: 0 24px;
    		margin: 18px 0;
    	}
    }

    And here is a screenshot of how this page should look, thus far (click to see full size):

    Home page preview


    Buddies Page

    The Buddies page should be displayed when a user logs in. It will display a list of the last “Ribbits,” along with some statistics of your account. Once again, start with the basic template. This page, along with other pages, will display a logout button in place of the login form in the header:

    <form><input type="submit" id="btnLogOut" value="Log Out"></form>

    The buttons have already been styled, so we only need to pin it to the right side of container and add some margins:

    #btnLogOut {
    	float: right;
    	margin: 14px 0 0 0;
    }

    Because this rule’s selector is an element’s ID, you can place it either outside of any element or within the header’s div.wrapper. It’s your choice, but remember that, if you choose to place it inside of another element, the compiled CSS will have a longer selector (header div.wrapper #btnLogOut).

    “Create a Ribbit” Box

    First, add this panel’s code to div.wrapper of #content:

    <div id="createRibbit" class="panel right"><h1>Create a Ribbit</h1><p><form><textarea name="text" class="ribbitText"></textarea><input type="submit" value="Ribbit!"></form></p></div>

    The .right class was styled earlier, but we need to add some styling for the <textarea/> element. We’ll give it a proper size and border:

    textarea.ribbitText {
        width: 249px;
        height: 160px;
        border: 1px solid @border-color;
    }

    Add this in the style definition of the right panel.

    User Information

    Now, let’s focus on the panel, which contains the user’s account information. We’ll temporarily populate it with some random content to see the styling:

    <div id="ribbits" class="panel left"><h1>Your Ribbit Profile</h1><div class="ribbitWrapper"><img class="avatar" src="gfx/user1.png"><span class="name">Frogger</span> @username<p>
                567 Ribbits<span class="spacing">45 Followers</span><span class="spacing">32 Following</span><br>
                Cras justo odio, dapibus ac facilisis in, egestas Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. <a href="#">http://net.tutsplus.com/tutorials/php/ ...</a></p></div></div>

    It may look complex, but the structure is fairly simple, when you strip out the content:

    <div id="ribbits" class="panel left"><h1>Your Ribbit Profile</h1><div class="ribbitWrapper"><img class="avatar" src="gfx/user1.png"><span class="name"> </span><p><span class="spacing"> </span><span class="spacing"> </span><br></p></div></div>

    Regardless, we have another panel; so we need to style it first:

    &.left {
        width: @content-width - 327;
        float: left;
    }

    You probably know where to place this code (notice how easily you can perform arithmetical operations in LESS). This panel contains div.ribbitWrapper. So, add the following code:

    div.ribbitWrapper {
        padding: 15px 0;
    }

    There are two <span/> elements inside this element, each with a different color and font size. They have classes of .name and .time:

    span {&.name {
            font-size: 18px;
            color: #58B84E;
        }&.time {
            font-size: 12px;
            color: #CCC;
        }
    }

    We should also position the avatar image near the left border. Add the following code:

    img.avatar {
        margin: 0 19px 0 20px;
        float: left;
    }

    Also, Ribbit’s text needs to be anti-aliased, justified and moved to the right. This code will place the text next to the avatar, as opposed to beneath it:

    p {
        margin: 5px 50px 0 90px;
        padding: 0;
        text-align: justify;
        line-height: 1.5;
        .antialiased(@text-color);
    }

    In this paragraph, there are <span/> elements with vertical lines, visually separating them. This effect is achieved by using border, padding, and margin:

    span.spacing {
        padding-left: 9px;
        margin-left: 9px;
        height: 10px;
        border-left: 1px solid @border-color;
    }

    Buddies’ Ribbits

    This panel lists the latest ribbits from the people to whom the user follows. Insert the following after the user’s information panel:

    <div class="panel left"><h1>Your Ribbit Buddies</h1><div class="ribbitWrapper"><img class="avatar" src="gfx/user2.png"><span class="name">Kermit</span> @username <span class="time">15m</span><p>
                Cras justo odio, dapibus ac facilisis in, egestas Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. <a href="#">http://net.tutsplus.com/tutorials/php/ ...</a></p></div><div class="ribbitWrapper"><img class="avatar" src="gfx/user1.png"><span class="name">Frogger</span> @username <span class="time">15m</span><p>
                Cras justo odio, dapibus ac facilisis in, egestas Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. <a href="#">http://net.tutsplus.com/tutorials/php/ ...</a></p></div><div class="ribbitWrapper"><img class="avatar" src="gfx/user2.png"><span class="name">Kermit</span> @username <span class="time">15m</span><p>
                Cras justo odio, dapibus ac facilisis in, egestas Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. <a href="#">http://net.tutsplus.com/tutorials/php/ ...</a></p></div><div class="ribbitWrapper"><img class="avatar" src="gfx/user3.png"><span class="name">Hypnotoad</span> @username <span class="time">15m</span><p>
                Cras justo odio, dapibus ac facilisis in, egestas Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. <a href="#">http://net.tutsplus.com/tutorials/php/ ...</a></p></div><div class="ribbitWrapper"><img class="avatar" src="gfx/user2.png"><span class="name">Kermit</span> @username <span class="time">15m</span><p>
                Cras justo odio, dapibus ac facilisis in, egestas Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. <a href="#">http://net.tutsplus.com/tutorials/php/ ...</a></p></div><div class="ribbitWrapper"><img class="avatar" src="gfx/user3.png"><span class="name">Hypnotoad</span> @username <span class="time">15m</span><p>
                Cras justo odio, dapibus ac facilisis in, egestas Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. <a href="#">http://net.tutsplus.com/tutorials/php/ ...</a></p></div></div>

    There are few example ribbits to see how it looks. We’ll add some borders to visually separate them. Add this code in div.ribbitWrapper:

    border-bottom: 1px solid @border-color;&:last-child {
        border: none;
    }

    This styling adds the bottom border, while removing the border on the last div.ribbitWrapper; a border already exists on the panel.

    Here is how this page should look now:

    Buddies page preview


    Public Ribbits Page

    The “Public Ribbits” page will list the latest ribbits of profiles not marked as private, so that users can view the ribbits of those who they don’t have in their buddy list. Surprisingly, there is nothing else to style, but we do need to add a touch of HTML. The only difference between this and the previous page is that this one doesn’t have the user’s information panel, but it will have other content in the final site. So feel free to copy the code of the buddies page, but remove this panel:

    <div id="ribbits" class="panel left"><h1>Your Ribbit Profile</h1><div class="ribbitWrapper"><img class="avatar" src="gfx/user1.png"><span class="name">Frogger</span> @username<p>
                567 Ribbits<span class="spacing">45 Followers</span><span class="spacing">32 Following</span><br>
                Cras justo odio, dapibus ac facilisis in, egestas Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. <a href="#">http://net.tutsplus.com/tutorials/php/ ...</a></p></div></div>

    Also change the header of the panel to “Public Ribbits.” Here is the preview of this page:

    Public ribbits page preview


    Public Profiles Page

    On this page, users can see a list of profiles that are not marked as private. There is also a search box to find other profiles. We’ll start with the basic template.

    Profile Search

    The search box will use the .right panel with an <input/> element inside:

    <div class="panel right"><h1>Search for profiles</h1><p><form><input name="query" type="text"><input type="submit" value="Ribbit!"></form></p></div>

    Profiles List

    Here are a handful of example profiles for the profile list, so that you can see how it looks in the browser. In a future lesson, we’ll of course replace this, accordingly.

    <div id="ribbits" class="panel left"><h1>Public Profiles</h1><div class="ribbitWrapper"><img class="avatar" src="gfx/user2.png"><span class="name">Kermit</span> @username <span class="time">625 followers <a href="#">follow</a></span><p>
                Cras justo odio, dapibus ac facilisis in, egestas Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. <a href="#">http://net.tutsplus.com/tutorials/php/ ...</a></p></div><div class="ribbitWrapper"><img class="avatar" src="gfx/user1.png"><span class="name">Frogger</span> @username <span class="time">329 followers <a href="#">follow</a></span><p>
                Cras justo odio, dapibus ac facilisis in, egestas Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. <a href="#">http://net.tutsplus.com/tutorials/php/ ...</a></p></div><div class="ribbitWrapper"><img class="avatar" src="gfx/user3.png"><span class="name">Hypnotoad</span> @username <span class="time">129 followers <a href="#">follow</a></span><p>
                Cras justo odio, dapibus ac facilisis in, egestas Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. <a href="#">http://net.tutsplus.com/tutorials/php/ ...</a></p></div></div>

    This page should look like:

    Public profiles page preview


    Compiling The CSS

    Referencing a nested element can result in lengthy selectors.

    As I noted earlier, for production, you can compile your LESS to CSS (and I recommend you do so for performance reasons). There are a few available online compilers:

    Along with some stand-alone compilers:

    • Crunch! (which is a full-blown LESS editor)
    • WinLess (features auto compilation when the less file changes)
    • SimpLESS (includes CSS minification)

    If any of these compilers do not work for you, Google for more; there are plenty! You can also use lessc from LESS’s site, but it’s much easier to compile your LESS files with other compilers. Of course, there is nothing wrong with using the less.js library to dynamically compile the layout; new browsers cache the resulting CSS.


    Conclusion

    As you can see, LESS is a powerful tool that makes it much easier and faster than plain CSS to style beautiful layouts.

    But this is just the beginning. Be prepared to implement Ribbit’s back-end in a plethora of languages and platforms in the next set of tutorials!

    Why Rails?

    $
    0
    0

    Your choice, when learning a new framework, is an incredibly important one. It takes countless hours and effort to become proficient and learn all the best practices – even for experienced developers.

    That's why it's necessary to understand the peculiarities of a framework as early as possible, in order to determine if it's the right solution for the problem that you’re trying to solve. In this article, I’ll cover many of the key areas of the Ruby on Rails framework, and why I feel that it’s an excellent choice for web developers.


    Some History

    Ruby on Rails was extracted from the project management application, Basecamp.

    Ruby on Rails was open-sourced in 2004, by David Heinemeier Hannson, after being extracted from the project management application, Basecamp.

    It's based on the Ruby programming language, and the current stable release is 3.2 – with 4.0 just around the corner!

    RoR is a full web application stack; starting with version 3.1, it also includes facilities and libraries to manage frontend code, supporting Sass and CoffeeScript out of the box, with no need for external tool to manage the compile process. Opinionated workflow is the name of the game with Rails.

    For development, it embeds its own web server, so that you don't need to install extra software apart from a working Ruby installation.


    Why Learn It?

    There are countless reasons for learning Rails, ranging from technical to business and productivity. We'll tackle each one by one.

    Technology

    Ruby has been designed to be a "joy to use".

    As its name implies, Rails is based on the Ruby language. Invented in 1993 and released for the first time in 1995 by Yukihiro Matsumoto (widely known simply as "Matz"), Ruby is an object-oriented interpreted language that features a syntax heavily inspired by Perl and Lisp. Since its inception, Ruby has been designed to be a "joy to use" – meaning a strong focus on readability and elegance.

    Being a higher level language, Ruby is extremely powerful and versatile, while maintaining a good balance of clarity and performance (bearing in mind that it's still an interpreted, dynamic language).

    The original Ruby interpreter (Matz's Ruby Interpreter, shortened as MRI) is written in C, but it's not the only one available nowadays (a couple of notable alternatives are JRuby, running on top of the JVM, and Rubinius).

    Ruby features several libraries shipped with its core, including a very powerful unit testing one, called Minitest (prior to Ruby 1.9, Ruby used TestUnit).

    Rails is a popular way to get involved with Ruby, so it's not rare nowadays to find people (including myself) whose first introduction to Ruby was through Rails.

    Learn the fundamentals of Ruby with Tuts+ Premium.

    Structure

    Rails is strongly opinionated, when it comes to architectural decisions

    Rails is a database-agnostic MVC framework that chooses convention over configuration, which means that it's strongly opinionated, when it comes to architectural decisions, naming conventions, paths and patterns.

    In more detail:

    • MVC means that it follows the Model-View-Controller paradigm, so that you can clearly separate concerns when developing an application. This allows your core business logic to be in a single place, avoiding duplication and assisting with maintenance.

    • It follows a RESTful, resource-oriented approach, meaning that it encourages you to think about your business logic from the data standpoint, exposing resources to endpoints that perform CRUD actions. For example, logging into a site can be seen as 'creating a session'; logging out as 'destroying a session'. This approach takes some getting used to, but once you’ve adopted that mindset, it helps in keeping your interfaces consistent and predictable by other developers. Rails applications tend to revolve around models, which manages data persistence.

    • It uses Bundler as a dependency management tool, leveraging the power of the Rubygems community. This ensures a consistent approach for adding third party functionality to an application, with an explicit format that details which libraries we need, and which versions, including resolving nested dependencies.

    • It can support a wide range of databases, with SQLite as a default (good for development) and MysQL and PostgreSQL as first choices for production. MongoDB can also be integrated with minimal effort.

    • Convention means that naming, paths and patterns are usually predictable and shared among fellow Rails developers. This ensures an easier learning curve, focused on the business logic for the app, easier maintenance and less documentation.

    • It's easy to test, with tools that integrate with the framework for unit testing and integration (with JavaScript support) as well. Additionally, the Ruby community, itself, strongly advocates test-driven development, so a good Rails developer is likely quite experienced in testing.

    • A Rails application can be easily deployed to cloud infrastructures, like Heroku, or straight to private servers (it runs great on Ubuntu Linux, for example).

    Core Features

    Here's a basic rundown of what Rails can do out of the box, along with some code examples. Please note that, even if you’ve never worked with Rails before or even don't know Ruby, this should not prevent you from understanding them, as they are quite readable.

    • Support for data model definition through migrations, i.e. repeatable and reversible database agnostic instructions, which manipulate the database structure. Consider the following migration:

      class CreateEvents < ActiveRecord::Migration
        def change
          create_table :events do |t|
            t.string :title
            t.date :start_date
            t.date :end_date
            t.boolean :live, :default => false
            t.timestamps
          end
        end
      end

      This migration creates an events table, with some basic data, like a title, and uses specific data types that are mapped to specific column types in the underlying database. For example, by default, string uses a VARCHAR(255) column, if using MySQL. This migration can be written manually from scratch, or generated from the command line and then edited before being run.

    • Database agnostic model interface for CRUD actions. Here’s a few examples, given a News model:

      news = News.new(title: 'Sample news')
      # => returns a news instance, not saved to the database
      news.save
      # => runs an insert query and updates the instance with the returned id from the database
      news.title = 'Updated sample news'
      # => sets the title to the new value, without saving to the database
      news.save
      # => runs an update query for that item
      news.destroy
      # => runs a delete query for that item

      In addition, Rails provides a simple interface to perform selection queries, including joins between models.

      News.where(published: true).order('created_at DESC').limit(5)
      # => produces 'SELECT * from news where published = 1 order by created_at DESC limit 5'
    • Support for validations; an Event model may always require the presence of a unique title. In that case, it's possible to clearly express these requirements in the Event class:

      class Event < ActiveRecord::Base
        validates :title, :presence => true, :uniqueness => true
      end

      This functionality ensures that no invalid record is saved to the database, and also provides all the bindings needed to display validation errors to the user (for example in a form).

    • Session and cookies with simple helpers to set values, get and delete them, with transparent signature.

    • Protection against form forgery, so that any form you generate through Rails is automatically signed with a token that guarantees its genuinely.

    • Aggressive XSS protection policy enabled by default, so that any form element you use is protected by default, unless you explicitly whitelist it (careful when doing that!).

    • Simple management for GET and POST data, accessible through a simple hash available in every controller action.

    • Simple bindings to connect controllers, models and views, with clear and conventional rules that simplify file management and code. For example, consider the following controller that is responsible for rendering a news list page at http://example.com/news:

      class NewsController < ApplicationController
          def index
          end
      end

      Even without writing any code to define what index does, Rails provides a default behaviour, which is to render the app/views/news/index.html.erb view. This reduces the need for boilerplate code, as, most of the time, it's just necessary to override behavior, when unconventional.

    • Integration with external services; Rails offers a rich ecosystem of applications that you can use to monitor, maintain and improve your application (some of them work with other frameworks as well). New Relic helps in monitoring performance, Airbrake collects exceptions to notify the development team, Code Climate analyzes your codebase for quality, complexity and duplication, Tddium and TravisCI can run your test suite remotely against different Ruby versions.

    • As noted previously, Rails also offers an integrated environment to work with Coffeescript and Sass, with transparent compilation in development and preprocessing and cache busting for deployment, so that your production app will serve single, minified files with a signature in the filename. This way, you can be absolutely sure that any browser will always load and cache the latest version of the file.


    Business Value

    Have you ever wondered why Rails is the first choice of many web startups? There are two primary reasons:

    • It lets you work on features with minimal boilerplate, removing a lot of non-business related work from the development process. This translates into increased velocity in developing and deploying new features, which is key to understanding if the product is solid.

    • Rails’ structure makes it easy to accommodate change. This is certainly true for many MVC frameworks, though Rails is particularly good at restructuring your application flow, reusing components in a simple way.

    It's important to remember that, frequently, development time is more costly than an extra server.

    There's always an ongoing conversation about Rails performance, and how it can become a bottleneck when you get thousands of hits a minute. The problem is that getting to that level of traffic requires a huge effort. The truth is: 9 times out of 10, scalability is a problem that many companies never need to face. To them, the ability to make changes, easy maintainability and predictability are far more valuable.

    In addition, it's important to remember that, frequently, development time is more costly than an extra server. A framework like Rails is often preferred, because, even if it may need more powerful hardware, it’s still cost effective in other areas.

    This doesn't mean that you shouldn't care about the performance of your code or worry about topics, such as caching and query optimization. Instead, it means taking into account the full spectrum of hardware and software changes you can make; sometimes, it's sensible to pospone a performance focused chunk of work and temporarily have more powerful hardware to continue working on important features.


    Extending the Framework

    Rails can easily be extended with a wide variety of external libraries, distributed through Rubygems. Most of the times, any feature that you need to build is already offered through a gem. Now, this doesn't mean that adding gems is the perfect solution; every third party dependency that you add to an application becomes a risk factor.

    Sometimes, it's preferable to roll your own version with custom code.

    That said, you shouldn't reinvent the wheel. Many Rails applications use the same gems to provide specific features; this can be seen as an advantage. Remember: wide usage translates to wide testing, so it's considered a safe practice to use certain well known gems to accomplish key tasks. Here are a few examples:

    This list could easily go on, but the point is that Rails leverages the modularity of a Rubygems-based approach and can greatly speed up development, by placing focus on building features that matter for the product you're working on, instead of boilerplate.


    Why I Enjoy Working With Rails

    I can focus on what matters for clients without compromising on good code quality.

    Roughly two years ago, I was working in a marketing/product management role (doing web development as a hobby); that meant focusing on product features, their business value and the cost associated with their development. When I decided to switch careers, Rails 3.0 had just been released. I spent an afternoon watching videos and reading tutorials. I quickly decided that Rails was what I wanted to focus my efforts on.

    The reason – and this somewhat overlaps with what we’ve already discussed – is that I could see a practical approach in the framemork, a clear goal to be productive and focus on the product and its development. I could get things done in a short amount of time. After a few months of intensive self-training through various web tutorials and some sample applications, I applied for my current job as a Rails developer at New Bamboo.

    I enjoy working with Rails every day, because I can focus on what matters for clients without compromising on good code quality. To me, it's the perfect starting point for most web-based applications.

    It doesn't solve all the problems you’ll encounter, when building large web applications. There are times when you clearly see that Rails isn't fit for a specific kind of service, but that's the time to split the architecture into smaller applications.


    Conclusion

    Rails is a powerful framework that can help you become more productive and confident, when working on complex projects. This is possible, thanks to its strong conventions and solid structure. Large companies, such as 37 Signals, Pivotal Labs, Groupon (or even Twitter in the old days) have chosen Rails as the base architecture for their core applications. There’s a reason why!

    Ready to start Riding Ruby on Rails?

    The Best Education of 2012: Month By Month

    $
    0
    0

    Well, 2012 has come to a close. A plethora of excellent tutorials and articles were published throughout the year, both here on Nettuts+ and elsewhere around the web. To document the year, I compiled a list of sixty of the best tutorials, month by month. You’ll likely find a few that you missed along the way!


    January

    • Learn jQuery in 30 Days

      Sometimes, it’s easy to become overwhelmed by how much there is to learn in this industry. If jQuery happens to be on your personal “need to learn soon” list, then check out Jeffrey Way’s course "Learn jQuery in 30 Days". If you’ll give him fifteen minutes a day for the next month, he’ll help you become a jQuery pro – and it’s free!

    • .htaccess for the Rest of Us

      .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.

    • HTML5 Please

      Look up HTML5, CSS3, etc features, know if they are ready for use, and if so find out how you should use them – with polyfills, fallbacks or as they are.

    • Understanding MVC and MPV for JavaScript and Backbone Developers

      Before exploring any JavaScript frameworks that assist in structuring applications, it can be useful to gain a basic understanding of architectural design patterns. Design patterns are proven solutions to common development problems and can suggest structural paradigms to help guide us in adding some organization to our application.

    • High Performance HTML5

      Steve Souders discusses the impact of website speed on users providing advice on creating high performance HTML5 applications.


    February

    • Wrangle Async Tasks with jQuery Promises

      Promises are an exciting jQuery feature that make it a breeze to manage async events. They allow you to write clearer, shorter callbacks and keep high-level application logic separate from low-level behaviors. Once you understand Promises, you’ll want to use them for everything from AJAX calls to UI flow. That’s a promise!

    • How to Customize Your Command Prompt

      I’ve been getting this question a lot: “how did you get your terminal to look the way it does?” If you’ve noticed my terminal and are curious about how I set it up, this is the tutorial for you! Of course, what you learn here will be enough to get you started on creating your own custom command prompt, as well!

    • Using JavaScript Prototypes with MVC

      In this article, we will review the process of using JavaScript, from an MVC-based perspective, to manipulate the DOM. More specifically, we’ll engineer our JavaScript objects, their properties and methods, and their instantiations parallel to the intended behavior of our Views (what the user sees).

    • Musings on Proprocessing

      I’ve been using SASS for pretty much everything I do recently. Here’s some musings on the journey. From hold-ups, to trip-ups, to turn-offs. From apps and teams to workflows and syntax.

    • It’s Curtains for Marital Strife Thanks to getUserMedia

      getUserMedia is an API that gives a web page access to a user’s camera and microphone via JavaScript. It’s supported in Opera 12 and Opera Mobile 12 for Android, and WebKit in Chrome Canary builds (instructions). Like many other APIs, it’s not part of the “real” HTML5 spec. It started life as the HTML5 element, then got moved into the W3C as part of the webRTC specifications. But let’s not taxonomise when we could be having fun.


    March

    • Building a Contacts Manager Using Backbone.js

      In this tutorial, we’re going to look at building a fully functional contacts manager using Backbone.js, Underscore.js, and jQuery. We’ll take a look at the basic components that make Backbone tick as well as some of the convenience methods exposed by Underscore. (See the whole session.)

    • Create Instagram Filters with PHP

      In this tutorial, I’ll demonstrate how to create vintage (just like Instagram does) photos with PHP and ImageMagick. Wait? What? Yes, you can do this very thing with PHP and ImageMagick, and that’s just scratching the surface!

    • It’s Time to Start using JavaScript Strict Mode

      ECMAScript 5 introduced strict mode to JavaScript. The intent is to allow developers to opt-in to a “better” version of JavaScript, where some of the most common and egregious errors are handled differently. For a while, I was skeptical, especially with only one browser (Firefox) initially supporting strict mode. Fast forward to today, every major browser supports strict mode in their latest version, including Internet Explorer 10 and Opera 12. It’s time to start using strict mode.

    • Thining Async

      Here’s the rub: when you load JavaScript from a third party you should do it asynchronously. You might want to load your own scripts asynchronously too, but for this article let’s focus on third parties.

    • Vendor Prefixes are not Developer-Friendly

      The premise of prefixes makes unrealistic demands on how developers maintain sites. There’s a lot of conversation about making prefixes work (by changing policy), but I believe they already are at odds with the developer workflow.


    April

    • Closures: Front to Back

      Closures are often viewed as an arcane art in the land of JavaScript. Once mastered, they allow you to write some truly amazing JavaScript. This article will get you up to speed on the magic of JavaScript closures.

    • Meeting Grunt: The Build Tool for JavaScript

      If you’re working on a large project, you’ll no doubt have a build script or a bunch of task scripts to help with some of the repetitive parts of the process. You might use Ant or Rake, depending on the language the project is written in. But what do you use if the project is primarily JavaScript? That’s the problem Ben Alman set out to solve when he created Grunt.

    • CSS Sprites Revisited

      I’m pretty confident that I won’t surprise anyone here by saying that CSS sprites have been around for quite a while now, rearing their somewhat controversial heads in the Web development sphere as early as 2003.

    • Creating a Mobile-First Responsive Web Design

      As the web landscape becomes increasingly complex, it’s becoming extremely important to deliver solid web experiences to a growing number of contexts. Thankfully, responsive web design gives web creators some tools for making layouts that respond to any screen size. We’ll use fluid grids, flexible images and media queries to get the layout looking great regardless of the size of the device’s screen dimensions.

    • A Baseline for Front-End Developers

      I wrote a README the other day for a project that I’m hoping other developers will look at and learn from, and as I was writing it, I realized that it was the sort of thing that might have intimidated the hell out of me a couple of years ago, what with its casual mentions of Node, npm, Homebrew, git, tests, and development and production builds.


    May

    • SSH: What and How

      Many web developers use SSH (“Secure Shell”) on a daily basis to manage their servers, back up files, work remotely, and a myriad of other tasks. Today, I’ll explain what SSH is, do a brief history review, and, lastly, teach you how to set it up on your remote server or even your local network. Let’s get started!

    • 10 Things I learned With Interning at YUI

      For eight months, I had the opportunity to intern with the YUI Team at Yahoo, while I was completing my engineering degree. Today, I’d like to share the top ten things that I learned from my experience with YUI.

    • Gem Creation with Bundler

      Building a gem used to be a complex task that would require either a precise knowledge of the gem format, itself, or some dedicated tools to generate a suitable boilerplate. These days, we can use the excellent Bundler to remove this complexity and keep the amount of generated code to a minimum.

    • PHP Database Access: Are You Doing it Correctly?

      We’ve covered PHP’s PDO API a couple of times here on Nettuts+, but, generally, those articles focused more on the theory, and less on the application. This article will fix that! To put it plainly, if you’re still using PHP’s old mysql API to connect to your databases, read on!

    • JavaScript Design Patterns

      This time around, you learn about the Adapter, Decorator, and Factory patterns.


    June

    • Key Principles of Maintainable JavaScript

      JavaScript is a curious language. It’s easy to write, but difficult to master. By the end of this article, hopefully, you’ll transform your spaghetti code into a five-course meal, full of readable, maintainable yumminess!

    • Building Web Applications from Scratch with Laravel

      In this Nettuts+ mini-series, we’ll build a web application from scratch, while diving into a great new PHP framework that’s rapidly picking up steam, called Laravel — a simple and elegant PHP 5.3 framework.

    • Understanding Hash Functions and Keeping Passwords Safe

      From time to time, servers and databases are stolen or compromised. With this in mind, it is important to ensure that some crucial user data, such as passwords, can not be recovered. Today, we are going to learn the basics behind hashing and what it takes to protect passwords in your web applications.

    • Classes? Where we’re Going, We Don’t Need Classes!

      Classes, classes, classes everywhere. What if we don’t need CSS classes at all? What if we stopped worrying about how many classes we’re using and what we should be calling them and just finished with them once and for all? It would be no revelation to you to say that HTML elements can be styled without recourse to the class attribute, but have you considered the multitude of benefits that come from forgoing classes altogether?

    • Writing an AngularJS App with an Express + Node.js Backend

      AngularJS is like the missing Batarang on your utility belt of web development awesomeness. It gives you two-way data binding that’s both easy to use and fast, a powerful directive system that lets you use create reusable custom components, plus a lot more. Express is an excellent webserver for Node.js that provides routing, middleware, and sessions. Incidentally, the two work quite well together!


    July

    • The Principles of Agile Development

      Agile or Agile Development – we hear these words more often these days. But do we really know what it is all about? How can it help us become more effective, while having lots of fun developing software? How can we use it to communicate with business people and make this communication easy and constructive for both sides?

    • From FTP to Git: A Deployment Story

      Once upon a time, there was a file. It was on your computer, and you wanted to get it on a server. Ever wondered why there are so many ways to do that? We’ll explain some of the basics of deployment in this article so you understand when to use what. Let’s get started!

    • Test-Driven Development in PHP: First Steps

      Let’s admit it: the PHP community has lagged a bit, when it comes to advocating test-driven development. We know we should, but, even to this day, a sizable portion of the community does not. In this new series of videos and tutorials, created by the Nettuts+ team, we’re hoping to change that. Trust me: it’s not as tough as you think.

    • Ping-Pong Game Tutorials with HTML5 Canvas and Sounds

      Making games in HTML5 Canvas is not that hard once you learn the logic of the game you are creating. In this tutorial, you will learn how to create a not-so-basic ping-pong game in Canvas. First of all, lets take a look on the main concept and some basic logic behind this game.

    • How I Learned Backbone.js, Three.js, and GLSL in One Week

      Last week was the 7dfps challenge, an open challenge where participants had to make a FPS in only one week. Such contests are very very interesting for those who want to experiment with things. Challenging yourself is IMO the best way to learn new things. You may also know the famous “Ludum Dare” contest. I learned to use Backbone.js and Three.js (a famous library on top of WebGL) in only one week, so you have no excuse to not be able to do the same


    August

    • Game On: Backbone and Ember

      So you’ve accepted the challenge to go thick on the client-side; well done. You’ve considered all the frameworks out there and are unsure which one to choose? You’re not alone. Read on.

    • Vagrant: What, Why and How

      This article will help walk you through using Vagrant to manage your virtual machine instances, and explain how you can take advantage of Puppet to provision various resources, like PHP and PostgreSQL.

    • Node.js for Beginners

      Event-driven programming can be overwhelming for beginners, which can make Node.js difficult to get started with. But don’t let that discourage you; In this article, I will teach you some of the basics of Node.js and explain why it has become so popular.

    • Magazine-lika Layout for the Web with CSS Regions and Exclusions

      The most frequently asked question I get since posting my responsive navigation patterns article is: How do I handle complex navigation for responsive designs?”

    • Writing a Command Line Node Tool

      Today we are going to combine a few different tools and create a simple Node package that will allow a user to search a directory for files. In this tutorial we will use Grunt to do a lot of the work for us, see how to to make a Node script executable on the command line, and finally see how we publish it to the Node Package Manager (npm) so anyone can install it.


    September

    • Organizing Enterprise-Level Applications

      Organization can make or break the maintainability of an application. With smaller applications, organization is more obviously apparent; however, as the application grows and as the number of application developers and front-end engineers producing code increases, the more confusing organization can become. In this post, we will go over some basic concepts for keeping applications organized so that finding relevant code is an efficient and systematic process.

    • Hands-On Unit Testing With PHPUnit

      In this screencast, we’ll build a relatively simple class, using TDD techniques. Along the way, we’ll discuss various PHPUnit methods, how to create mock objects, and more! I encourage you to work along; it’s the best way to learn!

    • Understanding Backbone.js and the Server

      Most Backbone tutorials will describe the process of sending RESTful requests to the server. But, how do we capture that data with our server-side framework? How do we know what the request urls are? How do we monitor these requests using Chrome Dev Tools? I’ll show you all of that and more in this screencast.

    • Rundown of Handling Flexible Media

      When you take the responsive web design route, part of the deal is fluid grids. That is, container elements set in percentage widths. Just one example: an

      that holds a blog post might be 320px wide on a small screen device and 690px wide on some large screen. Text can be resized and will flow nicely to fill a container. That’s not too hard. But media – images, video players, and audio players – demand a bit more attention (e.g. a video that sticks off the edge of the screen == bad). This post is to round up the methods of handling that.

    • HTML5 Web Storage – Cookies are so 1994

      In this two part series, we’re going to look at Web Storage, one of the best and most interesting features to come out of the HTML5 spec. We’ll look at the history of both Web Storage and cookies.


    October

    • Make JavaScript Testing Fun with Testem

      JavaScript testing is a sensitive subject. Some developers are huge advocates of it (including myself), while others don’t see the need or benefit. One huge barrier is the simple fact that it can sometimes take a considerable amount of setup to get up and running. The longer it takes, the more likely it is that the developer simply won’t bother. That’s why Testem is so fantastic; it makes testing as effortless as possible, and, more importantly, fun!

    • Getting Started with Web Workers

      One of the many design goals of the JavaScript language was to keep it single-threaded and, by extension, simple. Though I must admit that, given the idiosyncrasies of the language constructs, it is anything but simple! But what we mean by being “single-threaded” is that there is only one thread of control in JavaScript; yes, sadly, your JavaScript engine can do only one thing at a time. Now, doesn’t that sound too restrictive to make use of multi-core processors lying idle on your machine? HTML5 promises to change all of that.

    • Namespacing in PHP

      It’s been a bumpy ride, in regards to namespace support in PHP. Thankfully, it was added to the language in PHP 5.3, and the applicable structure of PHP code has improved greatly since then. But how exactly do we use them?

    • Step by Step: From jQuery to Backbone

      I’ve seen many struggle when they first meet Backbone.js. In this blog post I will gradually refactor a bit of code from how I used to write JavaScript before, into proper Backbone.js code using models, collections, views and events. Hopefully this process will give you a firm understanding of the core abstractions in Backbone.js.

    • Contraint Validation: Native Client Side Validation For Web Forms

      Validating forms has notoriously been a painful development experience. Implementing client side validation in a user friendly, developer friendly, and accessible way is hard. Before HTML5 there was no means of implementing validation natively; therefore, developers have resorted to a variety of JavaScript based solutions.


    November

    • 20 All Too Common Coding Pitfalls For Beginners

      Regardless of our current skill level, we all were beginners at one point in time. Making classic beginner mistakes comes with the territory. Today, we’ve asked a variety of Nettuts+ staff authors to chime in with their list of pitfalls and solutions – in a variety of languages. Learn from our mistakes; don’t do these things!

    • Why Haskell?

      Being a purely functional language, Haskell limits you from many of the conventional methods of programming in an object-oriented language. But does limiting programming options truly offer us any benefits over other languages? In this tutorial, we’ll take a look at Haskell, and attempt to clarify what it is, and why it just might be worth using in your future projects.

    • Testing JavaScript with PhantomJS

      I don’t think I need to convince you that testing your JavaScript code is a good idea. But, it can sometimes prove tedious to test JavaScript code that requires a DOM. This means you need to test your code in the browser and can’t use the terminal, right? Wrong, actually: enter PhantomJS.

    • JavaScript APIs You’ve Never Heard of (and Some You Have)

      This week I was scheduled to give a brand new talk at YUIConf entitled, JavaScript APIs you’ve never heard of (and some you have). Unfortunately, a scheduling conflict means that I won’t be able to attend. So instead of letting the work of putting together a brand-= new talk go to waste (or otherwise be delayed) I decided to put together a screencast of the talk.

    • Code Smells in CSS

      My day-to-day life is spent working in-house at BSkyB… I work on big websites, the last of which took me over a year to build the front-end for (and it’s still ongoing). For me, in my world, bad CSS is a very specific and troublesome thing; when you’re working on one site for months on end, you can’t afford poor code, be it CSS or otherwise, and any bad code needs righting.


    December

    • Apache: Aliasing and Redirection

      It’s common for a client to send a request for a file that either does not exist on the server, or exists in a different location. This can occur for a variety of reasons. You might move your files around the server (or to a completely different server), or you may want to present a logical file system structure to connecting clients.

    • Essential Command-Line Tools for Web Developers

      Tools can make our workflows feel seamless, allowing us to focus on what we are building, and not worry about the process. Most web developers, on all portions of the stack, work from the command-line. There are countless utilities, which can make you more productive. These aren’t full blown command-line applications, such as Git, but rather simple and composable tools, which can improve your workflow as a web developer.

    • Dependency Injection in PHP

      Dependency injection has been a frequent subject of discussion among many corporate developers in the past few years. Many feared that they might sacrifice too much time building their application architecture without doing any real work. In this article, I’ll explain why PHP developers should consider taking advantage of dependency injection, when building large, scalable projects.

    • How to Make Your Site Look Half-Decent in Half an Hour

      Programmers like me are often intimidated by design – but a little effort can give a huge return on investment. Here are one coder’s tips for making any site quickly look more professional. I am a programmer. I am not a designer. I have a degree in computer science, and I don’t mind Comic Sans. (It looks cheerful. Move on.)

    • Persistent Terminal Sessions

      Have you ever had a remote terminal session running, only to have your connection drop out half way through a large task? Then, you reconnect, not knowing anything about its progress (if any) and current status. Screen is the solution to this problem. Screen allows you to start terminal sessions that you can disconnect from and resume at any time.


    Conclusion

    Well, that’s my list of 60 great tips and tutorials from 2012. You probably have some favorites of your own; let’s hear them in the comments!

    Viewing all 502 articles
    Browse latest View live