Feeds

107664 items (1333 unread) in 22 feeds

CNN CNN
MSNBC MSNBC
PHP PHP
Deals Deals
Tech Tech
Web Development Web Development
CNN Money CNN Money
Frugal Blogs Frugal Blogs

Nettuts+ (86 unread)


  • Permalink for 'JavaScript Testing From Scratch: New on Premium'

    JavaScript Testing From Scratch: New on Premium

    Posted: February 5th, 2012, 1:30pm MST by Andrew Burgess

    This likely isn’t the first tutorial on testing that you’ve ever seen. But perhaps you’ve had your doubts about testing, and never took the time to read them. After all, it can seem like extra work for no reason.

    This tutorial (with screencasts) intends to change your views. We’re going to start at the very beginning: what is testing and why should you do it? Then, we’ll talk briefly about writing testable code, before actually, you know, doing some testing! Let’s get to it.

    Become a Premium member to read this tutorial/screencast, as well as hundreds of other advanced tutorials and screencasts from the Tuts+ network.

    Tuts+ Premium

    The recently re-launched Tuts+ Premium is a service that provides top-tier training in a variety of creative fields. Whether you prefer books, visual training, or in depth tutorials, we have you covered. While we unfortunately can’t afford to provide the service for free, it’s only $19 a month – less than you’d spend on dinner.

    I hope you’ll consider checking it out! In addition to learning a huge variety of new skills, it’s also a fantastic way to say thank you to Nettuts+.


  • Permalink for 'Best of Tuts+ in January 2012'

    Best of Tuts+ in January 2012

    Posted: February 2nd, 2012, 8:37am MST by David Appleyard

    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
    • Create a Pimped Out Truck Using Photoshop and Point and Shoot Photos Create a Pimped Out Truck Using Photoshop and Point and Shoot Photos

      Making modifications to your car or truck in Photoshop can be a lot of fun. In this tutorial we will demonstrate how to create a pimped out truck modification using photos taken with a simple point and shoot camera, with no advanced lighting setup. Let’s get started!

      Visit Article

    • Create an Elephant Sundae Using Photo Manipulation Techniques Create an Elephant Sundae Using Photo Manipulation Techniques

      Photoshop is great at seamlessly combing photos to create an entirely new scene. In this tutorial we will create an elephant sundae using several stock photos. Let’s get started!

      Visit Article

    • The Incredible Digital Art of Michael Oswald The Incredible Digital Art of Michael Oswald

      In this article we will be featuring the work of Michael Oswald. Oswald is a digital artist with a unique style. His technique involves a combination of photo manipulation and digital painting techniques and the results are often stunning. Let’s take a look!

      Visit Article

    • Nettuts+ — Web Development Tutorials
    • Sublime Text 2 Tips and Tricks (Updated) Sublime Text 2 Tips and Tricks (Updated)

      Sublime Text 2 is one of the fastest and most incredible code editors to be released in a long time! With a community and plugin ecosystem as passionate as this one, it just might be impossible for any other editor to catch up. I’ll show you my favorite tips and tricks today.

      Visit Article

    • An In Depth Analysis of HTML5 Multimedia and Accessibility An In Depth Analysis of HTML5 Multimedia and Accessibility

      In this tutorial, youll learn how HTML5 helps to provide you with several ways of presenting your media content to users. As a result, youll increase the availability of your media to users with different
      needs and requirements, making it more accessible.

      Visit Article

    • Writing an API Wrapper in Ruby with TDD Writing an API Wrapper in Ruby with TDD

      Sooner or later, all developers are required to interact with an API. The most difficult part is always related to reliably testing the code we write, and, as we want to make sure that everything works properly, we continuosly run code that queries the API itself. This process is slow and inefficient, as we can experience network issues and data inconsistencies (the API results may change). Let’s review how we can avoid all of this effort with Ruby.

      Visit Article

    • Vectortuts+ — Illustrator Tutorials
    • How to Illustrate a Microscope in Illustrator How to Illustrate a Microscope in Illustrator

      The microscopes is a symbol of our civilization. Throughout this tutorial on how to illustrate a vector microscope you’ll take advantage of numerous Illustrator tools. You will learn how to use blends, art brushes and 3D rendering in Adobe Illustrator. Let’s get started!

      Visit Article

    • Create a Picture Gallery in Illustrator Create a Picture Gallery in Illustrator

      This work is a common project created together with Iaroslav Lazunov and Alexander Egupov. We have used 3D rendering, Blends, Opacity masks, making this three-dimensional stage with vanishing points. Learn every step in how to create this picture gallery work.

      Visit Article

    • 13 Important Resources for Learning How to Design Typefaces and Full Fonts Important Resources for Learning How to Design Typefaces and Full Fonts

      If you’re serious about creating a typeface design, then you’ll need some solid resources to get started. Learn effective typeface design workflows, how to take an initial spark of an idea from sketch, through Illustrator, into Fontlab, and then work your creation into a complete and custom font design. Here are multiple tutorials that show you how to create fonts in Illustrator and Fontlab, and you can also dive into articles that describe the foundation of quality type design with ample inspirational examples.

      Visit Article

    • Webdesigntuts+ — Web Design Tutorials
    • A Beginner’s Guide to Pairing Fonts A Beginner’s Guide to Pairing Fonts

      Pairing fonts can be a challenge. Selecting two or more fonts which work well is one thing – selecting two which work together to achieve your typographic aims may have you reaching for the aspirin. Let’s see if we can alleviate any headaches. This guide will help you get started with font pairing for the web.

      Visit Article

    • Design a Series of Smart Banner Ads in Photoshop Design a Series of Smart Banner Ads in Photoshop

      With the continuous growth of the Internet, online marketing has gotten bigger every year, and along with it, the advertising industry. One major factor in all this craziness is buying and selling ads.

      Visit Article

    • Introduction Twitter Bootstrap 101: Introduction

      Twitter’s Bootstrap is an excellent set of carefully crafted user interface elements, layouts, and javascript tools, freely available to use in your next web design project. This video series aims to introduce you to Bootstrap; taking you all the way from downloading the resources, to building a complete Bootstrap-based website.

      Visit Article

    • Phototuts+ — Photography Tutorials
    • Love it or Leave It? HDR: Love it or Leave It?

      There are few techniques in the photography world that divide our community as much as HDR. High dynamic range images, or HDR images, are a special type of composite image that combines several images at different exposure settings in order to create an image with increased dynamic range. The look provided by HDR is loved by many, and disliked by perhaps just as many. In today’s article, we’re going to take a better look at what HDR is, and get some opinions from photographers using HDR.

      Visit Article

    • 50 Inspiring Images of Cars and Motorcycles Inspiring Images of Cars and Motorcycles

      Cars and motorbikes have been around for 100 years. Throughout the century, they have looked beautiful, satisfied our need for speed and become a symbol for thrill seeking. Today, we’ll look at photos ranging from brand new Ferrari’s to classic muscle cars.

      Visit Article

    • GIMP Portable – Take Your Editing Software With You Quick Tip: GIMP Portable – Take Your Editing Software With You

      While a number of smartphones now offer photo editing basics (and a plethora of apps to expand things even more), the portability of a solid photo editing program has been hard to come by. Photoshop is a monster in regards to space requirements and its ability to work on any system where it is not expressively installed. Picasa can be fairly ‘lightweight’ but lacks many of the more advanced photo editing tools. So what about GIMP?

      Visit Article

    • Cgtuts+ — Computer Graphics Tutorials
    • Modeling, UVmapping And Texturing A Low Poly T-Rex In Blender, Part 1 Modeling, UVmapping And Texturing A Low Poly T-Rex In Blender, Part 1

      In the first tutorial of 2012 you’ll learn how to create an awesome low-poly dinosaur using Blender and Gimp. In today’s post artist Karan Shah will walk you through the entire modeling process step by step, and show you how to create an optimized model suitable for use in any game engine.

      Visit Article

    • Create A Realistic Explosion In Maya Using Maya Fluids Create A Realistic Explosion In Maya Using Maya Fluids

      Today you’ll learn to animate and shade fluids, understand all of the major attributes, learn how adding fields will allow you to gain better control over your simulation, and how to light and render the final animation.

      Visit Article

    • The Complete Workflow, Part 1 Creating The Tree SpeedTree To UDK: The Complete Workflow, Part 1 Creating The Tree

      Due to the shear number of polygons often required to make believable 3D trees, creating realistic ones for use “in-game” can be a challenging, time consuming task. SpeedTree from IDV aims to change all that with it’s intuitive UI, ease of use and powerful toolset. Making believable trees and plants has literally never been easier!

      Visit Article

    • Aetuts+ — After Effects Tutorials
    • “Dominoes” CameraTracker and Cinema 4d Case Study – Day 1 Dominoes” CameraTracker and Cinema 4d Case Study – Day 1

      In this tutorial we’re going to go over the principle functionality of CameraTracker from The Foundry, learning basic workflow, optimizing results, aligning the ground plane and exporting this data from After Effects to Cinema 4d.

      Visit Article

    • Make An Amazing Motion Reactant Flame – Tuts+ Premium Make An Amazing Motion Reactant Flame – Tuts+ Premium

      Using just a few video elements of torch flames, we composite a burning hand by using a series of null objects and expressions to drive a time lagged displacement effect to simulate fire burning from a moving source. We use the Puppet tool for the distortion and throw on some tracked lighting effects and a displacement map for the Heat. This principle can be used to add realistic, fluid motion to any tracked object.

      Visit Article

    • 10 Key Tips To Becoming A Successful Video Freelancer Key Tips To Becoming A Successful Video Freelancer

      Youve watched thousands of tutorials. Youve put in countless hours and spent many late nights working on personal projects. Youve finally come to the conclusion that this may just be something you would like to do for a career. It can seem a little intimidating at first, because how are you going to convince someone to pay you to do this? Up until now youve been your only client. How do you get more? Im going to share my insight and experiences on how to successfully launch your freelance career this year!

      Visit Article

    • Audiotuts+ — Audio & Production Tutorials
    • 8 Free Professional Quality Audio Unit Plug-ins for Mac Free Professional Quality Audio Unit Plug-ins for Mac

      Lets face it, software is expensive. While there are hundreds of free plug-ins available online, more often than not two problems will arise: One, most of them are for PCs leaving us Mac users feeling left out. Two, most of them are vary poor quality.

      While I do agree with the saying, “The tools are only as good as the artist,” I also believe the opposite is true; that at some point the artist can only be as good as his tools are.

      Visit Article

    • Tips and Tricks Quick Tip: Drum Processing Part 4: Tips and Tricks

      This short series of quick tips is designed to give you a good overview of the audio processing techniques involved in creating a professional sounding drum beat for use in house, electro and breaks in Cubase. In this final part we will look at a few ways to add even more life to your drums.

      Here is a sample of the type of beat you could expect to end up with at the end of this series of tips:

      Visit Article

    • Use the Doubling Technique for Quick Drums Quick Tip: Use the Doubling Technique for Quick Drums

      It’s 3:30 in the afternoon when your phone rings. The head of a music library is calling and she needs your help. They have a commercial for an A-list client that needs music, and they want you to submit an entry. You’ll get $10,000 if you land the gig.

      Visit Article

    • Activetuts+ — Flash, Flex & ActionScript Tutorials
    • Create a Microphone-Controlled Flash Game: Code Create a Microphone-Controlled Flash Game: Code

      In this mini-series, we’re creating a spaceship game where the main control is via the microphone: shout louder to make the ship fly higher. So far, we’ve created all the required graphical elements for the game. Now, it’s time to work on our code. We’ve got a lot to do, so let’s get started!

      Visit Article

    • Why Bother With jQuery? A Guide for (Former) Flash Developers Why Bother With jQuery? A Guide for (Former) Flash Developers

      If you, like many Flash developers, are looking into using HTML5 for your web apps, you’ll almost certainly have come across jQuery. It’s a very popular JavaScript library, used by a large percentage of the most visited websites – but what’s all the fuss about, and should you use it?

      Visit Article

    • An Introduction to the HTML5 Gamepad API An Introduction to the HTML5 Gamepad API

      As HTML games begin to gradually increase in popularity, vendors are starting to introduce some exciting new APIs to make gaming that little bit sweeter for both us developers and our end players. One of these is the GamepadAPI, which allows you to connect your good old console gamepad into your computer and use it for browser based games, plug and play style. Let’s dive in!

      Visit Article

    • Wptuts+ — WordPress Tutorials
    • The Rise of HTML5 in WordPress The Rise of HTML5 in WordPress

      2011 was a big year for the advancement of HTML5 in the web development community. It became pretty widely adopted, especially for the mobile web. There have been major projects that help developers use HTML5, like Paul Irish’s HTML5 Boilerplate (technically 2010, but popularized in 2011) and books galore!

      Visit Article

    • Extra Fields Reusable Custom Meta Boxes Part 3: Extra Fields

      In Part 1 and Part 2 of our custom meta box template tutorial series, we learned how to create a field array to loop through and create a custom meta box with your standard fields. Now let’s throw in a bit of JavaScript for some fancy, but highly useful fields.

      Visit Article

    • The Ultimate Quickstart Guide to Speeding Up Your WordPress Site The Ultimate Quickstart Guide to Speeding Up Your WordPress Site

      Give your site a boost! Implement crucial optimization techniques that will improve not only your ySlow score, but your Google rank too. In this tutorial we will cover all aspects of W3 caching, ySlow, Google page speed, CSS sprites & htaccess rules, to achieve a high ySlow score like i have done on my blog.

      Visit Article

    • Mobiletuts+ — Mobile Development Tutorials
    • Creating an Awesome Carousel iOS SDK: Creating an Awesome Carousel

      Engage your users with stunning carousels. We’ll look at how easy and clean it can be to implement scrollable, interactive carousels in your iOS applications. With high configurability, you can have 3D, flat, rotating, and endless scrolling arrays for data, images, or buttons.

      Visit Article

    • Introduction PhoneGap From Scratch: Introduction

      Want to learn how to use PhoneGap, but don’t know where to get started? Join us as we put together “Sculder”, not only a tribute to an excellent science fiction TV series, but a fully-fledged native mobile application for the believer in you!

      Visit Article

    • Setting the Record Straight Mobile Flash is Far From Dead: Setting the Record Straight

      In light of recent announcements from Adobe, there has been a lot of confusion over the state of the Flash Platform – specifically in regard to Flash content on mobile devices. This article seeks to clarify many of the misconceptions that exist by addressing the main points of confusion around these announcements regardless of the initial, monumental, and absolutely unbelievable blunders from failed public (and private) relations messaging and general marketing surrounding these announcements.

      Visit Article


  • Permalink for 'Learn jQuery in 30 Days'

    Learn jQuery in 30 Days

    Posted: January 31st, 2012, 9:47pm MST by Jeffrey Way

    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 I’m happy to announce my new course: “Learn jQuery in 30 Days”. If you’ll give me fifteen minutes a day for the next month, I’ll help you become a jQuery pro – and it’s free!

    How Does it Work? Learn jQuery

    Sporadically, your skills will be put to the test, when you take the interactive quizzes!

    Once you enroll (free) via email, each day, you’ll receive a 10-15 minute video lesson. As you might expect, every episode will build upon the one it proceeds, and, sporadically, your skills will be put to the test, when you take the interactive quizzes!

    Along the way, you’ll learn the essentials (querying and manipulating the DOM), while incrementally working your way up to more advanced topics, such as jQuery’s AJAX methods and plugin development.

    I worked particularly hard to make the process of picking up this new skill as easy as possible for everyone – even if you have very, very little JavaScript experience. So…do you want to join me?


  • Permalink for 'Recently in Web Development (January ’12 Edition)'

    Recently in Web Development (January ’12 Edition)

    Posted: January 30th, 2012, 1:37pm MST by Siddharth

    Web development is an industry that’s in a state of constant flux with technologies and jargon changing and mutating in an endless cycle. Not to mention the sheer deluge of information one has to process everyday.

    In this series, published monthly, we’ll seek to rectify this by bringing you all the important news, announcements, releases and interesting discussions within the web development industry in a concise package. Join me after the jump for an extra dose of community content this month!

    News and Releases

    All of the important news in a single place: releases, announcements, companies bickering, security issues and all related hoopla.

    Nettuts image ‘HTML5 Please’ Helps Devs Make Informed Decisions

    HTML5 is a beast of a spec with no one truly knowing everything there is to know. This shiny new site gives you all the information you need to use HTML5 features on your site, right now.

    The site provides you with recommendations as to whether you should be using that specific facet of HTML5 right now and provides you with helpful links to polyfills, when necessary. Time saver!

    Read more

    Nettuts image HP Open Sources Enyo

    Enyo is the engine that powers webOS. But what exactly is Enyo, you ask? Well, it’s a spiffy JavaScript framework that helps you build better performing, easier to maintain application.

    I’m sure you’ve heard this plenty of times before so why don’t you check out the link below to find out for yourself?

    Read more

    Nettuts image Tech Giants Protest SOPA

    Last month saw a figurative deluge of protests against SOPA. If you have no idea what SOPA is, hit the link below to find out.

    While many services merely blackened out their logo, many others, including Wikipedia and Reddit, went the extra length and completely blacked out their sites. The proposed bill has been shelved but I predict that we’ll see another in a different skin soon…

    Read more

    Nettuts image Vim on a Tablet? Yes, Please!

    I understand not everyone uses a tablet but the number is growing, quite rapidly. Wouldn’t it be great to SSH into your server to fix that pesky bug? Get a proper laptop, you say? I’m going to ask you to shush for now and go with the flow.

    This month saw the release of Vim for the iOS platform. And no, it’s not a gimped version. From a quick run through, it seems that all the nice bits are still in there. If you’re in the intersection between developers and iPad users, let us know in the comments below as to whether it fits your needs.

    Read more

    Nettuts image Cut the Rope Ported to the Browser

    I’m sure a lot of you have played this ridiculously cute ‘aww’ inducing game. What brings the game to our list is the fact that it has been ported to the browser by the newly cool Internet Explorer team.

    And true to their current vision, they’ve ported it using JavaScript and the magic of HTML5. The link below leads you to a write up about the game development instead of the game itself to protect your productivity.

    Read more

    Nettuts image The Rails Tutorial, Version Two, Inches Towards Completion

    ‘The’ Rails tutorial? Indeed it is! Michael Hartl’s free has helped many learn the voodoo that is Rails and Michael is slowly updating his ebook for Ruby 1.9 and Rails 3.2

    Thus far, six chapters are out with a chapter expected every week in the future. Make sure to check the site out!

    Read more

    Nettuts image Sublime Text 2 Piles on More Features with New Beta

    Sublime Text 2 is a grand piece of work and every build only reaffirms this. This new build introduces a ton of features including auto complete, performance improvements, a new UI theme and a ton more.

    Read more

    New Kids on the Block

    As web developers, the sheer amount of resources we can tap into increases exponentially with time. Here is just a quick look at some recently created resources that deserve your attention — everything from new books to scripts and frameworks.

    wrap.js

    My wrap.js plugin handles the nested require based on a config, and takes it to the next level by generating an actual AMD module for you during the build. So now you don’t have to write wrappers around scripts that you wish were modules, wrap.js does that for you.

    Github Repo

    Resumable.js

    Resumables is a JavaScript library providing multiple simultaneous, stable and resumable uploads via the HTML5 File API.
    The library is designed to introduce fault-tolerance into the upload of large files through [HTTP.] This is done by splitting each files into small chunks; whenever the upload of a chunk fails, uploading is retried until the procedure completes.

    Github Repo

    IcedCoffeeScript

    IcedCoffeeScript is a fork of CoffeeScript. It is superset of the CoffeeScript language. The iced interpreter is a drop-in replacement for the standard coffee interpreter since it will interpret all existing CoffeeScript programs. IcedCoffeeScript (ICS) adds two new keywords: await and defer. These additions simply and powerfully streamline asynchronous control flow, both on the server and on the browser.

    Github Repo

    Banking.js

    Banking.JS retrieves all of your bank transactions similiar to how quickbooks does it. There is no need to depend on or pay for third party services. The bank statement results are in JSON or Valid XML and supports all financial institutions.

    Github Repo

    Roy

    Roy is a small functional language that compiles to JavaScript. The main features include whitespace significant syntax, compile-time meta-programming, structural typing and monad syntax

    Github Repo

    jsgif

    jsgif an animated GIF player bookmarklet with support for pausing, going frame-by-frame, playing in reverse, and other features that one might expect from a video player.

    Github Repo

    zip.js

    zip.js offers a low-level API for writing and reading large zip files (up to 4GB) with a stable RAM use. It also offers a Filesystem API in order to manipulate zip file structure.

    Github Repo

    Seriously.js

    Seriously.js is a real-time, node-based video compositor for the web. Inspired by professional software such as After Effects and Nuke, Seriously.js renders high-quality video effects, but allows them to be dynamic and interactive.

    Github Repo

    Best of the Internet

    Often, you’re not really looking for a tutorial as much as you’re looking for a rant, an opinion or the musings of a tired developer or just something cool with absolutely zero real world use. This sections contains links to precisely those — interesting and cool stuff from the developer community.

    Nettuts image The Five Stages of Hosting

    Five common options for hosting a web business, ranked in decreasing order of ‘cloudiness’.

    Read more

    Nettuts image JavaScript Needs Blocks

    Yehuda Katz talks about why he wants to see block lambdas in JavaScript. It’s a bit technical but well worth a read.

    Read more

    Nettuts image How I Learned Enough Ruby On Rails In 12 Weeks To Launch Freelancify

    A Non-Developer explains how… I think you know already. Just click the darn link and move on.

    Read more

    Nettuts image Why are software development task estimations regularly off by a factor of 2-3?

    Is it the developer’s fault? Is it a management issue? Bad methodology, or lack thereof? Or is it ingrained in the nature of the process?

    Read more

    Nettuts image Explanation for the ‘Wat’ Talk – CodeMash 2012

    This StackOverflow question, along with the well written answers below, explore the code that was demonstrated in the talk mentioned in the title. Provides a quick look at the quirkier portions of JavaScript.

    Read more

    Nettuts image Why are column oriented databases so much faster than row oriented databases?

    A quick little read that explains why, and how, different databases perform differently. There isn’t much jargon there and gets the point quite clearly.

    Read more

    Nettuts image PHP Mind Love

    The link below points to some PHP code. Figure out what the output is and you get a cookie!

    Read more

    Nettuts image Testing Socket.IO With Mocha, Should.js and Socket.IO Client

    A clean writeup that details how the author got all the named technologies working together.

    Read more

    Nettuts image What is the difference between semicolons in JavaScript and in Python?

    Ever had to think about the question above? How exactly do they each handle semicolons and newlines? Read up below.

    Read more

    Nettuts image The Programming Djinn

    The Least Boring Programming Book teaches Ruby programming to beginners in an unconventional way.

    Read more

    Nettuts image Non-Canvas Wizardry

    I don’t really have much context to go on here so just give the link below a click. Pretty smooth stuff for something that’s not canvas or Flash based.

    Read more

    Wrapping Up

    Well, that’s about all the major changes that happened in our industry lately.

    Do you want us to cover more standard news? A focus on upcoming scripts maybe? Or just more interesting posts and discussions from the community? Let us know in the comments and thank you so much for reading!


  • Permalink for 'Writing an API Wrapper in Ruby with TDD'

    Writing an API Wrapper in Ruby with TDD

    Posted: January 28th, 2012, 4:18pm MST by Claudio Ortolina

    Sooner or later, all developers are required to interact with an API. The most difficult part is always related to reliably testing the code we write, and, as we want to make sure that everything works properly, we continuosly run code that queries the API itself. This process is slow and inefficient, as we can experience network issues and data inconsistencies (the API results may change). Let’s review how we can avoid all of this effort with Ruby.

    Our Goal

    “Flow is essential: write the tests, run them and see them fail, then write the minimal implementation code to make them pass. Once they all do, refactor if needed.”

    Our goal is simple: write a small wrapper around the Dribbble API to retrieve information about a user (called ‘player’ in the Dribbble world).
    As we will be using Ruby, we will also follow a TDD approach: if you’re not familiar with this technique, Nettuts+ has a good primer on RSpec you can read. In a nutshell, we will write tests before writing our code implementation, making it easier to spot bugs and to achieve a high code quality. Flow is essential: write the tests, run them and see them fail, then write the minimal implementation code to make them pass. Once they all do, refactor if needed.

    The API

    The Dribbble API is fairly straightforward. At the time of this it supports only GET requests and doesn’t require authentication: an ideal candidate for our tutorial. Moreover, it offers a 60 calls per minute limit, a restriction that perfectly shows why working with APIs require a smart approach.

    Key Concepts

    This tutorial needs to assume that you have some familiarity with testing concepts: fixtures, mocks, expectations. Testing is an important topic (especially in the Ruby community) and even if you are not a Rubyist, I’d encourage you to dig deeper into the matter and to search for equivalent tools for your everyday language. You may want to read “The RSpec book” by David Chelimsky et al., an excellent primer on Behavior Driven Development.

    To summarize here, here are three key concepts you must know:

    • Mock: also called double, a mock is “an object that stands in for another object in an example”. This means that if we want to test the interaction between an object and another, we can mock the second one. In this tutorial, we will mock the Dribbble API, as to test our code we don’t need the API, itself, but something that behaves like it and exposes the same interface.
    • Fixture: a dataset that recreates a specific state in the system. A fixture can be used to create the needed data to test a piece of logic.
    • Expectation: a test example written the from the point of view of the result we want to achieve.
    Our Tools

    “As a general practice, run tests every time you update them.”

    WebMock is a Ruby mocking library that is used to mock (or stub) http requests. In other words, it allows you to simulate any HTTP request without actually making one. The primary advantage to this is being able to develop and test against any HTTP service without needing the service itself and without incurring in related issues (like API limits, IP restrictions and such).
    VCR is a complementary tool that records any real http request and creates a fixture, a file that contains all the needed data to replicate that request without performing it again. We will configure it to use WebMock to do that. In other words, our tests will interact with the real Dribbble API just once: after that, WebMock will stub all the requests thanks to the data recorded by VCR. We will have a perfect replica of the Dribbble API responses recorded locally. In addition, WebMock will let us test edge cases (like the request timing out) easily and consistently. A wonderful consequence of our setup is that everything will be extremely fast.

    As for unit testing, we will be using Minitest. It’s a fast and simple unit testing library that also supports expectations in the RSpec fashion. It offers a smaller feature set, but I find that this actually encourages and pushes you to separate your logic into small, testable methods. Minitest is part of Ruby 1.9, so if you’re using it (I hope so) you don’t need to install it. On Ruby 1.8, it’s only a matter of gem install minitest.

    I will be using Ruby 1.9.3: if you don’t, you will probably encounter some issues related to require_relative, but I’ve included fallback code in a comment right below it. As a general practice, you should run tests every time you update them, even if I won’t be mentioning this step explicitly throughout the tutorial.

    Setup Setup

    We will use the conventional /lib and /spec folder structure to organize our code. As for the name of our library, we’ll call it Dish, following the Dribbble convention of using basketball related terms.

    The Gemfile will contain all our dependencies, albeit they’re quite small.

    source :rubygems
    
    gem 'httparty'
    
    group :test do
      gem 'webmock'
      gem 'vcr'
      gem 'turn'
      gem 'rake'
    end
    

    Httparty is an easy to use gem to handle HTTP requests; it will be the core of our library. In the test group, we will also add Turn to change the output of our tests to be more descriptive and to support color.

    The /lib and /spec folders have a symmetrical structure: for every file contained in the /lib/dish folder, there should be a file inside /spec/dish with the same name and the ‘_spec’ suffix.

    Let’s start by creating a /lib/dish.rb file and add the following code:

    require " [httparty"] Dir[File.dirname(__FILE__) + '/dish/*.rb'].each do |file|
      require file
    end
    

    It doesn’t do much: it requires ‘ [httparty’] and then iterates over every .rb file inside /lib/dish to require it. With this file in place, we will be able to add any functionality inside separate files in /lib/dish and have it automatically loaded just by requiring this single file.

    Let’s move to the /spec folder. Here’s the content of the spec_helper.rb file.

    #we need the actual library file
    require_relative '../lib/dish'
    # For Ruby < 1.9.3, use this instead of require_relative
    # require(File.expand_path('../../lib/dish', __FILE__))
    
    #dependencies
    require 'minitest/autorun'
    require 'webmock/minitest'
    require 'vcr'
    require 'turn'
    
    Turn.config do |c|
     # :outline  - turn's original case/test outline mode [default]
     c.format  = :outline
     # turn on invoke/execute tracing, enable full backtrace
     c.trace   = true
     # use humanized test names (works only with :outline format)
     c.natural = true
    end
    
    #VCR config
    VCR.config do |c|
      c.cassette_library_dir = 'spec/fixtures/dish_cassettes'
      c.stub_with :webmock
    end
    

    There’s quite a few things here worth noting, so let’s break it piece by piece:

    • At first, we require the main lib file for our app, making the code we want to test available to the test suite. The require_relative statement is a Ruby 1.9.3 addition.
    • We then require all the library dependencies: minitest/autorun includes all the expectations we will be using, webmock/minitest adds the needed bindings between the two libraries, while vcr and turn are pretty self-explanatory.
    • The Turn config block merely needs to tweak our test output. We will use the outline format, where we can see the description of our specs.
    • The VCR config blocks tells VCR to store the requests into a fixture folder (note the relative path) and to use WebMock as a stubbing library (VCR supports some other ones).

    Last, but not least, the Rakefile that contains some support code:

    require 'rake/testtask'
    
    Rake::TestTask.new do |t|
      t.test_files = FileList['spec/lib/dish/*_spec.rb']
      t.verbose = true
    end
    
    task :default => :test
    

    The rake/testtask library includes a TestTask class that is useful to set the location of our test files. From now on, to run our specs, we will only type rake from the library root directory.

    As a way to test our configuration, let’s add the following code to /lib/dish/player.rb:

    module Dish
      class Player
      end
    end
    

    Then /spec/lib/dish/player_spec.rb:

    require_relative '../../spec_helper'
    # For Ruby < 1.9.3, use this instead of require_relative
    # require (File.expand_path('./../../../spec_helper', __FILE__))
    
    describe Dish::Player do
    
      it "must work" do
        "Yay!".must_be_instance_of String
      end
    
    end
    

    Running rake should give you one test passing and no errors. This test is by no means useful for our project, yet it implicitly verifies that our library file structure is in place (the describe block would throw an error if the Dish::Player module was not loaded).

    First Specs

    To work properly, Dish requires the [Httparty] modules and the correct base_uri, i.e. the base url of the Dribbble API. Let’s write the relevant tests for these requirements in player_spec.rb:

    ...
    describe Dish::Player do
    
      describe "default attributes" do
    
        it "must include [httparty] methods" do
          Dish::Player.must_include [HTTParty]     end
    
        it "must have the base url set to the Dribble API endpoint" do
          Dish::Player.base_uri.must_equal 'http://api.dribbble.com'
        end
    
      end
    
    end
    

    As you can see, Minitest expectations are self-explanatory, especially if you are an RSpec user: the biggest difference is wording, where Minitest prefers “must/wont” to “should/should_not”.

    Running these tests will show one error and one failure. To have them pass, let’s add our first lines of implementation code to player.rb:

    module Dish
    
      class Player
    
        include [HTTParty] 
        base_uri 'http://api.dribbble.com'
    
      end
    
    end
    

    Running rake again should show the two specs passing. Now our Player class has access to all [Httparty] class methods, like get or post.

    Recording our First Request

    As we will be working on the Player class, we will need to have API data for a player. The Dribbble API documentation page shows that the endpoint to get data about a specific player is http://api.dribbble.com/players/:id

    As in typical Rails fashion, :id is either the id or the username of a specific player. We will be using simplebits, the username of Dan Cederholm, one of the Dribbble founders.

    To record the request with VCR, let’s update our player_spec.rb file by adding the following describe block to the spec, right after the first one:

      ...
    
      describe "GET profile" do
    
      before do
        VCR.insert_cassette 'player', :record => :new_episodes
      end
    
      after do
        VCR.eject_cassette
      end
    
      it "records the fixture" do
        Dish::Player.get('/players/simplebits')
      end
    
      end
    
    end
    

    After running rake, you can verify that the fixture has been created. From now on, all our tests will be completely network independent.

    The before block is used to execute a specific portion of code before every expectation: we use it to add the VCR macro used to record a fixture that we will call ‘player’. This will create a player.yml file under spec/fixtures/dish_cassettes. The :record option is set to record all new requests once and replay them on every subsequent, identical request. As a proof of concept, we can add a spec whose only aim is to record a fixture for simplebits’s profile. The after directive tells VCR to remove the cassette after the tests, making sure that everything is properly isolated. The get method on the Player class is made available, thanks to the inclusion of the Httparty module.

    After running rake, you can verify that the fixture has been created. From now on, all our tests will be completely network independent.

    Getting the Player Profile Dribbble

    Every Dribbble user has a profile that contains a pretty extensive amount of data. Let’s think about how we would like our library to be when actually used: this is a useful way to flesh out our DSL will work. Here’s what we want to achieve:

    simplebits = Dish::Player.new('simplebits')
    simplebits.profile
      => #returns a hash with all the data from the API
    simplebits.username
      => 'simplebits'
    simplebits.id
      => 1
    simplebits.shots_count
      => 157
    

    Simple and effective: we want to instantiate a Player by using its username and then get access to its data by calling methods on the instance that map to the attributes returned by the API. We need to be consistent with the API itself.

    Let’s tackle one thing at a time and write some tests related to getting the player data from the API. We can modify our "GET profile" block to have:

    describe "GET profile" do
    
      let(:player) { Dish::Player.new }
    
      before do
        VCR.insert_cassette 'player', :record => :new_episodes
      end
    
      after do
        VCR.eject_cassette
      end
    
      it "must have a profile method" do
        player.must_respond_to :profile
      end
    
      it "must parse the api response from JSON to Hash" do
        player.profile.must_be_instance_of Hash
      end
    
      it "must perform the request and get the data" do
        player.profile["username"].must_equal 'simplebits'
      end
    
    end
    

    The let directive at the top creates a Dish::Player instance available in the expectations. Next, we want to make sure that our player has got a profile method whose value is a hash representing the data from the API. As a last step, we test a sample key (the username) to make sure that we actually perform the request.

    Note that we’re not yet handling how to set the username, as this is a further step. The minimal implementation required is the following:

    ...
    class Player
    
      include [HTTParty] 
      base_uri 'http://api.dribbble.com'
    
      def profile
        self.class.get '/players/simplebits'
      end
    
    end
    ...
    

    A very little amount of code: we’re just wrapping a get call in the profile method. We then pass the hardcoded path to retrieve simplebits’s data, data that we had already stored thanks to VCR.

    All our tests should be passing.

    Setting the Username

    Now that we have a working profile function, we can take care of the username. Here are the relevant specs:

    describe "default instance attributes" do
    
      let(:player) { Dish::Player.new('simplebits') }
    
      it "must have an id attribute" do
        player.must_respond_to :username
      end
    
      it "must have the right id" do
        player.username.must_equal 'simplebits'
      end
    
    end
    
    describe "GET profile" do
    
      let(:player) { Dish::Player.new('simplebits') }
    
      before do
        VCR.insert_cassette 'base', :record => :new_episodes
      end
    
      after do
        VCR.eject_cassette
      end
    
      it "must have a profile method" do
        player.must_respond_to :profile
      end
    
      it "must parse the api response from JSON to Hash" do
        player.profile.must_be_instance_of Hash
      end
    
      it "must get the right profile" do
        player.profile["username"].must_equal "simplebits"
      end
    
    end
    

    We’ve added a new describe block to check the username we’re going to add and simply amended the player initialization in the GET profile block to reflect the DSL we want to have. Running the specs now will reveal many errors, as our Player class doesn’t accept arguments when initialized (for now).

    Implementation is very straightforward:

    ...
    class Player
    
      attr_accessor :username
    
      include [HTTParty] 
      base_uri 'http://api.dribbble.com'
    
      def initialize(username)
        self.username = username
      end
    
      def profile
        self.class.get "/players/#{self.username}"
      end
    
    end
    ...
    

    The initialize method gets a username that gets stored inside the class thanks to the attr_accessor method added above. We then change the profile method to interpolate the username attribute.

    We should get all our tests passing once again.

    Dynamic Attributes

    At a basic level, our lib is in pretty good shape. As profile is a Hash, we could stop here and already use it by passing the key of the attribute we want to get the value for. Our goal, however, is to create an easy to use DSL that has a method for each attribute.

    Let’s think about what we need to achieve. Let’s assume we have a player instance and stub how it would work:

    player.username
      => 'simplebits'
    player.shots_count
      => 157
    player.foo_attribute
      => NoMethodError
    

    Let’s translate this into specs and add them to the GET profile block:

    ...
    describe "dynamic attributes" do
    
      before do
        player.profile
      end
    
      it "must return the attribute value if present in profile" do
        player.id.must_equal 1
      end
    
      it "must raise method missing if attribute is not present" do
        lambda { player.foo_attribute }.must_raise NoMethodError
      end
    
    end
    ...
    

    We already have a spec for username, so we don’t need to add another one. Note a few things:

    • we explicitly call player.profile in a before block, otherwise it will be nil when we try to get the attribute value.
    • to test that foo_attribute raises an exception, we need to wrap it in a lambda and check that it raises the expected error.
    • we test that id equals 1, as we know that that is the expected value (this is a purely data-dependent test).

    Implementation-wise, we could define a series of methods to access the profile hash, yet this would create a lot of duplicated logic. Moreover, the would rely on the API result to always have the same keys.

    “We will rely on method_missing to handle this cases and ‘generate’ all those methods on the fly.”

    Instead, we will rely on method_missing to handle this cases and ‘generate’ all those methods on the fly. But what does this mean? Without going into too much metaprogramming, we can simply say that every time we call a method not present on the object, Ruby raises a NoMethodError by using method_missing. By redefining this very method inside a class, we can modify its behaviour.

    In our case, we will intercept the method_missing call, verify that the method name that has been called is a key in the profile hash and in case of positive result, return the hash value for that key. If not, we will call super to raise a standard NoMethodError: this is needed to make sure that our library behaves exactly the way any other library would do. In other words, we want to guarantee the least possible surprise.

    Let’s add the following code to the Player class:

    def method_missing(name, *args, &block)
      if profile.has_key?(name.to_s)
        profile[name.to_s]
      else
        super
      end
    end
    

    The code does exactly what described above. If you now run the specs, you should have them all pass. I’d encorage you to add some more to the spec files for some other attribute, like shots_count.

    This implementation, however, is not really idiomatic Ruby. It works, but it can be streamlined into a ternary operator, a condensed form of an if-else conditional. It can be rewritten as:

    def method_missing(name, *args, &block)
      profile.has_key?(name.to_s) ? profile[name.to_s] : super
    end
    

    It’s not just a matter of length, but also a matter of consistency and shared conventions between developers. Browsing source code of Ruby gems and libraries is a good way to get accustomed to these conventions.

    Caching

    As a final step, we want to make sure that our library is efficient. It should not make any more requests than needed and possibly cache data internally. Once again, let’s think about how we could use it:

    player.profile
      => performs the request and returns a Hash
    player.profile
      => returns the same hash
    player.profile(true)
      => forces the reload of the http request and then returns the hash (with data changes if necessary)
    

    How can we test this? We can by using WebMock to enable and disable network connections to the API endpoint. Even if we’re using VCR fixtures, WebMock can simulate a network Timeout or a different response to the server. In our case, we can test caching by getting the profile once and then disabling the network. By calling player.profile again we should see the same data, while by calling player.profile(true) we should get a Timeout::Error, as the library would try to connect to the (disabled) API endpoint.

    Let’s add another block to the player_spec.rb file, right after dynamic attribute generation:

    describe "caching" do
    
      # we use Webmock to disable the network connection after
      # fetching the profile
      before do
        player.profile
        stub_request(:any, /api.dribbble.com/).to_timeout
      end
    
      it "must cache the profile" do
        player.profile.must_be_instance_of Hash
      end
    
      it "must refresh the profile if forced" do
        lambda { player.profile(true) }.must_raise Timeout::Error
      end
    
    end
    

    The stub_request method intercepts all calls to the API endpoint and simulates a timeout, raising the expected Timeout::Error. As we did before, we test the presence of this error in a lambda.

    Implementation can be tricky, so we’ll split it into two steps. Firstly, let’s move the actual http request to a private method:

    ...
    def profile
      get_profile
    end
    
    ...
    
    private
    
    def get_profile
      self.class.get("/players/#{self.username}")
    end
    ...
    

    This will not get our specs passing, as we’re not caching the result of get_profile. To do that, let’s change the profile method:

    ...
    def profile
      @profile ||= get_profile
    end
    ...
    

    We will store the result hash into an instance variable. Also note the ||= operator, whose presence makes sure that get_profile is run only if @profile returns a falsy value (like nil).

    Next we can add the forced reload directive:

    ...
    def profile(force = false)
      force ? @profile = get_profile : @profile ||= get_profile
    end
    ...
    

    We’re using a ternary again: if force is false, we perform get_profile and cache it, if not, we use the logic written in the previous version of this method (i.e. performing the request only if we don’t have already an hash).

    Our specs should be green now and this is also the end of our tutorial.

    Wrapping Up

    Our purpose in this tutorial was to write a small and efficient library to interact with the Dribbble API; we’ve laid the foundation for this to happen. Most of the logic we’ve written can be abstracted and reused to access all the other endpoints. Minitest, WebMock and VCR have proven to be valuable tools to help us shape our code.

    We do, however, need to be aware of a small caveat: VCR can become a double-edged sword, as our tests can become too much data-dependent. If, for any reason, the API we’re building against changes without any visible sign (like a version number), we may risk having our tests perfectly working with a dataset, which is no longer relevant. In that case, removing and recreating the fixture is the best way to make sure that our code still works as expected.


  • Permalink for '24 Extremely Useful Ruby Gems for Web Development'

    24 Extremely Useful Ruby Gems for Web Development

    Posted: January 26th, 2012, 2:38pm MST by Siddharth

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

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

    A Quick Note

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

    CarrierWave

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

    Related reading

    Kaminari

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

    Related reading

    HAML

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

    Related reading

    Authlogic

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

    Related reading

    Shoulda

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

    Related reading

    factory_girl

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

    Related reading

    RMagick

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

    Related reading

    Cancan

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

    Related reading

    Nokogiri

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

    Related reading

    SASS

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

    Related reading

    Formtastic

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

    Related reading

    Capistrano

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

    Related reading

    Omniauth

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

    Related reading

    Bundler

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

    Related reading

    resque

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

    Related reading

    Jammit

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

    Related reading

    capybara

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

    Related reading

    Active Merchant

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

    Related reading

    eventmachine

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

    Related reading

    mustache

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

    Related reading

    Passenger

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

    Related reading

    Chef

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

    Related reading

    Thinking Sphinx

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

    Related reading

    Wrapping Up

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


  • Permalink for 'Why you Should be using PHP’s PDO for Database Access'

    Why you Should be using PHP’s PDO for Database Access

    Posted: January 25th, 2012, 9:04am MST by Erik Wurzer

    Many PHP programmers learned how to access databases by using either the MySQL or MySQLi extensions. As of PHP 5.1, there’s a better way. PHP Data Objects (PDO) provide methods for prepared statements and working with objects that will make you far more productive!

    May of 2010 PDO Introduction

    “PDO – PHP Data Objects – is a database access layer providing a uniform method of access to multiple databases.”

    It doesn’t account for database-specific syntax, but can allow for the process of switching databases and platforms to be fairly painless, simply by switching the connection string in many instances.

    PDO - db abstraction layer

    This tutorial isn’t meant to be a complete how-to on SQL. It’s written primarily for people currently using the mysql or mysqli extension to help them make the jump to the more portable and powerful PDO.

    Database Support

    The extension can support any database that a PDO driver has been written for. At the time of this writing, the following database drivers are available:

    • PDO_DBLIB ( FreeTDS / Microsoft SQL Server / Sybase )
    • PDO_FIREBIRD ( Firebird/Interbase 6 )
    • PDO_IBM ( IBM DB2 )
    • PDO_INFORMIX ( IBM Informix Dynamic Server )
    • PDO_MYSQL ( MySQL 3.x/4.x/5.x )
    • PDO_OCI ( Oracle Call Interface )
    • PDO_ODBC ( ODBC v3 (IBM DB2, unixODBC and win32 ODBC) )
    • PDO_PGSQL ( PostgreSQL )
    • PDO_SQLITE ( SQLite 3 and SQLite 2 )
    • PDO_4D ( 4D )

    All of these drivers are not necessarily available on your system; here’s a quick way to find out which drivers you have:

    print_r(PDO::getAvailableDrivers());
    
    Connecting

    Different databases may have slightly different connection methods. Below, the method to connect to some of the most popular databases are shown. You’ll notice that the first three are identical, other then the database type – and then SQLite has its own syntax.

    Connection String
    try {
      # MS SQL Server and Sybase with PDO_DBLIB
      $DBH = new PDO("mssql:host=$host;dbname=$dbname, $user, $pass");
      $DBH = new PDO("sybase:host=$host;dbname=$dbname, $user, $pass");
    
      # MySQL with PDO_MYSQL
      $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
    
      # SQLite Database
      $DBH = new PDO("sqlite:my/database/path/database.db");
    }
    catch(PDOException $e) {
        echo $e->getMessage();
    }
    

    Please take note of the try/catch block – you should always wrap your PDO operations in a try/catch, and use the exception mechanism – more on this shortly. Typically you’re only going to make a single connection – there are several listed to show you the syntax. $DBH stands for ‘database handle’ and will be used throughout this tutorial.

    You can close any connection by setting the handle to null.

    # close the connection
    $DBH = null;
    

    You can get more information on database specific options and/or connection strings for other databases from PHP.net.

    Exceptions and PDO

    PDO can use exceptions to handle errors, which means anything you do with PDO should be wrapped in a try/catch block. You can force PDO into one of three error modes by setting the error mode attribute on your newly created database handle. Here’s the syntax:

    $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
    $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
    $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    

    No matter what error mode you set, an error connecting will always produce an exception, and creating a connection should always be contained in a try/catch block.

    PDO::ERRMODE_SILENT

    This is the default error mode. If you leave it in this mode, you’ll have to check for errors in the way you’re probably used to if you used the mysql or mysqli extensions. The other two methods are more ideal for DRY programming.

    PDO::ERRMODE_WARNING

    This mode will issue a standard PHP warning, and allow the program to continue execution. It’s useful for debugging.

    PDO::ERRMODE_EXCEPTION

    This is the mode you should want in most situations. It fires an exception, allowing you to handle errors gracefully and hide data that might help someone exploit your system. Here’s an example of taking advantage of exceptions:

    # connect to the database
    try {
      $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
      $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    
      # UH-OH! Typed DELECT instead of SELECT!
      $DBH->prepare('DELECT name FROM people');
    }
    catch(PDOException $e) {
        echo "I'm sorry, Dave. I'm afraid I can't do that.";
        file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
    }
    

    There’s an intentional error in the select statement; this will cause an exception. The exception sends the details of the error to a log file, and displays a friendly (or not so friendly) message to the user.

    Insert and Update

    Inserting new data, or updating existing data is one of the more common database operations. Using PDO, this is normally a two-step process. Everything covered in this section applies equally to both UPDATE and INSERT operations.

    2 to 3 step insert and update

    Here’s an example of the most basic type of insert:

    # STH means "Statement Handle"
    $STH = $DBH->prepare("INSERT INTO folks ( first_name ) values ( 'Cathy' )");
    $STH->execute();
    

    You could also accomplish the same operation by using the exec() method, with one less call. In most situations, you’re going to use the longer method so you can take advantage of prepared statements. Even if you’re only going to use it once, using prepared statements will help protect you from SQL injection attacks.

    Prepared Statements

    Using prepared statements will help protect you from SQL injection.

    A prepared statement is a precompiled SQL statement that can be executed multiple times by sending just the data to the server. It has the added advantage of automatically making the data used in the placeholders safe from SQL injection attacks.

    You use a prepared statement by including placeholders in your SQL. Here’s three examples: one without placeholders, one with unnamed placeholders, and one with named placeholders.

    # no placeholders - ripe for SQL Injection!
    $STH = $DBH->("INSERT INTO folks (name, addr, city) values ($name, $addr, $city)");
    
    # unnamed placeholders
    $STH = $DBH->("INSERT INTO folks (name, addr, city) values (?, ?, ?);
    
    # named placeholders
    $STH = $DBH->("INSERT INTO folks (name, addr, city) value (:name, :addr, :city)");
    

    You want to avoid the first method; it’s here for comparison. The choice of using named or unnamed placeholders will affect how you set data for those statements.

    Unnamed Placeholders
    # assign variables to each place holder, indexed 1-3
    $STH->bindParam(1, $name);
    $STH->bindParam(2, $addr);
    $STH->bindParam(3, $city);
    
    # insert one row
    $name = "Daniel"
    $addr = "1 Wicked Way";
    $city = "Arlington Heights";
    $STH->execute();
    
    # insert another row with different values
    $name = "Steve"
    $addr = "5 Circle Drive";
    $city = "Schaumburg";
    $STH->execute();
    

    There are two steps here. First, we assign variables to the various placeholders (lines 2-4). Then, we assign values to those placeholders and execute the statement. To send another set of data, just change the values of those variables and execute the statement again.

    Does this seem a bit unwieldy for statements with a lot of parameters? It is. However, if your data is stored in an array, there’s an easy shortcut:

    # the data we want to insert
    $data = array('Cathy', '9 Dark and Twisty Road', 'Cardiff');
    
    $STH = $DBH->("INSERT INTO folks (name, addr, city) values (?, ?, ?);
    $STH->execute($data);
    

    That’s easy!

    The data in the array applies to the placeholders in order. $data[0] goes into the first placeholder, $data[1] the second, etc. However, if your array indexes are not in order, this won’t work properly, and you’ll need to re-index the array.

    Named Placeholders

    You could probably guess the syntax, but here’s an example:

    # the first argument is the named placeholder name - notice named
    # placeholders always start with a colon.
    $STH->bindParam(':name', $name);
    

    You can use a shortcut here as well, but it works with associative arrays. Here’s an example:

    # the data we want to insert
    $data = array( 'name' => 'Cathy', 'addr' => '9 Dark and Twisty', 'city' => 'Cardiff' );
    
    # the shortcut!
    $STH = $DBH->("INSERT INTO folks (name, addr, city) value (:name, :addr, :city)");
    $STH->execute($data);
    

    The keys of your array do not need to start with a colon, but otherwise need to match the named placeholders. If you have an array of arrays you can iterate over them, and simply call the execute with each array of data.

    Another nice feature of named placeholders is the ability to insert objects directly into your database, assuming the properties match the named fields. Here’s an example object, and how you’d perform your insert:

    # a simple object
    class person {
        public $name;
        public $addr;
        public $city;
    
        function __construct($n,$a,$c) {
            $this->name = $n;
            $this->addr = $a;
            $this->city = $c;
        }
        # etc ...
    }
    
    $cathy = new person('Cathy','9 Dark and Twisty','Cardiff');
    
    # here's the fun part:
    $STH = $DBH->("INSERT INTO folks (name, addr, city) value (:name, :addr, :city)");
    $STH->execute((array)$cathy);
    

    By casting the object to an array in the execute, the properties are treated as array keys.

    Selecting Data Fetch data into arrays or objects

    Data is obtained via the ->fetch(), a method of your statement handle. Before calling fetch, it’s best to tell PDO how you’d like the data to be fetched. You have the following options:

    • PDO::FETCH_ASSOC: returns an array indexed by column name
    • PDO::FETCH_BOTH (default): returns an array indexed by both column name and number
    • PDO::FETCH_BOUND: Assigns the values of your columns to the variables set with the ->bindColumn() method
    • PDO::FETCH_CLASS: Assigns the values of your columns to properties of the named class. It will create the properties if matching properties do not exist
    • PDO::FETCH_INTO: Updates an existing instance of the named class
    • PDO::FETCH_LAZY: Combines PDO::FETCH_BOTH/PDO::FETCH_OBJ, creating the object variable names as they are used
    • PDO::FETCH_NUM: returns an array indexed by column number
    • PDO::FETCH_OBJ: returns an anonymous object with property names that correspond to the column names

    In reality, there are three which will cover most situations: FETCH_ASSOC, FETCH_CLASS, and FETCH_OBJ. In order to set the fetch method, the following syntax is used:

    $STH->setFetchMode(PDO::FETCH_ASSOC);
    

    You can also set the fetch type directly within the ->fetch() method call.

    FETCH_ASSOC

    This fetch type creates an associative array, indexed by column name. This should be quite familiar to anyone who has used the mysql/mysqli extensions. Here’s an example of selecting data with this method:

    # using the shortcut ->query() method here since there are no variable
    # values in the select statement.
    $STH = $DBH->query('SELECT name, addr, city from folks');
    
    # setting the fetch mode
    $STH->setFetchMode(PDO::FETCH_ASSOC);
    
    while($row = $STH->fetch()) {
        echo $row['name'] . "\n";
        echo $row['addr'] . "\n";
        echo $row['city'] . "\n";
    }
    

    The while loop will continue to go through the result set one row at a time until complete.

    FETCH_OBJ

    This fetch type creates an object of std class for each row of fetched data. Here’s an example:

    # creating the statement
    $STH = $DBH->query('SELECT name, addr, city from folks');
    
    # setting the fetch mode
    $STH->setFetchMode(PDO::FETCH_OBJ);
    
    # showing the results
    while($row = $STH->fetch()) {
        echo $row->name . "\n";
        echo $row->addr . "\n";
        echo $row->city . "\n";
    }
    
    FETCH_CLASS

    The properties of your object are set BEFORE the constructor is called. This is important.

    This fetch method allows you to fetch data directly into a class of your choosing. When you use FETCH_CLASS, the properties of your object are set BEFORE the constructor is called. Read that again, it’s important. If properties matching the column names don’t exist, those properties will be created (as public) for you.

    This means if your data needs any transformation after it comes out of the database, it can be done automatically by your object as each object is created.

    As an example, imagine a situation where the address needs to be partially obscured for each record. We could do this by operating on that property in the constructor. Here’s an example:

    class secret_person {
        public $name;
        public $addr;
        public $city;
        public $other_data;
    
        function __construct($other = '') {
            $this->address = preg_replace('/[a-z]/', 'x', $this->address);
            $this->other_data = $other;
        }
    }
    

    As data is fetched into this class, the address has all its lowercase a-z letters replaced by the letter x. Now, using the class and having that data transform occur is completely transparent:

    $STH = $DBH->query('SELECT name, addr, city from folks');
    $STH->setFetchMode(PDO::FETCH_CLASS, 'secret_person');
    
    while($obj = $STH->fetch()) {
        echo $obj->addr;
    }
    

    If the address was ’5 Rosebud,’ you’d see ’5 Rxxxxxx’ as your output. Of course, there may be situations where you want the constructor called before the data is assigned. PDO has you covered for this, too.

    $STH->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'secret_person');
    

    Now, when you repeat the previous example with this fetch mode (PDO::FETCH_PROPS_LATE) the address will NOT be obscured, since the constructor was called and the properties were assigned.

    Finally, if you really need to, you can pass arguments to the constructor when fetching data into objects with PDO:

    $STH->setFetchMode(PDO::FETCH_CLASS, 'secret_person', array('stuff'));
    

    If you need to pass different data to the constructor for each object, you can set the fetch mode inside the fetch method:

    $i = 0;
    while($rowObj =  $STH->fetch(PDO::FETCH_CLASS, 'secret_person', array($i))) {
        // do stuff
        $i++
    }
    
    Some Other Helpful Methods

    While this isn’t meant to cover everything in PDO (it’s a huge extension!) there are a few more methods you’ll want to know in order to do basic things with PDO.

    $DBH->lastInsertId();
    

    The ->lastInsertId() method is always called on the database handle, not statement handle, and will return the auto incremented id of the last inserted row by that connection.

    $DBH->exec('DELETE FROM folks WHERE 1');
    $DBH->exec("SET time_zone = '-8:00'");
    

    The ->exec() method is used for operations that can not return data other then the affected rows. The above are two examples of using the exec method.

    $safe = $DBH->quote($unsafe);
    

    The ->quote() method quotes strings so they are safe to use in queries. This is your fallback if you’re not using prepared statements.

    $rows_affected = $STH->rowCount();
    

    The ->rowCount() method returns an integer indicating the number of rows affected by an operation. In at least one known version of PDO, according to [this bug report] [bugs.php.net] the method does not work with select statements. If you’re having this problem, and can’t upgrade PHP, you could get the number of rows with the following:

    $sql = "SELECT COUNT(*) FROM folks";
    if ($STH = $DBH->query($sql)) {
        # check the row count
        if ($STH->fetchColumn() > 0) {
    
        # issue a real select here, because there's data!
        }
        else {
            echo "No rows matched the query.";
        }
    }
    
    Conclusion

    I hope this helps some of you migrate away from the mysql and mysqli extensions. What do you think? Are there any of you out there who might make the switch?


  • Permalink for 'Meet Crockford’s JSDev'

    Meet Crockford’s JSDev

    Posted: January 24th, 2012, 10:29pm MST by Andrew Burgess

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

    Watch the Screencast Show Link Will you use JSDev?

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


  • Permalink for '.htaccess Files for the Rest of Us'

    .htaccess Files for the Rest of Us

    Posted: January 23rd, 2012, 5:37pm MST by Dan Wellman

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

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

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

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

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

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

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

    Redirects and URL Rewriting

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

    Redirections

    A redirection can be as simple as the following:

    Redirect 301 ^old\.html$ [localhost]  

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

    Rewrites

    A rewrite rule can be as simple as this:

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

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

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

    RewriteRule ^old\.html$ [hostname] [r=301]

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

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

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

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

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

    Serving Custom Error Pages

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

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

    ErrorDocument 404 "/404.html"

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

    Restricting Access to Specific Resources

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

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

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

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

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

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

    Block Access to Certain Entities

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

    order allow,deny
    deny from 192.168.0.1
    allow from all

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

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

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

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

    Force an IE Rendering Mode

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

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

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

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

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

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

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

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

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

    Enabling Compression

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

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

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

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

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

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

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

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

    Summary

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


  • Permalink for 'Testing your PHP Codebase with EnhancePHP'

    Testing your PHP Codebase with EnhancePHP

    Posted: January 20th, 2012, 9:51pm MST by Andrew Burgess

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

    Meet EnhancePHP

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

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

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

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

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

    Writing Tests

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

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

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

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

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

    So, the tests!

    Email Addresses

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

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

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

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

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

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

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

    Finally, we call the scenario’s verifyExpectations method.

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

    Running Tests

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

    <?php
    
    class Validation {
    	public function validate_email ($address) {
    
    	}
    }
    

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

    <?php
    
    require "vendor/EnhanceTestFramework.php";
    require "lib/validation.php";
    require "test/validation_test.php";
    
    \Enhance\Core::runTests();
    

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

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

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

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

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

    Getting the Tests to Pass

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

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

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

    Then, there’s the method:

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

    Now, we run the tests again, and:

    Writing More Tests

    Time for more tests:

    Usernames

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

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

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

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

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

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

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

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

    # At the top . . .
    public  $username_regex = '/^[\w\.]{4,20}$/';
    
    # and the method . . .
    public function validate_username ($username) {
    	return preg_match($this->username_regex, $username) == 1;
    }
    

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

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

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

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

    Phone Numbers

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

    public function validates_good_phonenumbers () {
    	$val_phonenumber = $this->get_scenario("validate_phonenumber");
    	$numbers = array("1234567890", "(890) 123-4567",
    		"123-456-7890", "123 456 7890", "(123) 456 7890");
    
    	foreach($numbers as $num) {
      		$val_phonenumber->with($num)->expect(true);
    	}
    	$val_phonenumber->verifyExpectations();
    }
    
    public function rejects_bad_phonenumnbers () {
    	$result = $this->val->validate_phonenumber("123456789012");
    	\Enhance\Assert::isFalse($result);
    }
    

    You can probably figure out the Validation method:

    public $phonenumber_regex = '/^\d{10}$|^(\(?\d{3}\)?[ |-]\d{3}[ |-]\d{4})$/';
    
    public function validate_phonenumber ($number) {
    	return preg_match($this->phonenumber_regex, $number) == 1;
    }
    

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

    Other Test Functionality

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

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

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

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

    Mocks

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

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

    <?php
    
    require "vendor/EnhanceTestFramework.php";
    
    class Counter {
      public $num = 0;
      public function increment ($num = 1) {
        $this->num = $this->num + $num;
        return $this->num;
      }
    }
    

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

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

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

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

    class ScoreboardTest extends \Enhance\TestFixture {
      public function score_home_calls_increment () {
        $home_counter_mock = \Enhance\MockFactory::createMock("Counter");
        $away_counter = new Counter();
    
        $home_counter_mock->addExpectation( \Enhance\Expect::method('increment') );
    
        $scoreboard = new Scoreboard($home_counter_mock, $away_counter);
        $scoreboard->score_home();
    
        $home_counter_mock->verifyExpectations();
      }
    }
    
    \Enhance\Core::runTests();
    

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

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

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

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

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

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

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

    Stubs

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

    class ScoreboardTest extends \Enhance\TestFixture {
      public function score_home_calls_increment () {
        $home_counter_stub = \Enhance\StubFactory::createStub("Counter");
        $away_counter = new Counter();
    
        $home_counter_stub->addExpectation( \Enhance\Expect::method('increment')->returns(10) );
    
        $scoreboard = new Scoreboard($home_counter_stub, $away_counter);
        $result = $scoreboard->score_home();
    
        \Enhance\Assert::areIdentical($result, 10);
    
      }
    }
    
    \Enhance\Core::runTests();
    

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

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

    Conclusion

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

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


  • Permalink for 'New Course: Introduction to Web Typography'

    New Course: Introduction to Web Typography

    Posted: January 19th, 2012, 4:24pm MST by Ian Yates

    Web typography is accessible to everyone. If you’ve ever built or designed a web page, you’ve almost definitely turned your hand to web typography of some sort. As a discipline, typography has been practiced for hundreds of years, and as a result there are many lessons and conventions we can learn from.

    Saying that, web typography is a bit like skiing. It’s unwise to just grab a couple of wooden planks and throw yourself down a black piste; you’ll develop bad habits and perhaps even break a bone. Before diving into your next web project, make sure you’ve at least considered the fundamentals.

    I can’t help you with skiing, but I can help you with web typography. If you’ve never looked properly into the subject, or even if you need a refresher, Introduction to Web Typography is for you!

    Free Preview Lessons Overview

    As with all Tuts+ Premium courses, we’ll start at the beginning, working through the basics and some terminology, before moving on to the practicalities. During the process we’ll build ourselves a demo web page which will highlight the theory we cover. Even if you’re not yet confident with HTML and CSS, each video comes with source files stepping off from where the previous video ended.

    Take a look at the episodes listed below and be sure to check out the preview videos even if you don’t yet have a Premium subscription.

    Lesson Overview
    This course comprises 11 helpful videos.

    As with all Tuts+ Premium courses, each lesson has an accompanying forum where you can discuss ideas and questions which arise as you watch the videos.

    Course Forum
    Get involved with the forum, where you can discuss each lesson. Tuts+ Premium

    The recently re-launched Tuts+ Premium is a service that provides top-tier training in a variety of creative fields. Whether you prefer books, visual training, or in depth tutorials, we have you covered. While we unfortunately can’t afford to provide the service for free, it’s only $19 a month – less than you’d spend on dinner.

    I hope you’ll consider checking it out! In addition to learning a huge variety of new skills, it’s also a fantastic way to say thank you to Nettuts+.


  • Permalink for 'From jQuery to JavaScript: A Reference'

    From jQuery to JavaScript: A Reference

    Posted: January 19th, 2012, 1:58pm MST by Jeffrey Way

    Whether we like it or not, more and more developers are being introduced to the world of JavaScript through jQuery first. In many ways, these newcomers are the lucky ones. They have access to a plethora of new JavaScript APIs, which make the process of DOM traversal (something that many folks depend on jQuery for) considerably easier. Unfortunately, they don’t know about these APIs!

    In this article, we’ll take a variety of common jQuery tasks, and convert them to both modern and legacy JavaScript.

    Modern vs. Legacy – For each item in the list below, you’ll find the modern, “cool kids” way to accomplish the task, and the legacy, “make old browsers happy” version. The choice you choose for your own projects will largely depend on your visitors.

    Before We Begin

    Please note that some of the legacy examples in this article will make use of a simple, cross-browser, addEvent function. This function will simply ensure that both the W3C-recommended event model, addEventListener, and Internet Explorer’s legacy attachEvent are normalized.

    So, when I refer to addEvent(els, event, handler) in the legacy code snippets below, the following function is being referenced.

    var addEvent = (function () {
    	var filter = function(el, type, fn) {
    		for ( var i = 0, len = el.length; i < len; i++ ) {
    			addEvent(el[i], type, fn);
    		}
    	};
    	if ( document.addEventListener ) {
    		return function (el, type, fn) {
    			if ( el && el.nodeName || el === window ) {
    				el.addEventListener(type, fn, false);
    			} else if (el && el.length) {
    				filter(el, type, fn);
    			}
    		};
    	}
    
    	return function (el, type, fn) {
    		if ( el && el.nodeName || el === window ) {
    			el.attachEvent('on' + type, function () { return fn.call(el, window.event); });
    		} else if ( el && el.length ) {
    			filter(el, type, fn);
    		}
    	};
    })();
    
    // usage
    addEvent( document.getElementsByTagName('a'), 'click', fn);
    
    1 – $('#container');

    This function call will query the DOM for the element with an id of container, and create a new jQuery object.

    Modern JavaScript
    var container = document.querySelector('#container');
    

    querySelector is part of the Selectors API, which provides us with the ability to query the DOM using the CSS selectors that we’re already familiar with.

    This particular method will return the first element that matches the passed selector.

    Legacy
    var container = document.getElementById('container');
    

    Pay special attention to how you reference the element. When using getElementById, you pass the value alone, while, with querySelector, a CSS selector is expected.

    2 – $('#container').find('li');

    This time, we’re not hunting for a single element; instead, we’re capturing any number of list items that are descendants of #container.

    Modern JavaScript
    var lis = document.querySelectorAll('#container li');
    

    querySelectorAll will return all elements that match the specified CSS selector.

    Selector Limitations

    While nearly all relevant browsers support the Selectors API, the specific CSS selectors you pass are still limited to the capability of the browser. Translation: Internet Explorer 8 will only support CSS 2.1 selectors.

    Legacy
    var lis = document.getElementById('container').getElementsByTagName('li');
    
    3 – $('a').on('click', fn);

    In this example, we’re attaching a click event listener to all anchor tags on the page.

    Modern JavaScript
    [].forEach.call( document.querySelectorAll('a'), function(el) {
       el.addEventListener('click', function() {
         // anchor was clicked
      }, false);
    
    });
    

    The above snippet looks scary, but it’s not too bad. Because querySelectorAll returns a static NodeList rather than an Array, we can’t directly access methods, like forEach. This is remedied by calling forEach on the Array object, and passing the the results of querySelectorAll as this.

    Legacy
    var anchors = document.getElementsbyTagName('a');
    addEvent(anchors, 'click', fn);
    
    4 – $('ul').on('click', 'a', fn);

    Ahh – this example is slightly different. This time, the jQuery snippet is using event delegation. The click listener is being applied to all unordered lists, however, the callback function will only fire if the target (what the user specifically clicked on) is an anchor tag.

    Modern JavaScript
    document.addEventListener('click', function(e) {
       if ( e.target.matchesSelector('ul a') ) {
          // proceed
       }
    }, false);
    

    Technically, this vanilla JavaScript method isn’t the same as the jQuery example. Instead, it’s attaching the event listener directly to the document. It then uses the new matchesSelector method to determine if the target – the node that was clicked – matches the provided selector. This way, we’re attaching a single event listener, rather than many.

    Please note that, at the time of this writing, all browsers implement matchesSelector via their own respective prefixes: mozMatchesSelector, webkitMatchesSelector, etc. To normalize the method, one might write:

    var matches;
    
    (function(doc) {
       matches =
          doc.matchesSelector ||
          doc.webkitMatchesSelector ||
          doc.mozMatchesSelector ||
          doc.oMatchesSelector ||
          doc.msMatchesSelector;
    })(document.documentElement);
    
    document.addEventListener('click', function(e) {
       if ( matches.call( e.target, 'ul a') ) {
          // proceed
       }
    }, false);
    

    With this technique, in Webkit, matches will refer to webkitMatchesSelector, and, in Mozilla, mozMatchesSelector.

    Legacy
    var uls = document.getElementsByTagName('ul');
    
    addEvent(uls, 'click', function() {
       var target = e.target || e.srcElement;
       if ( target && target.nodeName === 'A' ) {
          // proceed
       }
    });
    

    As a fallback, we determine if the nodeName property (the name of the target element) is equal to our desired query. Pay special attention to the fact that older versions of Internet Explorer sometimes plays by their own rules – sort of like the kid who eats play-doh during lunch time. You won’t be able to access target directly from the event object. Instead, you’ll want to look for event.srcElement.

    5 - $('#box').addClass('wrap');

    jQuery provides a helpful API for modifying class names on a set of elements.

    Modern JavaScript
    document.querySelector('#box').classList.add('wrap');
    

    This new technique uses the new classList API to add, remove, and toggle class names.

    var container = document.querySelector('#box');
    
    container.classList.add('wrap');
    container.classList.remove('wrap');
    container.classList.toggle('wrap');
    
    Legacy
    var box = document.getElementById('box'),
    
        hasClass = function (el, cl) {
            var regex = new RegExp('(?:\\s|^)' + cl + '(?:\\s|$)');
            return !!el.className.match(regex);
        },
    
        addClass = function (el, cl) {
            el.className += ' ' + cl;
        },
    
        removeClass = function (el, cl) {
            var regex = new RegExp('(?:\\s|^)' + cl + '(?:\\s|$)');
            el.className = el.className.replace(regex, ' ');
        },
    
        toggleClass = function (el, cl) {
            hasClass(el, cl) ? removeClass(el, cl) : addClass(el, cl);
    
        };
    
    addClass(box, 'drago');
    removeClass(box, 'drago');
    toggleClass(box, 'drago'); // if the element does not have a class of 'drago', add one.
    

    The fallback technique requires just a tad more work, ay?

    6 - $('#list').next();

    jQuery’s next method will return the element that immediately follows the current element in the wrapped set.

    Modern JavaScript
    var next = document.querySelector('#list').nextElementSibling; // IE9
    

    nextElementSibling will refer specifically to the next element node, rather than any node (text, comment, element). Unfortunately, Internet Explorer 8 and below do not support it.

    Legacy
    var list = document.getElementById('list'),
    	next = list.nextSibling;
    
    // we want the next element node...not text.
    while ( next.nodeType > 1 ) next = next.nextSibling;
    

    There’s a couple ways to write this. In this example, we’re detecting the nodeType of the node that follows the specified element. It could be text, element, or even a comment. As we specifically need the next element, we desire a nodeType of 1. If next.nodeType returns a number greater than 1, we should skip it and keep going, as it’s probably a text node.

    7 - $('<div id=box></div>').appendTo('body');

    In addition to querying the DOM, jQuery also offers the ability to create and inject elements.

    Modern JavaScript
    var div = document.createElement('div');
    div.id = 'box';
    document.body.appendChild(div);
    

    There’s nothing modern about this example; it’s how we’ve accomplished the process of creating and injecting elements into the DOM for a long, long time.

    You’ll likely need to add content to the element, in which case you can either use innerHTML, or createTextNode.

    div.appendChild( document.createTextNode('wacka wacka') );
    
    // or
    
    div.innerHTML = 'wacka wacka';
    
    8 – $(document).ready(fn)

    jQuery’s document.ready method is incredibly convenient. It allows us to begin executing code as soon as possible after the DOM has been loaded.

    Modern JavaScript
    document.addEventListener('DOMContentLoaded', function() {
       // have fun
    });
    

    Standardized as part of HTML5, the DOMContentLoaded event will fire as soon as the document has been completed parsed.

    Legacy
    // [dustindiaz.com] function ready(cb) {
    	/in/.test(document.readyState) // in = loadINg
    		? setTimeout('ready('+cb+')', 9)
    		: cb();
    }
    
    ready(function() {
       // grab something from the DOM
    });
    

    The fallback solution, every nine milliseconds, will detect the value of document.readyState. If “loading” is returned, the document hasn’t yet been fully parsed (/in/.test(). Once it has, though, document.readyState will equal “complete,” at which point the user’s callback function is executed.

    9 – $('.box').css('color', 'red');

    If possible, always add a class to an element, when you need to provide special styling. However, sometimes, the styling will be determined dynamically, in which case it needs to be inserted as an attribute.

    Modern JavaScript
    [].forEach.call( document.querySelectorAll('.box'), function(el) {
      el.style.color = 'red'; // or add a class
    });
    

    Once again, we’re using the [].forEach.call() technique to filter through all of the elements with a class of box, and make them red, via the style object.

    Legacy
    var box = document.getElementsByClassName('box'), // refer to example #10 below for a cross-browser solution
       i = box.length;
     
    while ( i-- > 0 && (box[i].style.color = 'red') );
    

    This time, we’re getting a bit tricky with the while loop. Yes, it’s a bit snarky, isn’t it? Essentially, we’re mimicking:

    var i = 0, len;
    
    for ( len = box.length; i < len; i++ ) {
       box[i].style.color = 'red';
    }
    

    However, as we only need to perform a single action, we can save a couple lines. Note that readability is far more important than saving two lines – hence my “snarky” reference. Nonetheless, it’s always fun to see how condensed you can make your loops. We’re developers; we do this sort of stuff for fun! Anyhow, feel free to stick with the for statement version.

    10 – $()

    Clearly, our intention is not to replicate the entire jQuery API. Typically, for non-jQuery projects, the $ or $$ function is used as shorthand for retrieving one or more elements from the DOM.

    Modern JavaScript
    var $ = function(el) {
    	return document.querySelectorAll(el);
    };
    // Usage = $('.box');
    

    Notice that $ is simply a one-character pointer to document.querySelector. It saves time!

    Legacy
    if ( !document.getElementsByClassName ) {
    	document.getElementsByClassName = function(cl, tag) {
    	   var els, matches = [],
    	      i = 0, len,
    	      regex = new RegExp('(?:\\s|^)' + cl + '(?:\\s|$)');
    	 
    	   // If no tag name is specified,
    	   // we have to grab EVERY element from the DOM	 
    	   els = document.getElementsByTagName(tag || "*");
    	   if ( !els[0] ) return false;
    
    	   for ( len = els.length; i < len; i++ ) {
    	      if ( els[i].className.match(regex) ) {
    	         matches.push( els[i]);
    	      }
    	   }
    	   return matches; // an array of elements that have the desired classname
    	};
    }
     
    // Very simple implementation. We're only checking for an id, class, or tag name.
    // Does not accept CSS selectors in pre-querySelector browsers.
    var $ = function(el, tag) {
       var firstChar = el.charAt(0);
     
       if ( document.querySelectorAll ) return document.querySelectorAll(el);
     
       switch ( firstChar ) {
          case "#":
             return document.getElementById( el.slice(1) );
          case ".":
             return document.getElementsByClassName( el.slice(1), tag );
          default:
             return document.getElementsByTagName(el);
       }
    };
    
    // Usage
    $('#container');
    $('.box'); // any element with a class of box
    $('.box', 'div'); // look for divs with a class of box
    $('p'); // get all p elements
    

    Unfortunately, the legacy method isn’t quite so minimal. Honestly, at this point, you should use a library. jQuery is highly optimized for working with the DOM, which is why it’s so popular! The example above will certainly work, however, it doesn’t support complex CSS selectors in older browsers; that task is just a wee-bit more complicated!

    Summary

    It’s important for me to note that that I’m not encouraging you to abandon jQuery. I use it in nearly all of my projects. That said, don’t always be willing to embrace abstractions without taking a bit of time to research the underlying code.

    I’d like this posting to serve as a living document, of sorts. If you have any of your own (or improvements/clarifications for my examples), leave a comment below, and I’ll sporadically update this posting with new items. Bookmark this page now! Lastly, I’d like to send a hat-tip to this set of examples, which served as the impetus for this post.


  • Permalink for 'Digging into Dojo: Premium Video Series'

    Digging into Dojo: Premium Video Series

    Posted: January 18th, 2012, 12:33pm MST by Andrew Burgess

    If you prefer the written word, we have a fantastic session on working with Dojo Toolkit, created by Andrew Burgess. However, for the visual learners among us, I also asked him to prepare a series of screencasts for the series as well. I’m pleased to announce that, today, we’ve released these videos exclusively to our Tuts+ Premium members.

    Become a Premium member to read this tutorial/screencast, as well as hundreds of other advanced tutorials and screencasts from the Tuts+ network.

    Maybe you saw that tweet: “jQuery is a gateway drug. It leads to full-on JavaScript usage.” Part of that addiction, I contend, is learning other JavaScript frameworks. And that’s what this four-part screencast series on the incredible Dojo Toolkit is all about: taking you to the next level of your JavaScript addiction.

    Tuts+ Premium

    The recently re-launched Tuts+ Premium is a service that provides top-tier training in a variety of creative fields. Whether you prefer books, visual training, or in depth tutorials, we have you covered. While we unfortunately can’t afford to provide the service for free, it’s only $19 a month – less than you’d spend on dinner.

    I hope you’ll consider checking it out! In addition to learning a huge variety of new skills, it’s also a fantastic way to say thank you to Nettuts+.


  • Permalink for 'The Principles of Web API Usage'

    The Principles of Web API Usage

    Posted: January 17th, 2012, 5:39pm MST by Janet Wagner

    Not too long ago, I wrote an article about “The Increasing Importance of APIs in Web Development.” As a follow-up, today, I’ll cover the basics of using Web APIs.

    Before we begin: this article does not detail the process of API design or development. That’s for a different article!

    Basic Principles

    There are a handful of basic principles that should be followed when using Web APIs:

    • Build applications that are social and engaging
    • Give users choice and control whenever applicable
    • Don’t surprise, mislead or confuse users
    • Don’t create or distribute spam; always encourage genuine communication
    • Respect the user’s privacy
    • Be a good partner to Web API providers

    Most of these guidelines are listed in the API “terms of service” for Twitter and Facebook, but can be applied to all Web APIs.

    Evaluate Your Coding Skills

    There are thousands of Web APIs available and most can be either integrated into a website, or to create a mashup. Some Web APIs are fairly simple and require minimal coding skills to implement, while others can be extremely complex and require advanced programming skills.

    The programming language you use to integrate a Web API into your website certainly depends on which ones you’re most comfortable with. You’ll find that many Web APIs, such as Flickr and Last.fm offer language specific toolkits.

    Read the Terms and Conditions

    Every Web API has specific terms regarding its usage; so it’s incredibly important that the “terms and conditions” are read carefully. They will detail many aspects of Web API usage, including:

    • Copyright Infringement
    • Logo Identity, Branding & Trademarks
    • Content Usage & Guidelines
    • General Restrictions
    • Usage Limitations
    • Use of cache files
    • Privacy Policy

    There may be additional “terms of use” information located on separate web pages. For example, there are “Display Guidelines” described in detail on separate web pages for Twitter, Foursquare, LinkedIn and Facebook.

    Read the Documentation

    Most Web APIs have detailed documentation available, which usually contains important information such as:

    • Features list
    • Available data formats
    • How to request an API key
    • How to use authentication (OAuth)
    • Examples of API calls & data requests
    • Tutorials and sample code
    • API reference page
    Use the Latest Version / Versioning

    Some Web API Providers recommend the use of a versioning parameter in the API call.

    Many Web API providers frequently release new versions of their APIs. These new releases may include the following:

    • Added functionality
    • Increased speed
    • Improved stability
    • Improved accuracy
    • Bug fixes

    Some Web API Providers recommend the use of a versioning parameter in the API call. Foursquare for example, accepts the param “v=YYYYMMDD” in API calls. This parameter will help indicate that the client is up to date as of the specified date.

    Periodically Check the Change Log

    It is a smart idea to periodically check the change log (if one exists) when using Web APIs. Many popular APIs have change logs available, such as Facebook, Google Maps, Google Charts and Foursquare.

    Plenty of API providers offer additional ways to keep track of their API revisions:

    • Subscribing to the API Developer blog
    • Following the API on Twitter
    • Joining an API User Group
    • Subscribing to an API email newsletter
    Usage Limits

    Nearly all web APIs are subject to rate limits; some API providers even charge fees if a user exceeds the API rate limit!

    Usage of most (if not all) APIs is subject to rate limits and each API provider has its own API rate limiting policy. Some API providers even charge fees if a user exceeds the API rate limit! Google recently introduced a new rate limiting policy for the Maps API which includes usage fees. Google has also provided additional details regarding the Maps API usage limits on their Geo Developers Blog. Here are links to rate limiting information for a few of the more popular APIs:

    It’s incredibly important that you not abuse the API. If you’re website is making an API call for every single page load, and for every single visitor, ask yourself, “Why”? Implement proper caching techniques to improve your website’s performance, and potentially save money.

    Caching Data

    Using a “cache file” will prevent problems with API Rate Limiting.

    Using a “cache file” will prevent problems with API Rate Limiting. In the Nettuts+ post “How to Create an Advanced Twitter Widget,”, there are instructions on how to create a PHP “cache file” script. This script retrieves the Twitter API “GET statuses/user_timeline” information and stores it in a “TXT” file located in a cache directory on the server. This script can be easily modified to work with most APIs. All you would have to do is change the txt file name and the API call. Note that the call in the script retrieves the data in JSON format.

    It is important that you read the APIs “terms of use” for any reference to using cache files. For example, the Amazon Product Advertising API has restrictions on caching. Facebook recommends that if you use caching you should try to keep the data up to date.

    Data Formats

    The two most popular data formats for Web APIs are XML and JSON.

    The two most popular data formats for Web APIs are XML and JSON; many providers offer both formats. However, JSON has become so popular among web developers to the point that some API providers, such as Foursquare, Twitter and Google+ offer the JSON data format exclusively.

    API data formats are covered in detail in a previous post.

    Sign-up for the API

    Most API providers require users to sign up for a user account and/or an API Key. For example, Google asks its users to request an API key here. This is usually a fairly simple process and should only take a few minutes to do. You may also be asked to use a developer/application ID when using an API.

    OAuth Token

    Many APIs require the use of OAuth for specific API functionality.

    OAuth (Open Authorization) is an open standard for authorization that allows users to share data and/or files stored on one website with another website.

    Many APIs require the use of OAuth for specific API functionality, such as logging in and out of an application. The Google+ API requires ALL API calls to use an OAuth 2.0 token or an API key. Google recommends using OAuth 2.0 as the authorization protocol for Google APIs. Other examples of APIs that require the use of OAuth are LinkedIn, Twitter and Foursquare.

    API Calls

    An API “call” needs to be used in order for your website application to access a Web API. Depending on the type of application you are creating, you may need to use multiple API calls. Most APIs can be used with a variety of programming languages. The call may need to be modified for different programming languages. For example, in the tutorial, “How to Create an Advanced Twitter Widget”, a PHP “cache file” script is created using the following Twitter API call:

     [api.twitter.com] 

    If you’re using JavaScript or jQuery instead of PHP, the call will need to be changed to:

     [api.twitter.com] 

    When using JavaScript or jQuery, “&callback=?” needs to be included in the API call, but if using PHP, it needs to be removed or the data will not be generated in a valid JSON format.

    Test the API Call

    There are several API testing tools available to help you test your API calls:

    Platform Status

    If you are having unexpected problems with an API, some API providers like Foursquare and Twitter offer platform status updates on status blogs.

    Facebook offers a nice “Live Status Tool” that includes:

    • Current platform status
    • Issue history
    • Average API response time chart
    • Error count chart

    Twitter also has an up to date “API Status Page” that includes:

    • Known hot issues
    • Recently closed issues
    • Live Current Performance and Availability Status
    • Performance and Availability History
    Conclusion

    Web APIs are becoming increasingly important in web development, and their popularity and usage has increased exponentially in the past few years. Hopefully, this article has detailed the basics of using Web APIs. If there are additional notes that I have not included, please mention them in the comments.


  • Permalink for 'Nettuts+ Quiz #9: The Absolute Basics of PHP'

    Nettuts+ Quiz #9: The Absolute Basics of PHP

    Posted: January 16th, 2012, 10:00am MST by Siddharth

    In 2012, we plan to take our quizzes to a whole new level with ones aimed at all languages and catering to all competencies and tastes. But what better language to start off the new year than PHP, the darling of the masses?

    In this test, aimed at beginners, your knowledge of the absolute basics of PHP will be tested. Yes, we know PHP is a bit old school but it still powers a massive portion of the web and is a force to be reckoned with. And don’t get complacent with the difficulty level of this test either! More difficult ones are on the way — we just like to take it nice and slow. Or maybe we like lulling you into a false sense of security…



    $(document).ready(function(){ $('#quiz-container').jquizzy({ questions: init.questions, resultComments: init.resultComments, twitterStatus: 'Woo! I scored {score} on the Nettuts quiz about the basics of PHP. Give it a shot!', twitterImage: 'http://d2o0t5hpnwv4c1.cloudfront.net/jquizzy-1.0/img/share.png', twitterUsername: 'envatowebdev', splashImage: 'http://d2o0t5hpnwv4c1.cloudfront.net/1123_quiz9/splash.png' }); });


  • Permalink for 'Test-Driven JavaScript Development in Practice'

    Test-Driven JavaScript Development in Practice

    Posted: January 14th, 2012, 7:00am MST by Christian Johansen

    TDD is an iterative development process where each iteration starts by writing a test which forms a part of the specification we are implementing. The short iterations allow for more instant feedback on the code we are writing, and bad design decisions are easier to catch. By writing the tests prior to any production code, good unit test coverage comes with the territory, but that is merely a welcome side-effect.

    November of 2010 Turning Development Upside-Down

    In traditional programming, problems are solved by programming until a concept is fully represented in code. Ideally, the code follows some overall architectural design considerations, although in many cases, perhaps especially in the world of JavaScript, this is not the case. This style of programming solves problems by guessing at what code is required to solve them, a strategy that can easily lead to bloated and tightly coupled solutions. If there are no unit tests as well, solutions produced with this approach may even contain code that is never executed, such as error handling logic and “flexible” argument handling, or it may contain edge cases that have not been thoroughly tested, if tested at all.

    Test-driven development turns the development cycle upside-down. Rather than focusing on what code is required to solve a problem, test-driven development starts by defining the goal. Unit tests forms both the specification and documentation for what actions are supported and accounted for. Granted, the goal of TDD is not testing and so there is no guarantee that it handles e.g. edge cases better. However, because each line of code is tested by a representative piece of sample code, TDD is likely to produce less excess code, and the functionality that is accounted for is likely to be more robust. Proper test-driven development ensures that a system will never contain code that is not being executed.

    The Process

    The test-driven development process is an iterative process where each iteration consists of the following four steps:

    • Write a test
    • Run tests, watch the new test fail
    • Make the test pass
    • Refactor to remove duplication

    In each iteration, the test is the specification. Once enough production code (and no more) has been written to make the test pass, we are done, and we may refactor the code to remove duplication and/or improve the design, as long as the tests still pass.

    Practical TDD: The Observer Pattern

    The Observer pattern (also known as Publish/Subscribe, or simply pubsub) is a design pattern that allows us to observe the state of an object and be notified when it changes. The pattern can provide objects with powerful extension points while maintaining loose coupling.

    There are two roles in The Observer – observable and observer. The observer is an object or function that will be notified when the state of the observable changes. The observable decides when to update its observers and what data to provide them with. The observable typically provides at least two public methods: pubsub, which notifies its observers of new data, and pubsub which subscribes observers to events.

    The Observable Library

    Test-driven development allows us to move in very small steps when needed. In this first real-world example we will start out with the tiniest of steps. As we gain confidence in our code and the process, we will gradually increase the size of our steps when circumstances allow it (i.e., the code to implement is trivial enough). Writing code in small frequent iterations will help us design our API piece-by-piece as well as help us make fewer mistakes. When mistakes occur, we will be able to fix them quickly as errors will be easy to track down when we run tests every time we add a handful lines of code.

    Setting up the Environment

    This example uses JsTestDriver to run tests. A setup guide is available from the official web site.

    The initial project layout looks as follows:

    chris@laptop:~/projects/observable $ tree
    .
    |-- jsTestDriver.conf
    |-- src
    |   `-- observable.js
    `-- test
        `-- observable_test.js
    

    The configuration file is just the minimal JsTestDriver configuration:

    server: [localhost:4224] 
    load:
      - lib/*.js
      - test/*.js
    
    Adding Observers

    We will kick off the project by implementing a means to add observers to an object. Doing so will take us through writing the first test, watching it fail, passing it in the dirtiest possible way and finally refactoring it into something more sensible.

    The First Test

    The first test will attempt to add an observer by calling the addObserver method. To verify that this works, we will be blunt and assume that observable stores its observers in an array and check that the observer is the only item in that array. The test belongs in test/observable_test.js and looks like the following:

    TestCase("ObservableAddObserverTest", {
      "test should store function": function () {
        var observable = new tddjs.Observable();
        var observer = function () {};
    
        observable.addObserver(observer);
    
        assertEquals(observer, observable.observers[0]);
      }
    });
    
    Running the Test and Watching it Fail

    At first glance, the result of running our very first test is devastating:

    Total 1 tests (Passed: 0; Fails: 0; Errors: 1) (0.00 ms)
      Firefox 3.6.12 Linux: Run 1 tests (Passed: 0; Fails: 0; Errors 1) (0.00 ms)
        ObservableAddObserverTest.test should store function error (0.00 ms): \
    tddjs is not defined
          /test/observable_test.js:3
    
    Tests failed.
    
    Making the Test Pass

    Fear not! Failure is actually a good thing: It tells us where to focus our efforts. The first serious problem is that tddjs doesn’t exist. Let’s add the namespace object in src/observable.js:

    var tddjs = {};
    

    Running the tests again yields a new error:

    E
    Total 1 tests (Passed: 0; Fails: 0; Errors: 1) (0.00 ms)
      Firefox 3.6.12 Linux: Run 1 tests (Passed: 0; Fails: 0; Errors 1) (0.00 ms)
        ObservableAddObserverTest.test should store function error (0.00 ms): \
    tddjs.Observable is not a constructor
          /test/observable_test.js:3
    
    Tests failed.
    

    We can fix this new issue by adding an empty Observable constructor:

    var tddjs = {};
    
    (function () {
      function Observable() {}
    
      tddjs.Observable = Observable;
    }());
    

    Running the test once again brings us directly to the next problem:

    E
    Total 1 tests (Passed: 0; Fails: 0; Errors: 1) (0.00 ms)
      Firefox 3.6.12 Linux: Run 1 tests (Passed: 0; Fails: 0; Errors 1) (0.00 ms)
        ObservableAddObserverTest.test should store function error (0.00 ms): \
     observable.addObserver is not a function
          /test/observable_test.js:6
    
    Tests failed.
    

    Let’s add the missing method.

    function addObserver() {}
    
    Observable.prototype.addObserver = addObserver;
    

    With the method in place the test now fails in place of a missing observers array.

    E
    Total 1 tests (Passed: 0; Fails: 0; Errors: 1) (0.00 ms)
      Firefox 3.6.12 Linux: Run 1 tests (Passed: 0; Fails: 0; Errors 1) (0.00 ms)
        ObservableAddObserverTest.test should store function error (0.00 ms): \
    observable.observers is undefined
          /test/observable_test.js:8
    
    Tests failed.
    

    As odd as it may seem, I will now define the observers array inside the pubsub method. When a test fails, TDD instructs us to do the simplest thing that could possibly work, no matter how dirty it feels. We will get the chance to review our work once the test is passing.

    function addObserver(observer) {
      this.observers = [observer];
    }
    
    Success! The test now passes:
    
    .
    Total 1 tests (Passed: 1; Fails: 0; Errors: 0) (1.00 ms)
      Firefox 3.6.12 Linux: Run 1 tests (Passed: 1; Fails: 0; Errors 0) (1.00 ms)
    
    Refactoring

    While developing the current solution we have taken the quickest possible route to a passing test. Now that the bar is green we can review the solution and perform any refactoring we deem necessary. The only rule in this last step is to keep the bar green. This means we will have to refactor in tiny steps as well, making sure we don’t accidentally break anything.

    The current implementation has two issues we should deal with. The test makes detailed assumptions about the implementation of Observable and the addObserver implementation is hard-coded to our test.

    We will address the hard-coding first. To expose the hard-coded solution, we will augment the test to make it add two observers instead of one.

    "test should store function": function () {
      var observable = new tddjs.Observable();
      var observers = [function () {}, function () {}];
    
      observable.addObserver(observers[0]);
      observable.addObserver(observers[1]);
    
      assertEquals(observers, observable.observers);
    }
    

    As expected, the test now fails. The test expects that functions added as observers should stack up like any element added to an pubsub. To achieve this, we will move the array instantiation into the constructor and simply delegate addObserver to the array method push:

    function Observable() {
      this.observers = [];
    }
    
    function addObserver(observer) {
      this.observers.push(observer);
    }
    

    With this implementation in place the test passes again, proving that we have taken care of the hard-coded solution. However, the issue of accessing a public property and making wild assumptions about the implementation of Observable is still an issue. An observable pubsub should be observable by any number of objects, but it is of no interest to outsiders how or where the observable stores them. Ideally, we would like to be able to check with the observable if a certain observer is registered without groping around its insides. We make a note of the smell and move on. Later, we will come back to improve this test.

    Checking for Observers

    We will add another method to Observable, hasObserver, and use it to remove some of the clutter we added when implementing addObserver.

    The Test

    A new method starts with a new test, and the next one desired behavior for the hasObserver method.

    TestCase("ObservableHasObserverTest", {
      "test should return true when has observer": function () {
        var observable = new tddjs.Observable();
        var observer = function () {};
    
        observable.addObserver(observer);
    
        assertTrue(observable.hasObserver(observer));
      }
    });
    

    We expect this test to fail in the face of a missing hasObserver, which it does.

    Making the Test Pass

    Again, we employ the simplest solution that could possibly pass the current test:

    function hasObserver(observer) {
      return true;
    }
    
    Observable.prototype.hasObserver = hasObserver;
    

    Even though we know this won’t solve our problems in the long run, it keeps the tests green. Trying to review and refactor leaves us empty-handed as there are no obvious points where we can improve. The tests are our requirements, and currently they only require hasObserver to return true. To fix that we will introduce another test that expects hasObserver to return false for a non-existent observer, which can help force the real solution.

    "test should return false when no observers": function () {
      var observable = new tddjs.Observable();
    
      assertFalse(observable.hasObserver(function () {}));
    }
    

    This test fails miserably, given that hasObserver always returns true, forcing us to produce the real implementation. Checking if an observer is registered is a simple matter of checking that the this.observers array contains the object originally passed to addObserver:

    function hasObserver(observer) {
      return this.observers.indexOf(observer) >= 0;
    }
    

    The Array.prototype.indexOf method returns a number less than 0 if the element is not present in the array, so checking that it returns a number equal to or greater than 0 will tell us if the observer exists.

    Solving Browser Incompatibilities

    Running the test in more than one browser produces somewhat surprising results:

    chris@laptop:~/projects/observable$ jstestdriver --tests all
    ...E
    Total 4 tests (Passed: 3; Fails: 0; Errors: 1) (11.00 ms)
      Firefox 3.6.12 Linux: Run 2 tests (Passed: 2; Fails: 0; Errors 0) (2.00 ms)
      Microsoft Internet Explorer 6.0 Windows: Run 2 tests \
    (Passed: 1; Fails: 0; Errors 1) (0.00 ms)
        ObservableHasObserverTest.test should return true when has observer error \
    (0.00 ms): Object doesn't support this property or method
    
    Tests failed.
    

    Internet Explorer versions 6 and 7 failed the test with their most generic of error messages: “Object doesn't support this property or method". This can indicate any number of issues:

    • we are calling a method on an object that is null
    • we are calling a method that does not exist
    • we are accessing a property that doesn’t exist

    Luckily, TDD-ing in tiny steps, we know that the error has to relate to the recently added call to indexOf on our observers array. As it turns out, IE 6 and 7 do not support the JavaScript 1.6 method Array.prototype.indexOf (for which we cannot really blame it, it was only recently standardized with ECMAScript 5, December 2009). At this point, we have three options:

    • Circumvent the use of Array.prototype.indexOf in hasObserver, effectively duplicating native functionality in supporting browsers.
    • Implement Array.prototype.indexOf for non-supporting browsers. Alternatively implement a helper function that provides the same functionality.
    • Use a third-party library which provides either the missing method, or a similar method.

    Which one of these approaches is best suited to solve a given problem will depend on the situation – they all have their pros and cons. In the interest of keeping Observable self-contained, we will simply implement hasObserver in terms of a loop in place of the indexOf call, effectively working around the problem. Incidentally, that also seems to be the simplest thing that could possibly work at this point. Should we run into a similar situation later on, we would be advised to reconsider our decision. The updated hasObserver looks as follows:

    function hasObserver(observer) {
      for (var i = 0, l = this.observers.length; i 
    
     Refactoring  
    

    With the bar back to green, it's time to review our progress. We now have three tests, but two of them seem strangely similar. The first test we wrote to verify the correctness of addObserver basically tests for the same things as the test we wrote to verify Refactoring . There are two key differences between the two tests: The first test has previously been declared smelly, as it directly accesses the observers array inside the observable object. The first test adds two observers, ensuring they're both added. We can now join the tests into one that verifies that all observers added to the observable are actually added:

    "test should store functions": function () {
      var observable = new tddjs.Observable();
      var observers = [function () {}, function () {}];
    
      observable.addObserver(observers[0]);
      observable.addObserver(observers[1]);
    
      assertTrue(observable.hasObserver(observers[0]));
      assertTrue(observable.hasObserver(observers[1]));
    }
    
    Notifying Observers

    Adding observers and checking for their existence is nice, but without the ability to notify them of interesting changes, Observable isn't very useful. It's time to implement the notify method.

    Ensuring That Observers Are Called

    The most important task notify performs is calling all the observers. To do this, we need some way to verify that an observer has been called after the fact. To verify that a function has been called, we can set a property on the function when it is called. To verify the test we can check if the property is set. The following test uses this concept in the first test for notify.

    TestCase("ObservableNotifyTest", {
      "test should call all observers": function () {
        var observable = new tddjs.Observable();
        var observer1 = function () { observer1.called = true; };
        var observer2 = function () { observer2.called = true; };
    
        observable.addObserver(observer1);
        observable.addObserver(observer2);
        observable.notify();
    
        assertTrue(observer1.called);
        assertTrue(observer2.called);
      }
    });
    

    To pass the test we need to loop the observers array and call each function:

    function notify() {
      for (var i = 0, l = this.observers.length; i 
    
     Passing Arguments  
    

    Currently the observers are being called, but they are not being fed any data. They know something happened - but not necessarily what. We will make notify take any number of arguments, simply passing them along to each observer:

    "test should pass through arguments": function () {
      var observable = new tddjs.Observable();
      var actual;
    
      observable.addObserver(function () {
        actual = arguments;
      });
    
      observable.notify("String", 1, 32);
    
      assertEquals(["String", 1, 32], actual);
    }
    

    The test compares received and passed arguments by assigning the received arguments to a variable local to the test. The observer we just created is in fact a very simple manual test spy. Running the test confirms that it fails, which is not surprising as we are currently not touching the arguments inside notify.

    To pass the test we can use apply when calling the observer:

    function notify() {
      for (var i = 0, l = this.observers.length; i 
    

    With this simple fix tests go back to green. Note that we sent in this as the first argument to apply, meaning that observers will be called with the observable as this.

    Error Handling

    At this point Observable is functional and we have tests that verify its behavior. However, the tests only verify that the observables behaves correctly in response to expected input. What happens if someone tries to register an object as an observer in place of a function? What happens if one of the observers blow up? Those are questions we need our tests to answer. Ensuring correct behavior in expected situations is important – that is what our objects will be doing most of the time. At least so we could hope. However, correct behavior even when the client is misbehaving is just as important to guarantee a stable and predictable system.

    Adding Bogus Observers

    The current implementation blindly accepts any kind of argument to addObserver. Although our implementation can use any function as an observer, it cannot handle any value. The following test expects the observable to throw an exception when attempting to add an observer which is not callable.

    "test should throw for uncallable observer": function () {
      var observable = new tddjs.Observable();
    
      assertException(function () {
        observable.addObserver({});
      }, "TypeError");
    }
    

    By throwing an exception already when adding the observers we don't need to worry about invalid data later when we notify observers. Had we been programming by contract, we could say that a precondition for the addObserver method is that the input must be callable. The postcondition is that the observer is added to the observable and is guaranteed to be called once the observable calls notify.

    The test fails, so we shift our focus to getting the bar green again as quickly as possible. Unfortunately, there is no way to fake the implementation this – throwing an exception on any call to addObserver will fail all the other tests. Luckily, the implementation is fairly trivial:

    function addObserver(observer) {
      if (typeof observer != "function") {
        throw new TypeError("observer is not function");
      }
    
      this.observers.push(observer);
    }
    

    addObserver now checks that the observer is in fact a function before adding it to the list. Running the tests yields that sweet feeling of success: All green.

    Misbehaving Observers

    The observable now guarantees that any observer added through addObserver is callable. Still, notify may still fail horribly if an observer throws an exception. The next test expects all the observers to be called even if one of them throws an exception.

    "test should notify all even when some fail": function () {
      var observable = new tddjs.Observable();
      var observer1 = function () { throw new Error("Oops"); };
      var observer2 = function () { observer2.called = true; };
    
      observable.addObserver(observer1);
      observable.addObserver(observer2);
      observable.notify();
    
      assertTrue(observer2.called);
    }
    

    Running the test reveals that the current implementation blows up along with the first observer, causing the second observer not to be called. In effect, notify is breaking its guarantee that it will always call all observers once they have been successfully added. To rectify the situation, the method needs to be prepared for the worst:

    function notify() {
      for (var i = 0, l = this.observers.length; i 
    

    The exception is silently discarded. It is the observer's responsibility to ensure that any errors are handled properly, the observable is simply fending off badly behaving observers.

    Documenting Call Order

    We have improved the robustness of the Observable module by giving it proper error handling. The module is now able to give guarantees of operation as long as it gets good input and it is able to recover should an observer fail to meet its requirements. However, the last test we added makes an assumption on undocumented features of the observable: It assumes that observers are called in the order they were added. Currently, this solution works because we used an array to implement the observers list. Should we decide to change this, however, our tests may break. So we need to decide: do we refactor the test to not assume call order, or do we simply add a test that expects call order – thereby documenting call order as a feature? Call order seems like a sensible feature, so our next test will make sure Observable keeps this behavior.

    "test should call observers in the order they were added":
    function () {
      var observable = new tddjs.Observable();
      var calls = [];
      var observer1 = function () { calls.push(observer1); };
      var observer2 = function () { calls.push(observer2); };
      observable.addObserver(observer1);
      observable.addObserver(observer2);
    
      observable.notify();
    
      assertEquals(observer1, calls[0]);
      assertEquals(observer2, calls[1]);
    }
    

    Since the implementation already uses an array for the observers, this test succeeds immediately.

    Observing Arbitrary Objects

    In static languages with classical inheritance, arbitrary objects are made observable by subclassing the Observable class. The motivation for classical inheritance in these cases comes from a desire to define the mechanics of the pattern in one place and reuse the logic across vast amounts of unrelated objects. In JavaScript, we have several options for code reuse among objects, so we need not confine ourselves to an emulation of the classical inheritance model.

    In the interest of breaking free of the classical emulation that constructors provide, consider the following examples which assume that tddjs.observable is an object rather than a constructor:

    Note: The tddjs.extend method is introduced elsewhere in the book and simply copies properties from one object to another.

    
    // Creating a single observable object
    var observable = Object.create(tddjs.util.observable);
    
    // Extending a single object
    tddjs.extend(newspaper, tddjs.util.observable);
    
    // A constructor that creates observable objects
    function Newspaper() {
      /* ... */
    }
    
    Newspaper.prototype = Object.create(tddjs.util.observable);
    
    // Extending an existing prototype
    tddjs.extend(Newspaper.prototype, tddjs.util.observable);
    

    Simply implementing the observable as a single object offers a great deal of flexibility. To get there we need to refactor the existing solution to get rid of the constructor.

    Making the Constructor Obsolete

    To get rid of the constructor we should first refactor Observable such that the constructor doesn't do any work. Luckily, the constructor only initializes the observers array, which shouldn't be too hard to remove. All the methods on Observable.prototype access the array, so we need to make sure they can all handle the case where it hasn't been initialized. To test for this we simply need to write one test per method which calls the method in question prior to doing anything else.

    As we already have tests that call addObserver and hasObserver before doing anything else, we will concentrate on the notify method. This method is only tested after addObserver has been called. Our next tests expects it to be possible to call this method prior to adding any observers.

    "test should not fail if no observers": function () {
      var observable = new tddjs.Observable();
    
      assertNoException(function () {
        observable.notify();
      });
    }
    

    With this test in place we can empty the constructor:

    function Observable() {
    }
    

    Running the tests shows that all but one is now failing, all with the same message: "this.observers is not defined". We will deal with one method at a time. First up is addObserver method:

    function addObserver(observer) {
    if (!this.observers) {
    this.observers = [];
    }

    /* ... */
    }

    Running the tests again reveals that the updated addObserver method fixes all but the two tests which does not start by calling it. Next up, we make sure to return false directly from hasObserver if the array does not exist.

    function hasObserver(observer) {
      if (!this.observers) {
        return false;
      }
    
      /* ... */
    }
    

    We can apply the exact same fix to notify:

    function notify(observer) {
      if (!this.observers) {
        return;
      }
    
      /* ... */
    }
    
    Replacing the Constructor With an Object

    Now that the constructor doesn't do anything it can be safely removed. We will then add all the methods directly to the tddjs.observable object, which can then be used with e.g. Object.create or tddjs.extend to create observable objects. Note that the name is no longer capitalized as it is no longer a constructor. The updated implementation follows:

    (function () {
      function addObserver(observer) {
        /* ... */
      }
    
      function hasObserver(observer) {
        /* ... */
      }
    
      function notify() {
        /* ... */
      }
    
      tddjs.observable = {
        addObserver: addObserver,
        hasObserver: hasObserver,
        notify: notify
      };
    }());
    

    Surely, removing the constructor causes all the tests so far to break. Fixing them is easy, however. All we need to do is to replace the new statement with a call to Object.create. However, most browsers don't support Object.create yet, so we can shim it. Because the method is not possible to perfectly emulate, we will provide our own version on the tddjs object:

    (function () {
      function F() {}
    
      tddjs.create = function (object) {
        F.prototype = object;
        return new F();
      };
    
      /* Observable implementation goes here ... */
    }());
    

    With the shim in place, we can update the tests in a matter that will work even in old browsers. The final test suite follows:

    TestCase("ObservableAddObserverTest", {
      setUp: function () {
        this.observable = tddjs.create(tddjs.observable);
      },
    
      "test should store functions": function () {
        var observers = [function () {}, function () {}];
    
        this.observable.addObserver(observers[0]);
        this.observable.addObserver(observers[1]);
    
        assertTrue(this.observable.hasObserver(observers[0]));
        assertTrue(this.observable.hasObserver(observers[1]));
      }
    });
    
    TestCase("ObservableHasObserverTest", {
      setUp: function () {
        this.observable = tddjs.create(tddjs.observable);
      },
    
      "test should return false when no observers": function () {
        assertFalse(this.observable.hasObserver(function () {}));
      }
    });
    
    TestCase("ObservableNotifyTest", {
      setUp: function () {
        this.observable = tddjs.create(tddjs.observable);
      },
    
      "test should call all observers": function () {
        var observer1 = function () { observer1.called = true; };
        var observer2 = function () { observer2.called = true; };
    
        this.observable.addObserver(observer1);
        this.observable.addObserver(observer2);
        this.observable.notify();
    
        assertTrue(observer1.called);
        assertTrue(observer2.called);
      },
    
      "test should pass through arguments": function () {
        var actual;
    
        this.observable.addObserver(function () {
          actual = arguments;
        });
    
        this.observable.notify("String", 1, 32);
    
        assertEquals(["String", 1, 32], actual);
      },
    
      "test should throw for uncallable observer": function () {
        var observable = this.observable;
    
        assertException(function () {
          observable.addObserver({});
        }, "TypeError");
      },
    
      "test should notify all even when some fail": function () {
        var observer1 = function () { throw new Error("Oops"); };
        var observer2 = function () { observer2.called = true; };
    
        this.observable.addObserver(observer1);
        this.observable.addObserver(observer2);
        this.observable.notify();
    
        assertTrue(observer2.called);
      },
    
      "test should call observers in the order they were added":
      function () {
        var calls = [];
        var observer1 = function () { calls.push(observer1); };
        var observer2 = function () { calls.push(observer2); };
        this.observable.addObserver(observer1);
        this.observable.addObserver(observer2);
    
        this.observable.notify();
    
        assertEquals(observer1, calls[0]);
        assertEquals(observer2, calls[1]);
      },
    
      "test should not fail if no observers": function () {
        var observable = this.observable;
    
        assertNoException(function () {
          observable.notify();
        });
      }
    });
    

    To avoid duplicating the tddjs.create call, each test case gained a setUp method which sets up the observable for testing. The test methods has to be updated accordingly, replacing observable with this.observable.

    Summary

    Test-Driven JavaScript Development
    Through this excerpt from the book we have had a soft introduction to Test-Driven Development with JavaScript. Of course, the API is currently limited in its capabilities, but the book expands further on it by allowing observers to observe and notify custom events, such as observable.observe("beforeLoad", myObserver).

    The book also provides insight into how you can apply TDD to develop code that e.g. relies heavily on DOM manipulation and Ajax, and finally brings all the sample projects together in a fully functional browser-based chat application.

    This excerpt is based on the book, 'Test-Driven JavaScript Development', authored by Christian Johansen, published by Pearson/Addison-Wesley Professional, Sept. 2010, ISBN 0321683919, Copyright 2011 Pearson Education, Inc. Refer here for a complete Table of Contents.


  • Permalink for 'Zend Framework from Scratch – Models and Integrating Doctrine ORM'

    Zend Framework from Scratch – Models and Integrating Doctrine ORM

    Posted: January 12th, 2012, 9:39am MST by Nikko Bautista

    Ready to take your PHP skills to the next level? In this new “From Scratch” series, we’ll focus exclusively on Zend Framework, a full-stack PHP framework created by Zend Technologies. This second tutorial on our series is entitled “Models and Integrating Doctrine ORM”.

    Review

    Welcome back to our Zend Framework from Scratch series! In our last tutorial, we learned some basic things about Zend Framework, such as:

    • Where to download the latest Zend Framework files
    • Where and how to set it up locally
    • Creating your first Zend Framework project and setting up a VirtualHost on your web server
    • How exactly Zend Framework implements the MVC pattern and its default application routing
    • Passing data from a controller to its view
    • Creating a site-wide layout for your Zend Framework application
    • Creating new controllers and actions

    If you haven’t yet, you should give the previous tutorial a read. It will really make it easier to for you to understand some Zend Framework basics and help you understand some things we discuss in this tutorial.

    In this second part of the series, we’ll be talking about a crucial part of any web application — the MODELS. We’ll also be taking a look at how to integrate the very popular Doctrine ORM with our Zend Framework project, and find out why it’s much better to use than Zend Framework’s native Zend_Db. So, without further ado, let’s begin!

    What exactly are “Models”?

    When I started trying to grasp the concept of MVC, I read quite a number of analogies, which attempted to explain exactly what each of these components represent. One of the best analogies I’ve read so far was from this article, Another way to think about MVC. It goes something like this:

    So, let’s imagine a bank.

    The safe is the Database – this is where all the most important goodies are stored, and are nicely protected from the outside world.

    Then we have the bankers or in programmatic terms the Models. The bankers are the only ones who have access to the safe (the DB). They are generally fat, old and lazy, which follows quite nicely with one of the rules of MVC: *fat Models, skinny controllers*. We’ll see why and how this analogy applies a little later.
    Now we’ve got our average bank workers, the gophers, the runners, the Controllers. Controllers or gophers do all the running around, that’s why they have to be fit and skinny. They take the loot or information from the bankers (the Models) and bring it to the bank customers the Views.

    The bankers (Models) have been at the job for a while, therefore they make all the important decisions. Which brings us to another rule: *keep as much business logic in the Model as possible*. The controllers, our average workers, should not be making such decisions, they ask the banker for details, get the info, and pass it on to the customer (the View). Hence, we continue to follow the rule of *fat Models, skinny controllers*. The gophers do not make important decisions, but they cannot be plain dumb (thus a little business logic in the controller is OK). However, as soon as the gopher begins to think too much the banker gets upset and your bank (or you app) goes out of business. So again, always remember to offload as much business logic (or decision making) to the model.

    Now, the bankers sure as hell aren’t going to talk to the customers (the View) directly, they are way too important in their cushy chairs for that. Thus another rule is followed: *Models should not talk to Views*. This communication between the banker and the customer (the Model and the View) is always handled by the gopher (the Controller). (Yes, there are some exception to this rule for super VIP customers, but let’s stick to basics for the time being).

    It also happens that a single worker (Controller) has to get information from more than one banker, and that’s perfectly acceptable. However, if the bankers are related (otherwise how else would they land such nice jobs?)… the bankers (Models) will communicate with each other first, and then pass cumulative information to their gopher, who will happily deliver it to the customer (View). So here’s another rule: *Related Models provide information to the controller via their association (relation)*.

    So what about our customer (the View)? Well, banks do make mistakes and the customer should be smart enough to balance their own account and make some decisions. In MVC terms we get another simple rule: *it’s quite alright for the views to contain some logic, which deals with the view or presentation*. Following our analogy, the customer will make sure not forget to wear pants while they go to the bank, but they are not going to tell the bankers how to process the transactions.

    MVC Architecture Diagram

    MVC Architecture Diagram

    Image courtesy of ash.MVC (now named Opendelight)

    In a nutshell:

    • Models are representatives of the Database, and should be where all the business logic of an application resides
    • Controllers communicate with Models and ask them to retrieve information they need
    • This information is then passed by a Controller to the View and is rendered
    • It’s very rare that a Model directly interacts with a View, but sometimes it may happen when necessary
    • Models can talk with other Models and aren’t self-contained. They have relationships that intertwine with each other
    • These relationships make it easier and quicker for a Controller to get information, since it doesn’t have to interact with different Models – the Models can do that themselves

    We can see how important Models are in any application, since it’s repsonsible for any dynamic actions that happens in an application. Now that we have a pretty clear understanding of the responsibilities of the Model, as well as the View and Controller, let’s dive into implementing the Models in our application.

    Step 1 - Setting up your Zend Application to Connect to a Database

    The first thing we’ll need to do is to make our Zend application connect to a database. Luckily, the zf command can take care of that. Open your Command Prompt (or Terminal), cd into your thenextsocial folder, and type in the following:

    zf configure db-adapter "adapter=PDO_MYSQL&dbname=thenextsocial&host=localhost&username=[your local database username]&password=[your local database password]" -s development

    If correct, you should get an output similar to:

    A db configuration for the development section has been written to the application config file.

    Additionally, you should see two new lines inside your application.ini file:

    resources.db.adapter = "PDO_MYSQL"
    resources.db.params.dbname = "thenextsocial"
    resources.db.params.host = "localhost"
    resources.db.params.username = "[your local database username]"
    resources.db.params.password = "[your local database password]"
    </p></code>
    
    <h3>The application.ini explained</h3>
    <p>The <code>application.ini</code> is a configuration file which should contain all of the configuration we have for an application. This includes, for example, what kind of database we're using, what the database name is, the username and password we'll be using with the database, even custom PHP settings like error display and include paths.</p>
    
    <div class="tutorial_image">
    <img src=" [d2o0t5hpnwv4c1.cloudfront.net] alt="The application.ini file" title="The application.ini file" />
    
    <small>The <code>application.ini</code> file</small>
    </div>
    
    <p>I'm sure you've noticed that the <code>application.ini</code> file has sections enclosed in [square brackets]. One of the great things about the <code>application.ini</code> is that you can define different settings depending on what environment your code is in. For example, the database parameters we created earlier falls under the <code>[development : production]</code> section, which means that the set of settings under this section will be used when the application is being run on the <code>development</code> environment.</p>
    
    <p>To add to that, you can &ldquo;inherit&rdquo; settings from another section. For example, the <code>[development : production]</code> section is the configuration for the <code>development</code> environmnent, but inherits all the settings from the <code>production</code> environment as well. This means that any setting which you haven't explicitly overwritten in <code>development</code> will use the setting from <code>production</code>. This allows you to configure settings that are the same in all environments in one place, and just override the ones that you need. Pretty nifty huh?</p>
    
    <p>To configure our project to use the <code>development</code> configuration settings, open or create an <strong>.htaccess</strong> file inside the <strong>public_html</strong> folder, and make sure that it looks like this:</p>
    
    1
    SetEnv APPLICATION_ENV development
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} -s [OR]
    RewriteCond %{REQUEST_FILENAME} -l [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^.*$ - [NC,L]
    RewriteRule ^.*$ index.php [NC,L]
    

    We can clearly see that the SetEnv APPLICATION_ENV directive sets our application’s environment. If and when we move the application to another environment, this should be the only thing we need to change. This ensures that everything our application relies on to work is defined in the application.ini, which makes sure that our application isn’t relying on any external setting. This helps eliminate the “it works on my development machine, how come it doesn’t work on the production server?” problem.

    Step 2 - Create the Database and Some Tables

    Before we create your our first Model for the application, we’ll need a Database that the Model will represent first. Let’s start with something simple — a User table, where we’ll save all the registered users for TheNextSocial.

    Login to your MySQL database and create a database called thenextsocial. Once created, execute the following query to create a User table, and an accompanying User Settings table:

    CREATE TABLE `thenextsocial`.`user` (
      `id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
      `email` VARCHAR(100) NOT NULL,
      `password` TEXT NOT NULL,
      `salt` TEXT NOT NULL,
      `date_created` DATETIME NOT NULL,
      PRIMARY KEY (`id`),
      UNIQUE INDEX `Index_email`(`email`)
    )
    ENGINE = InnoDB
    CHARACTER SET utf8 COLLATE utf8_general_ci;
    
    CREATE TABLE `thenextsocial`.`user_settings` (
      `id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
      `user_id` INTEGER UNSIGNED NOT NULL,
      `name` VARCHAR(100) NOT NULL,
      `value` TEXT NOT NULL,
      PRIMARY KEY (`id`),
      CONSTRAINT `FK_user_settings_user_id` FOREIGN KEY `FK_user_settings_user_id` (`user_id`)
        REFERENCES `user` (`id`)
        ON DELETE CASCADE
        ON UPDATE CASCADE
    )
    ENGINE = InnoDB
    CHARACTER SET utf8 COLLATE utf8_general_ci;
    

    These SQL queries should create two tables. A user table with the following columns:

    • id – a unique ID for each user
    • email – the email address of the user, also unique
    • password – the user’s password, which we’ll hash
    • salt – a random salt, which we’ll use to hash the user’s password
    • date_created – the date and time the user record was created

    And a user_settings table, where we’ll store any user-related settings, with the columns:

    • id – a unique ID for each setting
    • user_id – the user_id which is a foreign key to user.id
    • name – a string of text that represents the setting
    • value – the value of the setting

    It’s worth taking note that the User and User Settings table share a One-to-Many relationship, which means a single User record can be related to multiple User Settings records. This will make it easier to store any kind of information related to a user, for example, their name or profile photo.

    Now that we have a few tables to play around with, let’s learn how to create our first Model: the User Model.

    Step 3 - Creating your First Model The DAO Design Pattern

    As with a lot of applications, the usual way to use make models in Zend Framework is to make use of a popular design pattern called the “DAO” pattern. In this pattern we have the following components:

    The DAO Design Pattern

    The DAO Design Pattern

    Image courtesy of [www.informit.com]

    • Table Data Gateway (DataSource) which connects our application to the data source, the MySQL table
    • Data Mapper (DataAccessObject) which maps the data retrieved from the database to the
    • Data Object (Data) which represents a row from our database, after the DataMapper maps the data to it

    Let’s begin by creating a Table Data Gateway for the User table using the zf CLI tool:

    zf create db-table User user
    Creating a DbTable at thenextsocial/application/models/DbTable/User.php
    Updating project profile 'thenextsocial/.zfproject.xml'
    

    The zf create db-table takes in two parameters:

    • ClassName – the name of the class
    • database_table – the name of the table

    Open the User.php file found in the application/models/DbTable folder and it should look like this:

    <?php
    
    class Application_Model_DbTable_User extends Zend_Db_Table_Abstract
    {
    
        protected $_name = 'user';
    
    }
    

    Now let’s create a Data Mapper class. Again, using the zf CLI tool:

    zf create model UserMapper
    Creating a model at thenextsocial/application/models/UserMapper.php
    Updating project profile 'thenextsocial/.zfproject.xml'
    

    The UserMapper.php file will be empty right now but we’ll put in some code later. For now, we need to create the Data Object, which is the User model:

    zf create model User
    Creating a model at thenextsocial/application/models/User.php
    Updating project profile 'thenextsocial/.zfproject.xml'
    </p></code>
    
    <p>Now that we have all three components of the DAO pattern, we create the code for the files. Open the <code>UserMapper.php</code> file and put in the following code:</p>
    
    1
    <?php
    class Application_Model_UserMapper
    {
    	protected $_db_table;
    
    	public function __construct()
    	{
    		//Instantiate the Table Data Gateway for the User table
    		$this->_db_table = new Application_Model_DbTable_User();
    	}
    
    	public function save(Application_Model_User $user_object)
    	{
    		//Create an associative array
    		//of the data you want to update
    		$data = array(
    			'email' => $user_object->email,
    			'password' => $user_object->password,
    		);
    
    		//Check if the user object has an ID
    		//if no, it means the user is a new user
    		//if yes, then it means you're updating an old user
    		if( is_null($user_object->id) ) {
    			$data['salt'] = $user_object->salt;
    			$data['date_created'] = date('Y-m-d H:i:s');
    			$this->_db_table->insert($data);
    		} else {
    			$this->_db_table->update($data, array('id = ?' => $user_object->id));
    		}
    	}
    
    	public function getUserById($id)
    	{
    		//use the Table Gateway to find the row that
    		//the id represents
    		$result = $this->_db_table->find($id);
    
    		//if not found, throw an exsception
    		if( count($result) == 0 ) {
    			throw new Exception('User not found');
    		}
    
    		//if found, get the result, and map it to the
    		//corresponding Data Object
    		$row = $result->current();
    		$user_object = new Application_Model_User($row);
    
    		//return the user object
    		return $user_object;
    	}
    }
    

    Here we have three methods:

    • __construct() – constructor for the class. Once instantiated, it creates an instance of the Table Data Gateway and stores it
    • save(Application_Model_User $user_object) – takes in a Application_Model_User and saves the data from the object to the database
    • getUserById($id) – takes in an integer $id which represents a single row from the database table, retrieves it, then returns a Application_Model_User with the data mapped

    Open up User.php and put the following code in:

    <?php
    class Application_Model_User
    {
    	//declare the user's attributes
    	private $id;
    	private $email;
    	private $password;
    	private $salt;
    	private $date_created;
    
    	//upon construction, map the values
    	//from the $user_row if available
    	public function __construct($user_row = null)
    	{
    		if( !is_null($user_row) && $user_row instanceof Zend_Db_Table_Row ) {
    			$this->id = $user_row->id;
    			$this->email = $user_row->email;
    			$this->password = $user_row->password;
    			$this->salt = $user_row->salt;
    			$this->date_created = $user_row->date_created;
    		}
    	}
    
    	//magic function __set to set the
    	//attributes of the User model
    	public function __set($name, $value)
    	{
    		switch($name) {
    			case 'id':
    				//if the id isn't null, you shouldn't update it!
    				if( !is_null($this->id) ) {
    					throw new Exception('Cannot update User\'s id!');
    				}
    				break;
    			case 'date_created':
    				//same goes for date_created
    				if( !is_null($this->date_created) ) {
    					throw new Exception('Cannot update User\'s date_created');
    				}
    				break;
    			case 'password':
    				//if you're updating the password, hash it first with the salt
    				$value = sha1($value.$this->salt);
    				break;
    		}
    
    		//set the attribute with the value
    		$this->$name = $value;
    	}
    
    	public function __get($name)
    	{
    		return $this->$name;
    	}
    }
    
    • __construct($user_row) – takes in an optional Zend_Db_Table_Row object, which represents one row from the database, and maps the data to itself
    • __set($name, $value) – a magic function that takes care of setting all of the attributes for the model.
    • __get($name) – a magic function that takes care of getting an attribute of the model.

    Let’s try it out! If you followed the previous tutorial, you should have an IndexController.php file. Open it and put in this code that creates a new user:

    public function indexAction()
    {
    	// action body
    	$this->view->current_date_and_time = date('M d, Y - H:i:s');
    
    	$user = new Application_Model_User();
    	$user->email = 'nikko@test.local';
    	$user->salt = sha1(time());
    	$user->password = 'test';
    	$user->date_created = date('Y-m-d H:i:s');
    
    	$user_mapper = new Application_Model_UserMapper();
    	$user_mapper->save($user);
    }
    

    Now go to [thenextsocial.local] . Once it loads, check the thenextsocial.user table on MySQL and if everything worked, you should have a new User record!

    A new User record!

    A new User record!

    Now, let’s try updating this record. Go back to IndexController.php and update the code to match the following:

    public function indexAction()
    {
    	// action body
    	$this->view->current_date_and_time = date('M d, Y - H:i:s');
    
    	$user_mapper = new Application_Model_UserMapper();
    	$user = $user_mapper->getUserById(1);
    	$user->email = 'new_email@test.local';
    	$user_mapper->save($user);
    }
    

    Check the MySQL table again, and you should see that the email for the record has been updated!

    Updated User record

    Updated User record

    Congratulations! You’ve successfully created your first ever Zend Framework Model!

    The Doctrine ORM Introduction

    From the Doctrine ORM website, [doctrine-project.org] :

    Object relational mapper (ORM) for PHP that sits on top of a powerful database abstraction layer (DBAL). One of its key features is the option to write database queries in a proprietary object oriented SQL dialect called Doctrine Query Language (DQL), inspired by Hibernates HQL. This provides developers with a powerful alternative to SQL that maintains flexibility without requiring unnecessary code duplication.

    Basically, the Doctrine ORM library abstracts most, if not all of the Model implementation for an application. Some of the incredible advantages I discovered while using Doctrine with Zend Framework are:

    • Very easy to use, guaranteed to cut your development time in half
    • Works just as well with different kinds of DB’s with very little tweaking needed. For example, Doctrine made it very easy for me to port an application I worked on before from using MySQL to MSSQL
    • A scaffolding tool, called Doctrine_Cli that creates models from the database very quickly

    To get started, you should download the Doctrine ORM library first from their site. I’ll be using the 1.2.4 version. Go to [www.doctrine-project.org] and click on the Download 1.2.4 Package link.

    Downloading the Doctrine ORM

    Downloading the Doctrine ORM

    Once downloaded, open it and extract the contents. Inside, you should see Doctrine-1.2.4 folder and a package.xml file. Go inside the folder and you should see a Doctrine folder, a Doctrine.php file, and a LICENSE file.

    Doctrine download contents

    Doctrine download contents

    Copy the Doctrine folder and the Doctrine.php file and put it inside the include path of your PHP installation. If you remember how we set up Zend Framework from the last tutorial, it’s most likely the same folder you placed the Zend library files in.

    Doctrine library with Zend library in PHP's include_path

    Doctrine library with Zend library in PHP’s include_path

    Now we’re ready to integrate it with our Zend application! Begin by opening application.ini again and adding the following configuration inside the [development : production] block:

    ;Doctrine settings
    resources.doctrine.connection_string = "mysql://[replace with db username]:[replace with db password]@localhost/thenextsocial"
    resources.doctrine.models_path = APPLICATION_PATH "/models"
    resources.doctrine.generate_models_options.pearStyle = true
    resources.doctrine.generate_models_options.generateTableClasses = true
    resources.doctrine.generate_models_options.generateBaseClasses = true
    resources.doctrine.generate_models_options.classPrefix = "Model_"
    resources.doctrine.generate_models_options.baseClassPrefix = "Base_"
    resources.doctrine.generate_models_options.baseClassesDirectory =
    resources.doctrine.generate_models_options.classPrefixFiles = false
    resources.doctrine.generate_models_options.generateAccessors = false
    

    Now that we have our configuration set up, open the application’s Bootstrap.php file. You’ll find this inside the thenextsocial/application folder.

    The Bootstrap.php

    The Bootstrap.php lets us initialize any resources we might use in our application. Basically, all resources we need to instantiate should be placed here. We’ll dive into this in more detail later in the series, but for now, all you need to know is that the format for methods here are like this:

    protected function _initYourResource()
    {
    	//Do your resource setup here
    }
    

    Inside the Bootstra.php file, add the following code to initialize Doctrine with the application:

    <?php
    class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
    {
    	public function _initDoctrine()
    	{
    		//require the Doctrine.php file
    		require_once 'Doctrine.php';
    
    		//Get a Zend Autoloader instance
    		$loader = Zend_Loader_Autoloader::getInstance();
    
    		//Autoload all the Doctrine files
    		$loader->pushAutoloader(array('Doctrine', 'autoload'));
    
    		//Get the Doctrine settings from application.ini
    		$doctrineConfig = $this->getOption('doctrine');
    
    		//Get a Doctrine Manager instance so we can set some settings
    		$manager = Doctrine_Manager::getInstance();
    
    		//set models to be autoloaded and not included (Doctrine_Core::MODEL_LOADING_AGGRESSIVE)
    		$manager->setAttribute(
    			Doctrine::ATTR_MODEL_LOADING,
    			Doctrine::MODEL_LOADING_CONSERVATIVE);
    
    		//enable ModelTable classes to be loaded automatically
    		$manager->setAttribute(
    			Doctrine_Core::ATTR_AUTOLOAD_TABLE_CLASSES,
    			true
    		);
    
    		//enable validation on save()
    		$manager->setAttribute(
    			Doctrine_Core::ATTR_VALIDATE,
    			Doctrine_Core::VALIDATE_ALL
    		);
    
    		//enable sql callbacks to make SoftDelete and other behaviours work transparently
    		$manager->setAttribute(
    			Doctrine_Core::ATTR_USE_DQL_CALLBACKS,
    			true
    		);
    
    		//not entirely sure what this does :)
    		$manager->setAttribute(
    			Doctrine_Core::ATTR_AUTO_ACCESSOR_OVERRIDE,
    			true
    		);
    
            //enable automatic queries resource freeing
    		$manager->setAttribute(
    			Doctrine_Core::ATTR_AUTO_FREE_QUERY_OBJECTS,
    			true
    		);
    
    		//connect to database
    		$manager->openConnection($doctrineConfig['connection_string']);
    
    		//set to utf8
    		$manager->connection()->setCharset('utf8');
    
    		return $manager;
    	}
    
    	protected function _initAutoload()
    	{
    		// Add autoloader empty namespace
    		$autoLoader = Zend_Loader_Autoloader::getInstance();
    		$resourceLoader = new Zend_Loader_Autoloader_Resource(array(
    			'basePath' => APPLICATION_PATH,
    			'namespace' => '',
    			'resourceTypes' => array(
    				'model' => array(
    					'path' => 'models/',
    					'namespace' => 'Model_'
    				)
    			),
    		));
    		// Return it so that it can be stored by the bootstrap
    		return $autoLoader;
    	}
    }
    

    The setup I’ve done here is based on a script I found in the past on http://dev.juokaz.com, which was maintained by Juozas Kaziukenas, one of the team members at the Doctrine project. Sadly, the blog has already been shut down, so I won’t be able to link to it anymore. Also, take note that we have another method called _initAutoload(). This basically initializes the Zend Autoloader, which will autoload all the generated models inside the models folder. This saves us the hassle of having to include these files one by one.

    Next, we need to setup the Doctrine CLI script that we’ll use to auto-generate Models from the database. Go back to the thenextsocial folder and create a folder called scripts. Inside, create a file named doctrine-cli.php and put the following inside:

    <?php
    /**
     * Doctrine CLI script
     *
     * @author Juozas Kaziukenas (juozas@juokaz.com)
     */
    
    define('APPLICATION_ENV', 'development');
    define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
    
    set_include_path(implode(PATH_SEPARATOR, array(
        realpath(APPLICATION_PATH . '/../library'),
        './',
        get_include_path(),
    )));
    
    require_once 'Zend/Application.php';
    
    // Create application, bootstrap, and run
    $application = new Zend_Application(
        APPLICATION_ENV,
        APPLICATION_PATH . '/configs/application.ini'
    );
    
    $application->getBootstrap()->bootstrap('doctrine');
    
    // set aggressive loading to make sure migrations are working
    Doctrine_Manager::getInstance()->setAttribute(
        Doctrine::ATTR_MODEL_LOADING,
        Doctrine_Core::MODEL_LOADING_AGGRESSIVE
    );
    
    $options = $application->getBootstrap()->getOptions();
    
    $cli = new Doctrine_Cli($options['doctrine']);
    
    $cli->run($_SERVER['argv']);
    

    Go back inside to your models folder and delete the User model files we have there (if you want, you can move it to another location first, but it shouldn’t be inside the folder). Next, open up your command prompt (or terminal), cd to the scripts folder and type in the following command:

    php doctrine-cli.php

    You should see something like this:

    Expected Doctrine CLI output

    Expected Doctrine CLI output

    If everything worked out, let’s start creating some models! Type in the following:

    php doctrine-cli.php generate-models-db

    You should now see the following output:

    Generating Models using Doctrine CLI

    Generating Models using Doctrine CLI

    If you did, check out your models folder again and you should see some brand new User and UserSettings models that have been generated by Doctrine!

    Generated Models!

    Generated Models!

    If you open the files, you won’t see much inside. Most of the code for the models are abstracted by the Doctrine library. By extending the Doctrine_Record class, we have available to us a lot of prebuilt methods from the library. Open IndexController.php again and replace the old test code with the following:

    public function indexAction()
    {
    	// action body
    	$this->view->current_date_and_time = date('M d, Y - H:i:s');
    
    	$user = new Model_User();
    	$user->email = 'new_user_2@test.local';
    	$user->password = 'test';
    	$user->salt = sha1(time());
    	$user->date_created = date('Y-m-d H:i:s');
    	$user->save();
    }
    

    Once done, go back to [thenextsocial.local] . If the page loads, check your MySQL table and you should see that a brand new User record has been inserted!

    User record via Doctrine ORM

    User record via Doctrine ORM

    Now, let’s try some more complicated stuff — retrieving an existing User via prebuilt Doctrine methods and updating it. Update the code so it looks like this:

    public function indexAction()
    {
    	// action body
    	$this->view->current_date_and_time = date('M d, Y - H:i:s');
    
    	$user = Doctrine_Core::getTable('Model_User')->findOneByEmailAndPassword('new_user_2@test.local', 'test');
    	$user->password = 'new_password';
    	$user->save();
    }
    

    The findOneByEmailAndPassword() method is a convenience method prebuilt by Doctrine to make it easier to select one row from the database. The great thing about it is you can mix-and-match table columns in the method. For example, you can call something like findOneByIdAndNameAndPasswordAndSalt() and it will still work!

    Updating a User record via Doctrine ORM

    Updating a User record via Doctrine ORM

    There’s a whole lot more we can do now that we use Doctrine ORM for the application’s Model implementation. Stuff like the Doctrine Query Language (DQL), taking advantage of Model relationships and generating Models from YAML. For the remainder of the series, we’ll be using Doctrine ORM for the Model implementation of the application, so you’ll actually be learning two things in the series instead of just one! Score!

    Conclusion

    By now, you should be able to know the following:

    • What are “Models”
    • Connecting your Zend application to a database
    • How the application.ini works
    • The DAO Design Pattern
    • Creating Models using the ZF CLI tool
    • Where to download the Doctrine ORM and how to install it
    • Integrating the Doctrine ORM with your Zend application
    • The Bootstrap.php
    • Generating Models using the Doctrine CLI tool
    • Basic usage of Models generated with Doctrine

    Now that you know how to implement the Models in an Zend Framework powered application, you have the knowledge to create dynamic websites. Try to play around with the application, create some new Controllers and Models that read, update, save and delete from the database.

    In our next tutorial, we’ll learn about some often used components of the Zend Framework library, the Zend_Auth and Zend_Acl components and build TheNextSocial‘s authentication system!

    Until then, stay tuned, and remember that all the code used here is available on TheNextSocial’s GitHub repository!


  • Permalink for 'Getting Started with MongoDB – Part 2'

    Getting Started with MongoDB – Part 2

    Posted: January 10th, 2012, 9:33am MST by Matthew Setter

    Ready to continue learning about MongoDB, one of the coolest technologies for web developers? In this second part of the series, we move on from the basics, on to advanced queries – with conditional operators – and MapReduce.

    Stepping Beyond the Basics

    Earlier, we covered the basics of and how to get started with mongoDB, one of the absolute best of breed of the NoSQL implementations. We looked at how to install it, create a basic database and then perform the basic operations on it:

    • search
    • update
    • delete

    In addition to this, we started to look at how to start interacting with mongoDB in a more powerful way, through the use of selectors. Selectors give us the ability to have much more fine grained control and to dig pretty deeply in to find the data that we really want.

    Now that’s all well and good to get started with, but when you want to write a real application, you need to go a lot further. Well, this is still a getting started series after all, but I want to get you excited about the possibilities of working in a document-oriented way. I want to enthuse you to take this great technology and make it your own and use it as powerfully as you can to make fantastic applications.

    Today, we’re going to expand on queries from last time and learn two key aspects of mongoDB:

    • Advanced Queries
    • MapReduce
    Advanced Queries

    Previously we looked at basic queries and were introduced to selectors. Now we’re going to get into more advanced queries, by building on the previous work in two key ways:

    • Conditional Operators
    • Regular Expressions

    Each of these successively provide us with more fine-grained control over the queries we can write and, consequently, the information that we can extract from our mongoDB databases.

    Conditional Operators

    Conditional operators are, as the name implies, operators to collection queries that refine the conditions that the query must match when extracting data from the database. There are a number of them, but today I’m going to focus on 9 key ones. These are:

    • $lt – value must be less than the conditional
    • $gt – value must be greater than the conditional
    • $lte – value must be less than or equal to the conditional
    • $gte – value must be greater than or equal to the conditional
    • $in – value must be in a set of conditionals
    • $nin – value must NOT be in a set of conditionals
    • $not – value must be equal to a conditional

    Let’s look at each one in turn. Open up your terminal and get ready to use the original database from the first part in this series (pre-modifications). To make this tutorial easier, we’re going to make a slight alteration to the database. We’re going to give each document in our collection an age attribute. To do that, run the following modification query:

    			db.nettuts.update({"_id" : ObjectId("4ef224be0fec2806da6e9b27")}, {"$set" : {"age" : 18 }});
    			db.nettuts.update({"_id" : ObjectId("4ef224bf0fec2806da6e9b28")}, {"$set" : {"age" : 45 }});
    			db.nettuts.update({"_id" : ObjectId("4ef224bf0fec2806da6e9b29")}, {"$set" : {"age" : 65 }});
    			db.nettuts.update({"_id" : ObjectId("4ef224bf0fec2806da6e9b2a")}, {"$set" : {"age" : 43 }});
    			db.nettuts.update({"_id" : ObjectId("4ef224bf0fec2806da6e9b2b")}, {"$set" : {"age" : 22 }});
    			db.nettuts.update({"_id" : ObjectId("4ef224bf0fec2806da6e9b2c")}, {"$set" : {"age" : 45 }});
    			db.nettuts.update({"_id" : ObjectId("4ef224bf0fec2806da6e9b2d")}, {"$set" : {"age" : 33 }});
    		

    All being well, you can run a ‘find all’ and you’ll have the following output:

    		db.nettuts.find();
    		{ "_id" : ObjectId("4ef224be0fec2806da6e9b27"), "age" : 18, "dob" : "21/04/1978", "first" : "matthew", "gender" : "m", "hair_colour" : "brown", "last" : "setter", "nationality" : "australian", "occupation" : "developer" }
    		{ "_id" : ObjectId("4ef224bf0fec2806da6e9b28"), "age" : 45, "dob" : "26/03/1940", "first" : "james", "gender" : "m", "hair_colour" : "brown", "last" : "caan", "nationality" : "american", "occupation" : "actor" }
    		{ "_id" : ObjectId("4ef224bf0fec2806da6e9b29"), "age" : 65, "dob" : "03/06/1925", "first" : "arnold", "gender" : "m", "hair_colour" : "brown", "last" : "schwarzenegger", "nationality" : "american", "occupation" : "actor" }
    		{ "_id" : ObjectId("4ef224bf0fec2806da6e9b2a"), "age" : 43, "dob" : "21/04/1978", "first" : "tony", "gender" : "m", "hair_colour" : "brown", "last" : "curtis", "nationality" : "american", "occupation" : "developer" }
    		{ "_id" : ObjectId("4ef224bf0fec2806da6e9b2b"), "age" : 22, "dob" : "22/11/1958", "first" : "jamie lee", "gender" : "f", "hair_colour" : "brown", "last" : "curtis", "nationality" : "american", "occupation" : "actor" }
    		{ "_id" : ObjectId("4ef224bf0fec2806da6e9b2c"), "age" : 45, "dob" : "14/03/1933", "first" : "michael", "gender" : "m", "hair_colour" : "brown", "last" : "caine", "nationality" : "english", "occupation" : "actor" }
    		{ "_id" : ObjectId("4ef224bf0fec2806da6e9b2d"), "age" : 33, "dob" : "09/12/1934", "first" : "judi", "gender" : "f", "hair_colour" : "white", "last" : "dench", "nationality" : "english", "occupation" : "actress" }
    		
    $lt/$lte

    Now let’s find all the actors who are less than 40. To do that, run the following query:

    		db.nettuts.find( { "age" : { "$lt" : 40 } } );
    		

    After running that query, you’ll see the following output:

    		{ "_id" : ObjectId("4ef224be0fec2806da6e9b27"), "age" : 18, "dob" : "21/04/1978", "first" : "matthew", "gender" : "m", "hair_colour" : "brown", "last" : "setter", "nationality" : "australian", "occupation" : "developer" }
    		{ "_id" : ObjectId("4ef224bf0fec2806da6e9b2b"), "age" : 22, "dob" : "22/11/1958", "first" : "jamie lee", "gender" : "f", "hair_colour" : "brown", "last" : "curtis", "nationality" : "american", "occupation" : "actor" }
    		{ "_id" : ObjectId("4ef224bf0fec2806da6e9b2d"), "age" : 33, "dob" : "09/12/1934", "first" : "judi", "gender" : "f", "hair_colour" : "white", "last" : "dench", "nationality" : "english", "occupation" : "actress" }
    		

    What about the ones who are less than 40 inclusive? Run the following query to return that result:

    		db.nettuts.find( { "age" : { "$lte" : 40 } } );
    		

    This returns the following list:

    		{ "_id" : ObjectId("4ef224be0fec2806da6e9b27"), "age" : 18, "dob" : "21/04/1978", "first" : "matthew", "gender" : "m", "hair_colour" : "brown", "last" : "setter", "nationality" : "australian", "occupation" : "developer" }
    		{ "_id" : ObjectId("4ef224bf0fec2806da6e9b2b"), "age" : 22, "dob" : "22/11/1958", "first" : "jamie lee", "gender" : "f", "hair_colour" : "brown", "last" : "curtis", "nationality" : "american", "occupation" : "actor" }
    		{ "_id" : ObjectId("4ef224bf0fec2806da6e9b2d"), "age" : 33, "dob" : "09/12/1934", "first" : "judi", "gender" : "f", "hair_colour" : "white", "last" : "dench", "nationality" : "english", "occupation" : "actress" }
    		
    $gt/$gte

    Now let’s find all the actors who are older than 47. Run the following query to find that list:

    			db.nettuts.find( { 'age' : { '$gt' : 47 } } );
    		

    You’ll then get the following output:

    		{ "_id" : ObjectId("4ef224bf0fec2806da6e9b29"), "age" : 65, "dob" : "03/06/1925", "first" : "arnold", "gender" : "m", "hair_colour" : "brown", "last" : "schwarzenegger", "nationality" : "american", "occupation" : "actor" }
    		

    What about inclusive of 40?

    			db.nettuts.find( { 'age' : { '$gte' : 47 } } );
    		

    As there’s only one person over 47, the data returned doesn’t change.

    $in/$nin

    What about finding information based on a list of criteria? These first ones have been ok, but arguably, quite trivial. Let’s now look to see which of the people we have are either actors or developers. With the following query, we’ll find that out (to make it a bit easier to read, we’ve limited the keys that are returned to just first and last names):

    			db.nettuts.find( { 'occupation' : { '$in' : [ "actor", "developer" ] } }, { "first" : 1, "last" : 1 } );
    		

    This query, yields the following output:

    			{ "_id" : ObjectId("4ef224be0fec2806da6e9b27"), "first" : "matthew", "last" : "setter" }
    			{ "_id" : ObjectId("4ef224bf0fec2806da6e9b28"), "first" : "james", "last" : "caan" }
    			{ "_id" : ObjectId("4ef224bf0fec2806da6e9b29"), "first" : "arnold", "last" : "schwarzenegger" }
    			{ "_id" : ObjectId("4ef224bf0fec2806da6e9b2a"), "first" : "tony", "last" : "curtis" }
    			{ "_id" : ObjectId("4ef224bf0fec2806da6e9b2b"), "first" : "jamie lee", "last" : "curtis" }
    			{ "_id" : ObjectId("4ef224bf0fec2806da6e9b2c"), "first" : "michael", "last" : "caine" }
    		

    You can see that we can get the inverse of this by using $ninjust as simply.

    Let’s make this a bit more fun and combine some of the operators. Let’s say that we want to look for all the people, who are either male or developers, they’re less than 40 years of age.

    Now that’s a bit of a mouthful, but with the operators that we’ve used so far – quite readily achievable. Let’s work through it and you’ll see. Have a look at the query below:

    			db.nettuts.find( { $or : [ { "gender" : "m", "occupation" : "developer" } ], "age" : { "$gt" : 40 } }, { "first" : 1, "last" : 1, "occupation" : 1, "dob" : 1 } );
    		

    You can see that we’ve stipulated that the either the gender can be male or the occupation can be a developer in the $or condition and then added an and condition of the age being greater than 4.

    For that, we get the following results:

    			{ "_id" : ObjectId("4ef22e522893ba6797bf8cb6"), "first" : "matthew", "last" : "setter", "dob" : "21/04/1978", "occupation" : "developer" }
    			{ "_id" : ObjectId("4ef22e522893ba6797bf8cb9"), "first" : "tony", "last" : "curtis", "dob" : "21/04/1978", "occupation" : "developer" }
    		
    Regular Expressions

    Now I’m sure that you’re not going to be satisfied with just this. I did promise you some more complexity and advanced functionality. So let’s get in to using some regular expressions. Let’s say that we want to find the users that have a first name starting with ‘ma’ or ‘to’ and who’s last names begin with ‘se’ or ‘de’. How would we do that?

    Have a look at the following query using a regular expression:

    			db.nettuts.find( { "first" : /(ma|to)*/i, "last" : /(se|de)/i  } );
    		

    Given that, the results will be:

    		{ "_id" : ObjectId("4ef22e522893ba6797bf8cb6"), "first" : "matthew", "last" : "setter", "dob" : "21/04/1978", "gender" : "m", "hair_colour" : "brown", "occupation" : "developer", "nationality" : "australian" }
    		{ "_id" : ObjectId("4ef22e532893ba6797bf8cbc"), "first" : "judi", "last" : "dench", "dob" : "09/12/1934", "gender" : "f", "hair_colour" : "white", "occupation" : "actress", "nationality" : "english" }
    		

    Let’s look at that query a bit more closely. Firstly, we’re performing a regex on the first name.

    		"first" : /(ma|to)*/i
    		

    //i indicates that we’re performing a case-insensitive regex.

    (ma|to)* indicates that the start of the first name string must be either ‘ma’ or ‘to’.

    If you’re not familiar, the * at the end, will match anything after that. So when you put it together, we match first names that have either ‘ma’ or ‘to’ at the beginning of them. In the regex for the last name, you can see that we’ve done the same thing, but for the last name.

    Not quite sure? Let’s try another one. What about combining it with one of the conditional operators. Let’s say we want to find all the people with the first name of james or jamie who are american female actors. How would we do that? Well, let’s see how we’d do it below:

    			db.nettuts.find( { "first" : /(jam?e*)*/i, "gender" : "f", "occupation" : "actor", "nationality" : "american"  } );
    		

    The regex above will match combinations such as: james, jamie, jamee etc. The question mark will match one character, whether a-z, A-Z or 0-9. Then, as before, the * matches anything else that comes after the ‘e’. From there on, we’re using the conditional operators from before to further limit the results that come back. It should be noted that as we’re using the case-insensitive operator, I, the queries won’t use an index. But for the purposes of this example, it’s fine.

    The output of the query above is:

    		{ "_id" : ObjectId("4ef22e522893ba6797bf8cba"), "first" : "jamie lee", "last" : "curtis", "dob" : "22/11/1958", "gender" : "f", "hair_colour" : "brown", "occupation" : "actor", "nationality" : "american" }
    		
    MapReduce

    MapReduce is the big daddy of data analysis. In case you’ve not heard of it, MapReduce is a process where the aggregation of data can be split up and farmed out across a cluster of computers to reduce the time that it takes to determine an aggregate result on a set of data.

    It’s made up of two parts: Map and Reduce. Map creates the jobs that can then be farmed out to the worker nodes to run the Reduce component. Reduce then computes the answer for that chunk of work that was farmed out to it and returns the result that can be combined with the other chunks to form the final answer.

    If you want a more specific description, here’s what Wikipedia has to say about it:

    MapReduce is a framework for processing highly distributable problems across huge datasets using a large number of computers (nodes), collectively referred to as a cluster (if all nodes use the same hardware) or a grid (if the nodes use different hardware). Computational processing can occur on data stored either in a file system (unstructured) or in a database (structured).

    “Map” step: The master node takes the input, partitions it up into smaller sub-problems, and distributes them to worker nodes. A worker node may do this again in turn, leading to a multi-level tree structure. The worker node processes the smaller problem, and passes the answer back to its master node.

    “Reduce” step: The master node then collects the answers to all the sub-problems and combines them in some way to form the output – the answer to the problem it was originally trying to solve.

    Example MapReduce

    Let’s look at a simple example. We’re going to analyse our simple dataset and find the total count of all the females in the group. Admittedly, this is a very simplistic example, but it will lay the foundation for understanding, practically, how MapReduce works.

    The Map Function

    Here, we’re going to create a map function that aggregates the information in our dataset by the gender of the person and emits a count of 1 for every one of them.

    			var map = function() {
    			    emit( { gender: this.gender }, { count: 1 } );
    			}
    		

    This will return output similar to the following:

    			{ 'f' : 1 }
    		
    The Reduce Function

    Our reduce function is going to take the output from the map function and use it to keep a running total of the count for each gender. Have a look at the reduce function below.

    			var reduce = function(key, values) {
    			    var result = { count : 0 };
    
    			    values.forEach(function(value){
    			        result.count += value.count;
    			    })
    
    			    return result;
    			}
    		
    Running the MapReduce

    Now, we put them together by calling the mapReduce function in our current database. We pass in the map and reduce variables we created previously by calling our map and reduce functions and specify the name of the collection that the result will be stored in; in this case ‘gender’. Just to reiterate, the result of calling the mapReduce function is a collection in our current database; that we can iterate over just like we would any other collection. Have a look at the code below:

    			var res = db.nettuts.mapReduce( map, reduce, { out : 'gender' } );
    		
    Displaying the output

    When the Map-Reduce is completed, we can access it just like a normal collection, by running the findfunction on it as we do below.

    			db.gender.find();
    			{ "_id" : { "gender" : "f" }, "value" : { "count" : 2 } }
    			{ "_id" : { "gender" : "m" }, "value" : { "count" : 5 } }
    		

    Here, we now have a running total per gender; 2 for females and 5 for males – which correlates with our dataset. But what if we wanted to filter by females in the group. Well, not much to it. We only need to make use of the query clause to allow us to do so. Lucky for us, it will look familiar. Have a look at the query below.

    			var res = db.nettuts.mapReduce( map, reduce, { out : 'gender', query : { "gender" : "f" } } );
    		

    Now, when we display the output, it will look like that below:

    			db.gender.find();
    			{ "_id" : { "gender" : "f" }, "value" : { "count" : 2 } }
    		

    There are a number of other parameters that you can pass to the mapReduce function to further customise the output.

    • sort – sort the output returned
    • limit – limit the number of results returned
    • out – the name of the collection to store the results in
    • finalise – specify a function to run after the reduction process is complete
    • scope – specify variables that can be used in the map, reduce and finalise function scope
    • jsMode – Avoids an intermediate step (between map and reduce) of converting back to JSON format
    • verbose – track statistics about the execution process
    Winding Up

    This has been a whirlwind coverage of some of the more complex topics of mongoDB. But I hope that it’s given you even more of a taste of what’s possible through using this great tool.

    We’ve looked at the conditional operators: $lt, $gt, $lte, $gte, $in, $nin, $not and run through an introduction to MapReduce. I hope that you’ve gotten a lot out of this and will learn more about the great tool that is mongoDB.


  • Permalink for 'Introducing “Regular Expressions: Up and Running”'

    Introducing “Regular Expressions: Up and Running”

    Posted: January 9th, 2012, 6:53pm MST by Jeffrey Way

    Regular expressions are easily one of the (initially) scariest aspects of programming. Particularly at the beginning, when you haven’t learned a single symbol, a large regular expression chunk can serve to be an incredibly intimidating force.

    However, once you dig in and learn a handful of the symbols and sequences, you’ll quickly find that it’s not so bad. Truly learning regular expressions was one of the best decisions that I’ve ever made in my development career. I’d like to pass this learning on to you in my brand new Tuts+ Premium course, Regular Expressions: Up and Running.”

    Overview

    As always, we start at the beginning, and slowly work our way up to more advanced regular expression patterns and techniques. So, if they currently look like Egyptian hieroglyphs to you, no worries, they did for me too! When you’re finished with this course, though, you’ll have a solid grasp of the language, and a fantastic new tool to use in your projects.

    Lesson Overview Tuts+ Premium

    The recently re-launched Tuts+ Premium is a service that provides top-tier training in a variety of creative fields. Whether you prefer books, visual training, or in depth tutorials, we have you covered. While we unfortunately can’t afford to provide the service for free, it’s only $19 a month – less than you’d spend on dinner.

    I hope you’ll consider checking it out! In addition to learning a huge variety of new skills, it’s also a fantastic way to say thank you to Nettuts+.


  • Permalink for 'Win Business Cards, Postcards, or Posters From UPrinting'

    Win Business Cards, Postcards, or Posters From UPrinting

    Posted: January 9th, 2012, 1:00pm MST by Grant Friedman

    Are you looking to start your new year with a fresh set of prints to help promote your design business? Today, our friends at UPrinting are kicking off 2012 by giving away business cards, posters, or postcards to 36 lucky Tuts+ readers. To enter, all you have to do is submit your entry using the form below and select which prize you would prefer.

    Update: The winners for this giveaway have been selected. Thanks to everyone who participated.

    If you are a frequent reader of our site, chances are, you are already familiar with UPrinting. They are an online printer that offers business cards, poster printing, postcard printing, and much more. UPrinting is a frequent sponsor of this site and we are very excited to partner with them on another giveaway.

    Submit Your Entry Up for Grabs

    Today, UPrinting is giving you several options to choose from. You can enter to win 500 standard business cards, 100 postcards, or 1 poster print. The choice is yours! More details can be found below.

    500 Standard Business Cards
    2" x 3.5" US Standard, 2" x 2" Square, 1.75" x 3.5" Slim
    14pt Cardstock Gloss / Matte, 13pt Cardstock Uncoated
    Front and Back Printing
    3 Business Days Turnaround time

    1 Poster Print
    18" x 24"
    Semi Gloss / High Gloss
    1 Business day print turnaround time

    100 Postcards
    5" x 7"
    14pt Cardstock Gloss
    Front Only Printing
    2 Business days print turnaround time

    Rules
    • To enter, submit your entry and select which product you would like.
    • You may only enter once.
    • Follow UPrinting on Twitter, Facebook, or Google+ (Optional)
    • Make sure to enter a valid email address so that we can contact you.
    • Entries will be accepted until Friday, January 20, 2012 at 11:59 PM, EST.
    • Shipping is free to U.S. and International residents.


  • Permalink for 'Dig into Dojo: DojoX'

    Dig into Dojo: DojoX

    Posted: January 9th, 2012, 9:22am MST by Andrew Burgess

    Maybe you saw that tweet: ”jQuery is a gateway drug. It leads to full-on JavaScript usage.” Part of that addiction, I contend, is learning other JavaScript frameworks. And that’s what this four-part series on the incredible Dojo Toolkit is all about: taking you to the next level of your JavaScript addiction.

    In this, the final episode of our session, we’ll look at the last member of the Dojo trinity: DojoX.

    What’s DojoX?

    DojoX is a place where modules can grow and evolve at whatever rate they need to. But don’t get the idea that DojoX is a coding free-for-all. Hardly.

    You could think of DojoX (which stands for Dojo Extensions) as a sandbox, a place where modules can grow and evolve at whatever rate they need to. DojoX modules aren’t necessarily as mature as Dojo and Dijit Modules. And while there is a DojoX leader, as there is for Dojo and Dijit, each of the subprojects (as they’re called) are individually managed.

    But don’t get the idea that DojoX is a coding free-for-all. Hardly. In fact, there are a couple of strict rules. Every subproject must have a README file, which you’ll find in its top directory, under the dojox folder. Then, every subproject also has a status (found in the README). A subproject’s status can be one of the following, based on the level of commitment, and the amount of testing and documentation available:

    • experimental
    • alpha
    • beta
    • production

    Interestingly, if a subproject wants to change its status, the DojoX leader (called the BDFL) must approve it.

    So, what kind of things will you find in DojoX? There are a lot of extensions to Dojo and Dijit functionality (think, plenty of UI widgets); then, there are projects for creating charts, work with feeds, building data tables, and more.

    Well, there’s not much more to say about DojoX in general. So, let’s use a DojoX subproject—and many of the other Dojo chops we’ve learned—and wrap up our “Dig into Dojo” session with a little demo project.

    Here’s what we’ll build: it’s an interactive table (a DojoX project called a DataGrid) with a list of recent tutorials from the Tuts+ websites. We’ll be able to filter the tutorials via typing in a text input box.

    Don’t forget, if you’re a Tuts+ Premium member, you’ll get the accompanying screencast, in which I walk you though building this project, step by step. As a premium member, you’ll also be able to download the code for this mini-project. It’s always a good time to sign up!

    Frame It: The HTML

    Let’s start with some HTML, in index.html, of course.

    <!DOCTYPE html>
    <head>
      <title> Dig into Dojo | Episode 4 </title>
    </head>
    <body class='claro'>
      <div id='main'>
        <div id='settings'>
        </div>
    
        <div id='content'>
        </div>
      </div>
    
      <script data-dojo-config='parseOnLoad: true' src='http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js'></script>
      <script src='script.js'></script>
    </body>
    </html>
    

    Pretty run-of-the-mill, no doubt. We’re loading Dojo from a CDN, and setting parseOnLoad: true. Let’s add a few more elements. Notice that we have a div#settings; let’s fill in some settings there; we want to be able to choose which Tuts+ sites we’re seeing tutorials from. We’ll have a list of checkboxes that allows us to do just that:

    <div id='settings'>
        <p>Choose the sites you'd like to include:</p>
        <ul>
          <li><input type='checkbox' value='aetuts' /> Aetuts+</li>
          <li><input type='checkbox' value='cgtuts' /> Cgtuts+</li>
          <li><input type='checkbox' value='wptuts' /> Wptuts+</li>
          <li><input type='checkbox' value='nettuts' /> Nettuts+</li>
          <li><input type='checkbox' value='psdtuts' /> Psdtuts+</li>
          <li><input type='checkbox' value='phototuts' /> Phototuts+</li>
          <li><input type='checkbox' value='audiotuts' /> Audiotuts+</li>
          <li><input type='checkbox' value='vectortuts' /> Vectortuts+</li>
          <li><input type='checkbox' value='flashtuts' /> Activetuts+</li>
          <li><input type='checkbox' value='mobiletuts' /> Mobiletuts+</li>
          <li><input type='checkbox' value='webdesigntuts' /> Webdesigntuts+</li>
        </ul>
        <button data-dojo-type='dijit.form.Button' data-dojo-id='update'> Update </button>
      </div>
    

    Notice that we’re declaratively creating a Dijit button. We’ll be turning our checkboxes into Dijit checkboxes programatically later.

    What about that div#content?

    <div id='content'>
      <h1> Recent Tutorial from the Tuts+ Network</h1>
      <input type='text' data-dojo-type='dijit.form.TextBox' data-dojo-props='intermediateChanges: true' data-dojo-id='filterBox' />
    
      <div id='table'></div>
    </div>
    

    Another declarative creation; this time, a text box. Be sure to set the property intermediateChanges to true; doing this ensures that the onChange will fire after every keystroke in the text box, and not only when the text box loses focus. We’ll want this behaviour when we hook up our table filtering later.

    Speaking of tables, you can probably guess that our table will show up in div#table later.

    One more thing here: we’ve got to link up a few stylesheets. In the &lt;head>:

    <link rel='stylesheet' href='http://ajax.googleapis.com/ajax/libs/dojo/1.6/dijit/themes/claro/claro.css' />
    <link rel='stylesheet' href='http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojox/grid/resources/Grid.css' />
    <link rel='stylesheet' href='http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojox/grid/resources/claroGrid.css' />
    <link rel='stylesheet' href='style.css' />
    

    The first is a standard Dijit theme. The next two are required for the DataGrid we’ll be using. Finally, we’ll add some styling of our own. Let’s look at that next!

    Style It: The CSS

    There’s nothing too groundbreaking here. We’re centering our content, and pushing our little settings panel over to the right. When we hover over the settings, they’ll pop out smoothly, with a simple CSS3 transition.

    The one very important point is that we’re setting a height on #table. This is required by the DataGrid class we’ll be using. The other thing to note is that we’re setting .dijitTextBox to have a width of 100%.

    Of course, this goes in that style.css file we linked up:

    body {
      margin: 40px 0;
      padding: 0;
      font: 14px/1.5 sans-serif;
      overflow: hidden;
      background: #ccc;
    }
    #main {
      border: 1px solid #474747;
      width: 940px;
      margin: auto;
      padding: 10px;
      background: #fff;
    
      -webket-border-radius: 7px;
      -moz-border-radius: 7px;
      border-radius: 7px;
    }
    #settings {
      padding: 20px 30px;
      width: 240px;
      background: #ececec;
      z-index: 10;
      border: 1px solid #474747;
    
      -webkit-border-radius: 7px 0 0 7px;
      -moz-border-radius: 7px 0 0 7px;
      border-radius: 7px 0 0 7px;
    
      -webkit-transition: right 0.3s ease;
      -moz-transition: right 0.3s ease;
      -o-transition: right 0.3s ease;
      -ms-transition: right 0.3s ease;
      transition: right 0.3s ease;
    
      position: absolute;
      right: -270px;
    }
    #settings:hover {
      right: -1px;
    }
    .dijitTextBox {
        width: 100%;
    }
    #table {
      margin-top: 20px;
      height: 600px;
    }
    
    Power It: The JavaScript

    Now, open that script.js file we linked to in our HTML. We’ll start by require-ing the functionality we need:

    dojo.require('dijit.form.Button');
    dojo.require('dijit.form.TextBox');
    dojo.require('dijit.form.CheckBox');
    dojo.require('dojo.io.script');
    dojo.require('dojox.grid.DataGrid');
    dojo.require('dojo.data.ItemFileReadStore');
    

    You probably aren’t familiar with the last two “classes” we’re pulling in. dojox.data.DataGrid is the interactive table we’re going to be using. The last, dojo.data.ItemFileReadStore, is one of Dojo’s many data stores. Really, it would take a whole tutorial to properly explain data stores, but we’ll cover enough to use them in our project today. For now, just know that our DataGrid takes a data store—in our case, an ItemFileReadStore—as its data source, and that’s why we’re using them.

    Of course, we’ll want to start performing a few actions once these modules have been loaded. Therefore, let’s wrap most of our code with this:

    dojo.ready(function () {
    
    });
    

    Other than two functions outside of this, all our code will be in here. Let’s get started with a few variables.

    var
    checks = dojo.query('input[type=checkbox]').map(function (el) {
        return new dijit.form.CheckBox({ checked: true, value: el.value}, el);
    }),
    

    At first glance, you might think that checks will be a NodeList of the checkboxes. However, notice that we’re using the map method to turn each regular old text box into the a Dijit checkbox. So, checks will be an array of checkbox widgets. In our options hash, we’re checking the checkboxes, and setting the value to the value attribute on the element; for some reason, the widget class doesn’t take that by default. Of course, we’re saving references to these widgets in an array, because we’ll need to access them later, to see, which boxes are checked.

    structure = [
        { field: 'title', name: 'Title', width: '650px' },
        { field: 'creator', name: 'Author', width: 'auto' },
        { field: 'pubDate', name: 'Date', width: 'auto' }
    ],
    

    Next up is a structure. This is the structure for our DataGrid table: each object in the array will be a column in our table. The field property maps to the data we’ll have, so the DataGrid will know what to put where. The name is the human-friendly column header. The width is the width of the column.

    Now, we come to the grid itself:

    grid = new dojox.grid.DataGrid({
        sortInfo: '-3',
        structure: structure,
        query: { title: '*' }
    }, 'table');
    grid.queryOptions = {ignoreCase: true};
    

    We’re setting three properties on out DataGrid instance. The first, sortInfo, says that we want to sort out rows by the third column; the - means order should be descending. Recall from our structure variable that the third column is the date the tutorial was published: so, out table will be sorted with the most recent tutorial at the top. Of course, the grid doesn’t know about this structure yet, so we inform it with the structure property. Finally, we set the query. This is important: it limits the rows from our data store that appear in the table. For example, if our query object was { creator: 'J*' }, only rows whose creator field starts with “J” would appear. In our case, we’re defaulting to all rows; we’ll look at how to change this later.

    Finally, we’re passing the id of the element that should house the DataGrid as second parameter to our constructor. After that, we’re setting the queryOptions object; we don’t want queries to be case sensitive, so we’ll tell our widget to ignoreCase.

    Excellent! Now, let’s prepare for some actions. When we type in out text box, we want the list of tutorial displaying to be filtered (yes, I know we actually don’t have any tutorials displaying yet, but we’ll get there).

    filterBox.set('onChange', function () {
        grid.filter({
            title : '*' + filterBox.get('value') + '*'
        });
    });
    

    If you’ll recall, we set data-dojo-id='filterBox' when declaratively creating our Dijit text box, so that’s how we can use it here in our JavaScript. We’re setting it’s onChange handler, it’s a super-simple change: we just call the grid.filter method, passing it a query object. If, for instance, we type “Scr” into the text box, only tutorials whose titles match *scr * will be displayed. The nice thing here is that when we clear the text box, the titles will be filtered by **, which matches them all.

    We have two tasks left:

    1. Initially fill the table with data (when the page loads).
    2. Load only tutorials for the checked sites when the “update” button is pressed.

    To do these, we’re going to abstract some functionality into two helper functions. First, we have the getSites function; as you might have guessed, we’ll be using YQL to get the Tuts+ sites’ feeds. So, we’ll need to create a query, based on the sites’ whose boxes are checked. Here’s the format of the query:

    select creator, pubDate, title from rss where url in (URL1, URL2, ....)
    

    So, here’s our function:

    function getSites (checks) {
        var urls = [];
        dojo.forEach(checks, function (check) {
            if (check.get('checked') === true){
                urls.push('' [feeds.feedburner.com] + check.get('value') + ''');
            }
        });
        return 'select creator, pubDate, title from rss where url in (' + urls.join(', ') + ')';
    }
    

    It’s pretty simple, and I think you can see what’s going on: we pass in the array of check box widgets, which then gets looped over. If the box is checked, we’ll create a url for it and push it into an array. We create the final YQL query by concatenating a few string and making use of the array join method.

    That was easy enough, but this next method is a bit more complex.

    function getTuts (query) {
        return dojo.io.script.get({
            url : 'http://query.yahooapis.com/v1/public/yql',
            content: {
                q: query,
                format: 'json'
            },
            callbackParamName: 'callback'
        }).then(function (data) {
    
        });
    }
    

    We start by accepting one parameter: the query. So, first, we set up our YQL call via dojo.io.script.get, as you’ve seen before (We’re not doing any caching of these request, just to keep things a little simpler). We’re using the dojo.Deferred method then to register our own callback here. But notice something else, right at the top: return. This will actually return a new dojo.Deferred object, that we can call a then method on. This is an alternative to accepting a callback function.

    But before we get to all that, we have to handle our own deferred callback. Here’s how that starts:

    var items = data.query.results.item,
    typemap = {
        'Date' : {
            deserialize: function (value) {
                var date = new Date(value),
                month = date.getMonth(),
                day  = date.getDate();
    
                month = month < 10 ? '0' + month : month;
                day  = day < 10 ? '0' + day : day;
                return date.getFullYear() + '-' + month + '-' + day;
            }
        }
    };
    

    Hey, come back: it isn’t that bad. You’re cool with bringing that long YQL object path down to just items, but don’t let the typemap scare you. This is simply an object of special types that we’re using in our DataGrid. In this case, we’re creating a Date type so that we can format our dates appropriately. While there can be other properties, we’re only using the deserialize one, which is a function take receives the raw value from the store (in our case, a date string), and outputs the format that will be displayed in our table. In our case, we’re simply formatting the date as YYYY-MM-DD.

    Next, we have to make some simple changes to the data that we got back from YQL:

    for ( var i = 0; items[i]; i++ ) {
        items[i].creator = (typeof items[i].creator === 'string') ? items[i].creator : items[i].creator.content;
        items[i].pubDate = { _value: items[i].pubDate, _type: 'Date' };
    }
    

    The creator value is usually the author’s name; however, for some of the feeds, we actually want creator.content. Our first line takes care of that.

    The second line is important: remember that typemap we created? We can tell our grid to use a specific type this way: We change our pubDate property from the date string to an object: that object has two properties: _value is the value for the field, while _type is the data type to use.

    Finally, let’s create our data store:

    return new dojo.data.ItemFileReadStore({
        data: { items: items },
        typeMap: typemap
    });
    

    It’s pretty simple, in our case: the data property takes an object, where items is our data; then, we also hand it our typemap. You might think returning this is pointless, because this is a dojo.Deferred’s callback function, and we’re not assigning it to anything. But remember, we’re returning a new dojo.Deferred object, and this data store will be passed to a callback function used on that object.

    If you’re confused, a simple example will clear that up. Back up in our dojo.ready call, let’s start with what happens when the “Update” button is clicked:

    update.set('onClick', function () {
    
        getTuts(getSites(checks))
            .then(function (data) {
                grid.setStore(data);
            });
    
    });
    

    We’re setting the onClick attribute for our update Dijit button. We first getSites, and pass that query to getTuts. Since that returns a dojo.Deferred object, we pass our callback function to its then method. We can use grid.setStore to refresh the DataGrid with new data.

    Finally, when the page loads, we’ll do very:

    // initially fill table
    getTuts(getSites(checks))
        .then(function (tutsdata) {
            grid.set('store', tutsdata);
            grid.startup();
        });
    

    Notice that we call grid.startup(); this is required to setup the UI; without this, nothing would show up on our page.

    Admire It: The Finished Product

    Nice job! Here’s our finished project:

    The Final Project, 1 The Final Project, 2 Conclusion

    Well, that brings us to the end of our “Dig into Dojo” session; I hope it has inspired you to really get into this incredibly library.

    But this isn’t the end of Dojo tutorials here on Nettuts+; far from it, if I have anything to do with it! You’ve all had some great suggestions in the comments on the others posts; keep ‘em coming and thank you so much for reading!


  • Permalink for 'An In Depth Overview of HTML5 Multimedia and Accessibility'

    An In Depth Overview of HTML5 Multimedia and Accessibility

    Posted: January 4th, 2012, 5:14pm MST by Ian Devlin

    In this tutorial, you’ll learn how HTML5 helps to provide you with several ways of presenting your media content to users. As a result, you’ll increase the availability of your media to users with different
    needs and requirements, making it more accessible.

    This tutorial comes courtesy of the recently released HTML5 Multimedia book.

    Media and Potential Accessibility Issues

    I’d strongly encourage you to think about making your content accessible…

    When thinking about the users who will be attempting to view your media content, you might make a number of assumptions:

    • Users will view your content on a desktop, laptop, tablet, or phone.
    • Users will have some way of listening to the audio of your content, be it via
      headphones or speakers.
    • Users will be able to understand the language in which you deliver the media.
    • Users will be able to successfully download and play your media.

    All are fairly reasonable assumptions to make and most likely cover the vast majority of users who will want to access your content. You may be happy with your content being accessible to these users only; after all, majority rules, doesn’t it?

    Well, I’d strongly encourage you to think about making your content accessible to users who do not fall into the category of the assumptions just listed. Who are these viewers? They include:

    • Users who have a sensory impairment that prevents them from listening to your content’s audio or viewing video.
    • Users who don’t understand the language the media is delivered in.
    • Users who use devices such as screen readers and/or use keyboards to access
      media content on the web.

    • Users who can’t successfully hear or view your content due to the environment they are in or because of device limitations.

    Because most media content will usually include some audio, not being able to hear or understand the audio it contains is quite a showstopper in comprehending the content’s message and information.

    Equally, being able to access the content through a device such as a screen reader but then not being able to actually use it due to the media controls not being properly set up (e.g., for keyboard access) would annoy any user.

    You’ll explore the accessibility of media controls later in this tutorial. You’ll also take a look at what HTML5 brings to the table in an attempt to address the issue of users being unable to see, hear, or understand your media content. But first, let’s take a quick look at what led to HTML5’s attempt to confront this accessibility problem — SRT.

    A Brief Look at SRT

    SRT is an existing file format for containing video subtitles and their timings.

    SRT is an existing file format for containing video subtitles and their timings. An SRT file is often produced automatically using a Windows program called SubRip, which uses optical character recognition (OCR) to obtain the subtitles from the specified video source.

    The SubRip file format is a basic text file with the .srt file extension that follows a basic format:

    • Subtitle number
    • hh:mm:ss,msmsms —> hh:mm:ss,msmsms
    • Subtitle Text (one or more lines)

    Each subtitle set begins with a unique subtitle number, followed by the start and end timestamps of the timing the subtitle represents on a separate line, which is then followed by one or more lines of subtitle text. Each subsequent subtitle set is separated by a blank line. The timestamp format hh:mm:ss,msmsms specifies the hours, minutes, seconds, and milliseconds of the time in question. Note that the millisecond separator is a comma.

    An example of such a file follows:

    1
    00:00:10,500 --> 00:00:13,000
    Elephant’s Dream
    2
    00:00:15,000 --> 00:00:18,000
    At the left we can see...
    

    The SRT file format is quite popular and is often the format that video subtitles are released in. This file format isn’t currently used as part of HTML5’s attempt to tackle accessibility, although it was to begin with but has now been extended and given a new name, WebVTT.

    Introducing WEBVTT

    WebVTT (Web Video Text Tracks) is a file format that is intended for marking up external text tracks. It was initially part of the WHATWG and the W3C HTML5 specifications, and was an extension of SRT called WebSRT (Web Subtitle Resource Tracks). But the W3C was concerned that HTML5 should be independent of any chosen captioning format, and therefore, it was removed from that specification.

    Note: even though the SRT in WebSRT stands for subtitle resource Tracks, the original acronym didn’t stand for anything and merely reflected
    the file extension used. WebSRT is a “backronym”; subtitle resource Tracks was shoe-horned into the three letters to actually mean something.

    The presence of WebVTT is currently one major difference between the WHATWG HTML5 specification and the W3C specification.

    Although no browser currently supports WebVTT, major browser vendors have indicated that they will implement support for WebVTT in the future. This indication has led to the creation of a WebVTT Working Group Charter at the W3C, whose mission is to:

    “create a W3C specification starting from the WHATWG WebVTT (Web Video Text Tracks) language and solidify it through the creation of a WebVTT test suite and through the creation of semantic mappings of other subtitle formats to or from WebVTT in order to facilitate browser implementation and market adoption.”

    This promise of vendor support will hopefully in turn eventually lead to a formal standardization of the WebVTT specification at the W3C. With browser support and that of the W3C, you can be sure that WebVTT is here to stay and is destined become the de facto method of marking up text tracks within audio and video content on the web.

    So what is the WebVTT file format and how can it help you make your content accessible? Read on.

    What Can WebVTT Do?

    The WebVTT format also allows you to provide a textual description of the video content

    You use the WebVTT file format to define WebVTT files. One of the main uses of these files is to provide subtitles to video content, although the format of the file doesn’t indicate what its contents are used for.

    The WebVTT format also allows you to provide a textual description of the video content, which can then be used by various accessibility devices (which might read the descriptions out loud) to describe the content of the video to those who cannot see it. You inform the browser of the WebVTT file and of its purpose using HTML markup; you’ll find out how this is done later in this tutorial, when you read about the track element.

    Let’s take a look at the WebVTT file format in more detail.

    WEBVTT File Format

    A WebVTT file is a simple text file with the .vtt extension that needs to follow a specified format, which you will look at shortly. The file must be encoded as UTF-8 and labeled with the MIME type text/tt. The line terminators within the file can only be \r (a carriage return), \n (a new line), or \r\n (a carriage return followed by a new line). It must also contain a WebVTT file body, which consists of the following:

    WEBVTT
    [cue]
    [cue]
    ...
    

    The WEBVTT string at the top identifies the contents as a WebVTT file and must then be followed by at least one blank line, which is then followed by any number of cues, each of which is separated by a blank line.

    A cue is defined as:

    [idstring]
    [hh:]mm:ss.msmsms --> [hh:]mm:ss.msmsms [cue settings]
    TextLine1
    TextLine2
    ...
    

    idstring is a unique identifier within the file that identifies the cue. It can consist of one or more characters that do not contain the substring “—>” or any of the line terminators mentioned earlier. [hh:]mm:ss.msmsms —> [hh:]mm:ss.msmsms indicates the timestamp range within the video file that the cue is specified for. [hh:]mm:ss.msmsms is a simple timestamp; the hour portion is optional (depending on the length of the video in question of course).

    Note: The millisecond separators are full stops, not commas as in SRT.

    cue settings allow you to specify the positioning of the text; you’ll read more about them in a moment.

    TextLineN is the actual text in the video file that the timestamp range in the cue represents. The content can be all in one line or presented in any number of separate lines. Any lines will be contained within the cue until a blank line is encountered, which indicates the end of that particular cue.

    Let’s take a quick look at a sample WebVTT file containing two timestamp ranges:

    WEBVTT
    1
    00:00:10.500 --> 00:00:13.000
    Elephant’s Dream
    2
    00:00:15.000 --> 00:00:18.000
    At the left we can see...
    

    This example defines two cues: The first one starts 10 seconds and 500 milliseconds into the video and ends at 13 seconds in, and the second one starts 15 seconds into the video and ends 3 seconds later. The subtitle text for each cue is given below its timestamp.


    How a subtitle cue might appear on a video with no cue settings specified.

    Using cues is relatively straightforward, and you can see how the file can be built up with a number of cues to cover the length of an entire video. You can also specify some settings on a per-cue basis. These affect the positioning of the cue on the related video. You can have a number of setting values, and a cue setting can contain one or more values, each one separated by a space. The various settings are listed below:

    If no cue settings are specified, the text will align to the middle, at the bottom of the video frame.

    Let’s add some of these settings to the example used earlier:

    WEBVTT
    1
    00:00:10.500 --> 00:00:13.000 A:start Elephant’s Dream
    2
    00:00:15.000 --> 00:00:18.000 A:end L:10% At the left we can see...
    

    The text in the first cue will be aligned to the left of the video (much the same way as the CSS rule text-align:left works).


    How a cue subtitle might appear on a video with a cue setting of A:start.

    The second cue has two settings applied to it: The text will be aligned to the end of the line (similar to text-align:right in CSS) and will be placed on the line 10 percent down from the top of the video.


    How a cue subtitle might appear on a video with a cue setting of A:end L:10%.

    In addition to specifying cue settings for controlling the positioning and alignment of cue text, there are also a number of inline styles that you can apply to the text. These look and act the same as HTML elements. They contain a start and an end tag, and the formatting is applied to the text in between.

    Let’s extend the example further and use some of the text tags to format the cue text:

    WEBVTT
    1
    00:00:00.000 --> 00:00:14.999 Elephant’s <c.dream>Dream</c>
    2
    00:00:15.000 --> 00:00:18.000 A:end L:10% At the <i>left</i> we can <b>see</b> ...
    3
    00:00:18.167 --> 00:00:22.000
    At the right <00:00:20.000>we can see the...
    

    With the first cue, a class name of “dream” has been added, a style for which you can define within your HTML file in the same way as you’d create any CSS style rules.


    Video-cue text with a style defined using CSS and the WebVTT c text tag.

    Note: any CSS class names that you might use within your WebVTT subtitle definitions can be defined in the containing HTML file or an external css file in the same way as you’d specify any other css classes.

    The second cue now has tags that will display the word “left” in italics and “see” in bold type.


    Video-cue text that uses the i and b text tags.

    An extra cue is added to this example to show how the timestamp is used to display the text “karaoke style.” When the cue starts, the words “At the right” will appear first. Then the text “we can see…” will be displayed at the appropriate time- stamp (Figure 8.6).

    Note: if you want the characters &, to appear in the text of a video cue, you need to escape them with &amp; &lt; and &gt; respectively.


    This video-cue text shows the text in stages.

    WEBVTT Future Developments

    It’s worth noting that because the WEBVTT file format is relatively new to the specification and with the recent creation of the WEBVTT Working Group Charter, additions to the specification are likely.

    If you want to keep abreast of any changes to this specification, keep an eye on the Working Group Charter’s site and the blog of Silvia Pfeiffer who is currently editor of the Working Group Charter. Silvia also blogs regularly about HtML5-related accessibility topics.

    You can see how the complete narrative in a video could be added to a WebVTT text file with formatting and styling.

    But how do you connect a WebVTT file with a particular video? This is where the new HTML5 track element steps in.

    The Track Element

    The track element is one of the new HTML5 elements. Its purpose is to allow external text tracks to be specified for media elements, such as audio and video. The track element does not represent anything on its own and must be used in conjunction with, and as a child of, a media element.
    The track element takes a number of attributes, which are listed below:

    The following example shows how a track element might be used in connection with a video to provide subtitles:

    <video controls>
        <source src="video-file.mp4" type="video/mp4">
        <source src="video-file.webm" type="video/webm">
        <track src="en.vtt" kind="subtitles" srclang="en" label="English p subtitles">
    </video>
    

    The track element in the example specifies that the en.vtt file contains English subtitles (as the label says) in the English language (srclang is set to en) of kind: subtitles for the surrounding video element. From this example, you can see just how easy it would be to add a second subtitles file that might be in a different language:

    <video controls>
        <source src="video-file.mp4" type="video/mp4">
        <source src="video-file.webm" type="video/webm">
        <track src="en.vtt" kind="subtitles" srclang="en" label="English p subtitles" default>
        <track src="de.vtt" kind="subtitles" srclang="de" label="German p subtitles">
    </video>
    

    Here, another track definition has been added, pointing to a de.vtt file that contains German subtitles; srclang is set to de.

    Notice that the default attribute has been added to the English subtitles definition, marking it as the default subtitle set to be used if the user doesn’t specifically select one.

    If you wanted to extend the example further and add a chapter listing in each language (English and German), you would do the following:

    <video controls>
        <source src="video-file.mp4" type="video/mp4">
        <source src="video-file.webm" type="video/webm">
        <track src="en.vtt" kind="subtitles" srclang="en" label="English p subtitles" default>
        <track src="de.vtt" kind="subtitles" srclang="de" label="German p subtitles">
        <track src="ch-en.vtt" kind="chapters" srclang="en" p label="English chapter listing" default>
        <track src="ch-de.vtt" kind="chapters" srclang="de" p label="German chapter listing">
    </video>
    

    Once the various WebVTT files have been created with the content you want, it’s a fairly simple process to add them to the appropriate video.

    Everything you’ve just read about WebVTT all sounds quite promising; however, even though some browsers support the track element to some degree, currently no browser supports the WebVTT file format.

    Note: at the time of this writing, the Webkit (which chrome and safari are based on) nightly build has some support for WebVTT.
    All is not lost, though, because several JavaScript libraries are available that enable you to start using WebVTT today.

    Using WEBVTT and the Track Element Now

    A small number of browsers support the track element to some degree. The latest WebKit browsers (e.g., Chrome 12 and Safari 5.0.5) recognize the element but don’t do anything with it. The current version of Firefox (5) parses the element but also does nothing with it. Although these browsers are taking steps in the right direction, they don’t really help you implement WebVTT now.

    Fortunately, four JavaScript libraries allow you to define the track element with WebVTT files in your web document that will deliver what you want:

    • J Playr – Supports: subtitles, chapters, some cue settings Browsers: Opera, Chrome, Safari, Firefox
    • LeanBack Player – Supports: subtitles
      Browsers: All major browsers with fallback to Flash if required
    • Captionator – Supports: subtitles, all cue settings Browsers: Opera, Chrome, Safari, Firefox, IE9
    • MediaElementJS – Supports: subtitles (timing format uses SRT format)
      Browsers: All major browsers with fallback to Flash if required
    SRT Support

    Although only a handful of JavaScript players support WEBVTT, a number of them support SRT subtitle files. those players that support WebVtt (Playr, LeanBack, Captionator, and MediaElementJS) also support SRT in addition to the following that provide support for SRT only:

    None of these libraries offer support for all the different values for the kind attribute of the track element: They only support the subtitle value (Playr also supports the chapter value). Because subtitles are one of the most important values, it’s a good start. This support also allows you to begin adding subtitles to your videos now and seeing them in action.

    Let’s look at how you might use the Playr JavaScript library to add subtitles and chapters to a video.

    Playr Example

    To use Playr, you must first download it from the Playr download website. Once downloaded, you need to include the Playr CSS file and JavaScript in your web document:

    <link rel="stylesheet" href="playr.css" />
    <script src="playr.js"></script>
    

    When defining your video, you simply add the CSS class “playr_video” to your video element, and Playr will automatically be used for that video.

    A sample of Playr with a short animated film called Elephant’s Dream (© copyright 2006, Blender Foundation, Netherlands Media Art Institute, www.elephants dream.org) is available here.

    The code used for this video is as follows:

    <video class="playr_video" preload="metadata" controls p poster="elephants-dream.title.jpg">
       <source src="elephants-dream-medium.mp4" type="video/mp4">
       <source src="elephants-dream-medium.webm" type="video/webm">
       <track label="English subtitles" kind="subtitles" srclang="en" p src="elephants-dream-subtitles-en.vtt" default>
       <track label="German subtitles" kind="subtitles" srclang="de" p src="elephants-dream-subtitles-de.vtt">
       <track label="Chapters" kind="chapters" srclang="en" p src="elephants-dream-chapters-en.vtt">
    </video>
    

    The Playr video player with Elephant’s Dream.

    Also, three track elements are used to point to English and German subtitles, and English chapters.

    Note: Playr currently doesn’t support multiple chapter files or the default attribute but will do so in a future release.

    Playr’s menu allows viewers to choose English and German subtitles plus chapters.

    Subtitles have been placed 6 percent from the top (using L:6%) and bolded with <b>.

    The same video with German subtitles chosen.

    A sample of how chapter selection looks in Playr.

    Playr is a handy video player, and its ability to display subtitles and chapters is very useful. Support for the other kinds of track element contents are planned, so like other available video players, it will keep on improving.

    Another important part of making media content accessible are the controls. Next, you’ll learn how accessible the default players are and what can you do to make your own custom controls more accessible.

    Media Controls and Accessibility

    It’s quite important for accessibility that the media controls can be accessed from the keyboard.

    As mentioned earlier, it’s quite important for accessibility that the media controls can be accessed from the keyboard. Browsers have their own set of controls for media elements, but how accessible are they from the keyboard? Unfortunately, at the moment, the answer is not very. Opera seems to be the only browser whose default control set is immediately accessible from the keyboard. You can easily tab from one control to the other, use the Return key to toggle the Play/Pause button, and use the arrow keys to control the seek bar and volume control.

    So, if you want to make your media content fully accessible across all modern browsers, you need to implement your own custom controls.

    Improving the Accessibility of Custom Controls

    You’ve already used the HTML button element to implement nearly all of the controls. Using button elements immediately increases the accessibility of the controls because the button element is automatically accessible from the key- board. That fact alone makes the custom controls keyboard accessible. Because the controls are also listed in the same order as they appear on the player, their tab order is also pretty much in the required logical order. However, you might want to change the tab order of the progress bar and the Play/Pause button. Most likely, users would want to play the video first, so that button should be the first control that they can access.

    You can specify the tab order of HTML controls using the tabindex attribute. The order specified by this attribute is the one that the browser will tell the key- board to follow. So you apply a tabindex of 1 to the Play/Pause button and 2 to the progress bar, and then apply subsequent tabindexes in the order in which they appear in the source:

    <div id="controls">
        <div id="progressBar"><span id="played" tabindex="2"></span></div>
        <button id="playpause" alt="play" title="play" tabindex="1">play</button>
        <button id="stop" alt="stop" title="stop" tabindex="3">stop</button>
        <button id="rewind" alt="rewind" title="rewind" tabindex="4">&laquo;</button>
        <button id="ffwd" alt="fast forward" title="fast forward" tabindex="5">&raquo;</button>
        <button id="volumeDown" alt="decrease volume" title="-" tabindex="6">button>
        <button id="volumeUp" alt="increase volume" title="+" tabindex="7">+</button>
        <button id="mute" alt="mute" title="mute" tabindex="8">mute</button>
    </div>
    

    In this code listing, the onclick() events have been omitted for brevity.

    The Range Element

    The range element would be ideal for use as a progress bar if support was better because it too automatically provides keyboard accessibility, and the seek bar would work via the keyboard (the up and down keys would toggle the seek when the element has focus) without any further requirements.

    Because the buttons provide keyboard accessibility automatically, all you need to tackle now is the progress bar, which uses a div and a span.
    You need to add an event listener for the keypress event, which fires when a key is pressed, and then act on it. You’re interested in just a key press on the progress bar, so the event is added to the progress bar only:

    var progressBar = document.getElementById(“progressBar");
    progressBar.addEventListener(“keypress", function(e) {
        checkKey(e.keyCode);
    }, false);
    

    The function that is called when a key press is detected is called checkKey() with a parameter indicating the numeric code of the key that was pressed:

    function checkKey(code) {
        if (code == 38) { // up arrow key
            video.currentTime += 0.5;
        }
        else if (code == 40) { // down arrow key
            video.currentTime -= 0.5;
        }
    }
    

    The checkKey() function simply checks the key code to see if it’s the up arrow key (code 38) or the down arrow key (code 40). Depending on which key it is, the video’s currentTime attribute is increased or decreased by 0.05 (an arbitrary time value, but it seems a good step to move the video forward or backward by).

    And that’s it. The progress bar’s seek capabilities can now be accessed via the keyboard with the up and down arrow keys when it’s in focus. The end result renders your media custom controls a lot more accessible than they would have been.

    Wrapping Up

    With regard to accessibility, HTML5 has advanced and expanded from its initial definition of the WebSRT file format to WebVTT. With browser vendors planning to support this format, a new W3C Working Group was formed with the intention of formalizing the WebVTT specification for browsers to start supporting. So hope- fully, browser support is only a matter of time.

    Although native support is currently patchy, you can use existing JavaScript libraries to add subtitles to your videos now. These libraries will undoubtedly increase their functionality and capabilities in the future.

    Overall, accessibility is a goal you should be thinking about when serving multimedia content to your users. The more users who can access your content the better, right?

    Be sure to visit the HTML5 Multimedia website, or buy the book to learn more!


  • Permalink for 'Create a Scalable Widget Using YUI3: Part 4'

    Create a Scalable Widget Using YUI3: Part 4

    Posted: January 3rd, 2012, 3:30pm MST by Dan Wellman

    Welcome to the last part in the YUI3 widget tutorial; although we’ve actually finished building the widget, we’re going to look at how easy it is to add extra functionality to a widget without having to re-write it.

    Let’s get started right away!

    If the functionality is required for a particular module it’s an extension. Otherwise, it’s a plugin.

    There are two ways of adding functionality – extensions and plugins. The difference between them is subtle but essentially boils down to whether or not the functionality is required or optional. If the functionality is required for a particular module it’s an extension, if the functionality is optional, it’s a plugin.

    The plugin that we’ll add will handle the paging functionality for our widget; maybe not all developers will want to add paging, or some may want to add it to some instances of the widget but not others. Adding the functionality makes sense when viewed in this way – if the developer wants to make use of paging, they can use the plugin, but we don’t force developers to run all the extra code that is required if they aren’t going to use it.

    Creating a Plugin

    The process for creating a plugin is similar to that for creating a widget, so many of the constructs that we’ll use here should be familiar from the previous parts of this tutorial. Just like when creating a widget, we use YUI’s add() method as a wrapper for our code:

    YUI.add("tweet-search-paging", function (Y) {
    
    },
    • The name of the plugin (the name that developers will use to initialize the plugin) is the first argument of the method
    • an anonymous callback function is the second parameter. The function receives a reference to the current YUI instance.
    • the third argument is the version number of the plugin and
    • the fourth is an object listing any dependencies required by the plugin.
    The Constructor and Namespace

    Just like with our widget, we need to add a constructor for our plugin so that it can initialised and set the namespace for it. Unlike our plugin, setting the namespace is required. Add the following code within the anonymous function we just added:

    var Node = Y.Node;
    
    function TweetSearchPaging(config) {
        TweetSearchPaging.superclass.constructor.apply(this, arguments);
    }
    
    Y.namespace("Plugin.DW").TweetSearchPaging = TweetSearchPaging;

    We start by caching references to any frequently used YUI resources, which in this case is just the Node utility. We add the constructor for the plugin in the same way as before; the TweetSearchPaging plugin method is defined as a function that accepts a configuration object. The class is initialized using the apply() method of the superclass’s constructor.

    We set a namespace for our plugin, but this time the namespace is attached to the Plugin namespace as opposed to the YUI object.

    Static Properties

    As before there are some static properties we should set for our plugin, these are as follows:

    TweetSearchPaging.NAME = "tweetsearch-paging";
    
    TweetSearchPaging.NS = "paging";
    
    TweetSearchPaging.ATTRS = {
    
        origShowUIValue: null,
    
        strings: {
            value: {
                nextLink: "Next Page",
                prevLink: "Previous Page"
            }
        }
    };
    
    TweetSearchPaging.PAGING_CLASS = Y.ClassNameManager.getClassName(TweetSearchPaging.NAME, "link");
    
    TweetSearchPaging.LINK_TEMPLATE = "<a class={linkclass} href={url}>{linktext}</a>";

    The name of the plugin is set with the NAME property, and also the NS property, which can be used to refer to the plugin from the host (the host is the widget or module that the plugin is connected to) class.

    We can also use the ATTRS property to set any configuration attributes for the plugin. These attributes also use the YUI3 Attributes module, just like the widget attributes, and can be used in the same way. The attributes we define are the origShowUIValue attribute, which the plugin will set to store whether the search UI was initially displayed in the widget when the plugin is initialized. We also store the text strings used by the plugin, again for easy internationalization.

    We manually generate a class name for the elements that we’ll create using the classNameManager, and define the template that our paging links will be created with. As there is only a single class name and template we don’t need to worry about using a for loop.

    Extending the Plugin Base Class

    Just like we did when creating the class for our widget, we use YUI’s extend() method to extend an underlying module. In the case of a plugin, it’s the Plugin.Base class that we’re extending. The extend() method should appear as follows:

    Y.extend(TweetSearchPaging, Y.Plugin.Base, {
    
    });

    We pass in our plugin as the first argument to the extend() method, the class we’re extending as the second method and an object literal containing the functionality we’re adding.

    Life Cycle Methods

    Plugins also get access to several life-cycle methods that can be overridden to add custom code that the plugin will execute for us at appropriate times. We can make use of use the initializer and destructor life-cycle methods:

    initializer: function () {
    
        Y.StyleSheet("tweetSearchPagingBase").set(".yui3-tweetsearch-paging-link", { float: "right" });
    
        if (Y.one(".yui3-skin-sam")) {
            Y.StyleSheet("tweetSearchPagingSkin").set(".yui3-skin-sam .yui3-tweetsearch-paging-link", { marginLeft: "2%" });
        }
    
        var widget = this.get("host");
    
        if (!widget.get("showUI")) {
            this.set("_origShowUIValue", false);
            widget.set("showUI", true);
        } else {
            this.set("_origShowUIValue", true);
        }
    
        this.afterHostEvent("tweetsChange", this._afterHostTweetsChange);
    },
    
    destructor: function () {
        Y.StyleSheet("tweetSearchPagingBase").unset(".yui3-tweetsearch-paging-link", "float");
    
        if (Y.one(".yui3-skin-sam")) {
            Y.StyleSheet("tweetSearchPagingSkin").unset(".yui3-skin-sam .yui3-tweetsearch-paging-link", "marginLeft");
        }
    
        if (!this.get("_origShowUIValue")) {
            this.get("host").set("showUI", false);
            Y.one(".yui3-tweetsearch-ui").remove();
        }
    },

    The initializer method will be executed when the plugin is initialized; in this method we first create the base style sheet our plugin needs. We could just include a separate CSS file, but as we only need a single style rule it makes sense to cut down on the number of files that any implementing developer needs to manage.

    We use YUI’s StyleSheet() method to create our new style sheet. This method accepts a single argument which is the name of the new style sheet. We then use the set() method to set the styles that we require. The set() method takes two arguments; the first is the selector we wish to target and the second is an object literal containing the styles that should be applied to the selector, which in this case is simply float: right.

    We then check whether the .yui3-sam-skin selector exists in the document; if it does, we then go ahead and create a skin style sheet for the plugin. If the sam skin is not in use, it is not worth creating any skin styles as the implementing developer will no doubt have custom styles that they may wish to apply.

    Next, we need to check whether the showUI attribute of the widget is enabled. We can get access to the host class that the plugin is attached to using the built-in host attribute, which we get using the get() method just like any other attribute. The showUI attribute of the widget must be enabled if the plugin is used, so if the attribute is not set originally we set it here.

    When using plugins we have the ability to detect and react to any of the host’s attributes changing. We add an attribute change-handler for the when the tweets attribute of our widget changes using the afterHostEvent() method. This method accepts two arguments; the first is the attribute to monitor, the second is the method to execute when the attribute changes.

    The destructor function is called when the plugin is destroyed; this method is used to tidy up after the plugin. Any changes to the page should be reversed, as well as any changes we make to the widget. The changes we make to the page that we have to undo are the addition of the style sheets, so this is what we do first. The style sheet styles can be removed using the unset() method; this method takes the selector to unset as the first argument and the styles to unset as the second argument.

    We then check whether the _origShowUiValue variable is set to true or false; if the variable is set to false we know we have to revert its value, so we set the attribute of the host back to false. If the value was changed and the UI was shown by the plugin, we hide it so that the widget is returned to its original state.

    Attribute Change-Handlers

    We only use a single attribute change-handling method in this plugin; the one that is called when the tweet attribute of the host changes. This method should appear as follows:

    _afterHostTweetsChange: function () {
    
        var widget = this.get("host");
    
        if (widget.get("tweets").next_page) {
            var nextPageUrl = widget.get("tweets").next_page,
                nextLink = Node.create(Y.substitute(TweetSearchPaging.LINK_TEMPLATE, {
                linkclass: TweetSearchPaging.PAGING_CLASS, url: [" [search.twitter.com] nextPageUrl, "&callback={callback}"].join(""), linktext: this.get("strings").nextLink }));
    
            if (this._nextLinkNode) {
                this._nextLinkNode.remove();
            }
    
            this._nextLinkNode = widget._uiNode.appendChild(nextLink);
    
            Y.on("click", Y.bind(this._getPage, this), this._nextLinkNode);
        }
    
        if (widget.get("tweets").previous_page) {
            var prevPageUrl = widget.get("tweets").previous_page,
                prevLink = Node.create(Y.substitute(TweetSearchPaging.LINK_TEMPLATE, {
                linkclass: TweetSearchPaging.PAGING_CLASS, url: [" [search.twitter.com] prevPageUrl, "&callback={callback}"].join(""), linktext: this.get("strings").prevLink }));
    
            if (this._prevLinkNode) {
                this._prevLinkNode.remove();
            }
            this._prevLinkNode = widget._uiNode.appendChild(prevLink);
            Y.on("click", Y.bind(this._getPage, this), this._prevLinkNode);
        }
    },

    We first store a reference to the host class once more as we’ll need to refer to it several times. We now need to determine whether or not there are paged results in the response from Twitter and whether there are previous or next pages of results. The cool thing about the response from twitter is that it will automatically maintain which page of results we are viewing if there are more results than the configured number of results per page.

    If there is another page of results after the current page, there will be a property in the JSON response object called next_page. Similarly, if there is a previous page of results, there will be a previous_page property. All we need to do is check for the presence of these properties and create next page and previous page links.

    The links are created using the template we stored earlier in the plugin class, and are given the generated CLASS_NAME. The next_page and previous_page response objects are obtained from Twitter using a URL with a special ID in the query string. When we create these new nodes, the URL provided in these properties is added to each link respectively. The links are appended to the searchUI node of the host, and click handlers are added for them. These click handlers point to a utility method called _getPage(). We’ll add this method next.

    Custom Prototype Methods

    Just like when creating the widget, we can add any number of custom prototype methods that are used to execute any custom code required by our plugin in response to user interaction or state changes. In this plugin, we only need to add a single method, which should appear as follows:

    _getPage: function (e) {
        var widget = this.get("host");
    
        e.preventDefault();
    
        widget._viewerNode.empty().hide();
        widget._loadingNode.show();
    
        widget.set("baseURL", e.target.get("href")),
    
        widget._retrieveTweets();
    
        Y.all(".yui3-tweetsearch-paging-link").remove();
    }

    First, we store a reference to the host class, and then prevent the paging link that was clicked being followed. We then remove any existing tweets in the widget’s viewer and show the loading node. Remember, each paging link (or whichever link exists if we are on the first or last page) will have the URL that retrieves the next (or previous) page of results, so we retrieve this URL from the link’s href and set the baseURL attribute of the widget. One this is done, we call the _retrieveTweets() method of our widget to request the next page. Finally, we remove the current paging links as they will be recreated if there are next or previous pages included in the new response object.

    Using the Plugin

    Now that we’ve created our plugin we can see how easy it is to use with our widget. We need to update our use() method to use our plugin, and call the plug() method before the widget is rendered:

    YUI().use("tweet-search", "tweet-search-paging", function (Y) {
        var myTweetSearch = new Y.DW.TweetSearch({
            srcNode: "#ts"
        });
        myTweetSearch.plug(Y.Plugin.DW.TweetSearchPaging);
        myTweetSearch.render();
    });

    The plug() method connects our plugin, which is accessible via the Plugin namespace and whatever namespace we specified when defining the plugin’s class. Now when we run the page, we should have paging links at the bottom of the widget:

    Nettuts+

    One of the features of our plugin (just like our widget) is easy internationalization; in order to provide strings for the plugin in another language (or override any attributes if a plugin), we can simply provide the configuration object as the second argument to the plug() method, e.g.:

    myTweetSearch.plug(Y.Plugin.DW.TweetSearchPaging, {
        strings: {
            nextLink: "Página Siguiente",
            prevLink: "Página Anterior"
        }
    });

    The paging link should now appear like so:

    Nettuts+ Wrapping Up

    In this part of the tutorial, we looked at how easy it is to create a plugin that can be used to enhance existing widgets or other modules. This is a great way of providing extra functionality that is not essential, which developers can choose to include if they wish. We saw that the structure of a plugin is similar to that of a widget on a smaller scale.

    In this example, the plugin was very tightly coupled to our widget; it wouldn’t be possible to use the plugin with a different widget for example. This does not have to be the case and plugins, as well as extensions can be much more loosely coupled to add or enhance functionality for a range of different modules.

    This now brings us to the end of the series on YUI3 widgets; I hope I’ve given some insight into the powerful mechanisms put in place by the library that enable us to easily create scalable and robust widgets that leverage the strengths of the library.

    Let us know what you think in the comments section below and thank you so much for reading!


  • Permalink for 'Introducing Nettuts+ Fetch'

    Introducing Nettuts+ Fetch

    Posted: January 2nd, 2012, 11:30am MST by Jeffrey Way

    In addition to producing various helpful apps for web developers, in 2012, we’ll also be commissioning and releasing smaller plugins and extensions. Today, I’d like to announce the first entry in this initiative: “Nettuts+ Fetch” – a Sublime Text plugin.

    The 20 Second Example
    Choose 720p for a clearer picture. The Dilemma

    Let’s say that you’re a fan of Normalize.css. Perhaps, you download it and save it to a snippet, or store the stylesheet, itself, in an assets folder. That way, for future projects, you only need to copy and paste.

    The only problem with this method – as we’ve all discovered – is that, if a few months have passed, it’s more than possible that the asset (in this case, Normalize.css) will have been updated by the creator. So your options are to either use the, now, out-dated version of Normalize, or, once again, return to the GitHub page and pull in a fresh copy. This all seems tedious.

    The Solution

    Created by Weslly Honorato, Nettuts+ Fetch is the solution to our dilemma.

    I thought to myself: “What if there was a plugin that would automatically pull in the latest copy of a file, simply by typing a keyboard shortcut. It’ll perform a curl request to your specified URL (saved away for future use), and allow you to rest assured that, for all new projects, you’re using the latest copy of a particular asset.

    Created by Weslly Honorato, Nettuts+ Fetch is the solution to our dilemma.

    Installation Instructions Nettuts+ Fetch

    While you can manually download Nettuts+ Fetch from GitHub, the easiest way to set it up is through Package Control (which all ST2 users should be using). Once you’ve installed package control, press ctrl+shift+p (Windows, Linux) or cmd+shift+p (OS X), and type “Package Install.” Next, search for “Nettuts+ Fetch,” press enter, and you’re done. Simple.

    Usage

    You’ll only use two commands, when working with Fetch. First, we need to save some file references. Again, bring up the command palette, and search for “Fetch.” For now, choose “Manage Remote Files.”

    Manage Remote Files

    What’s great about Sublime Text 2 is that configuration is incredibly simple. To assign references to online asset files, we only need to create an object, like so (don’t worry; one will be pre-populated for you, after installation):

    So, to pull in the latest copy of jQuery (if you don’t want to use a CDN):

    {
    	"files":
    	{
    		"jquery": " [code.jquery.com] 	}
    }
    
    Packages

    Even better, I can pull in entire packages, or zip files. What if we want to start a new project, using HTML5 Boilerplate? In that case, we add the reference to the “packages” object.

    {
    	"files":
    	{
    		"jquery": " [code.jquery.com] 	},
    	"packages":
    	{
    		"html5-boilerplate": " [github.com] 	}
    }
    
    Fetch, Boy

    Now that we have a package and script saved (add as many as you like), we can pull them in by using the Fetch command. Pull up the command palette – ctrl+shift+p (Windows, Linux) or cmd+shift+p (OS X) – type “Fetch,” and make your selection.

    Choose HTML5 Boilerplate from the list, give it a few seconds, and, bam, you’re ready to go with the latest release.

    Pretty sweet, huh? I hope you like it! Thanks again to Weslly Honorato for building it for us.


  • Permalink for 'Best of Tuts+ in December 2011'

    Best of Tuts+ in December 2011

    Posted: January 2nd, 2012, 8:32am MST by David Appleyard

    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
    • Create a Festive Cocktail Using Photoshop’s 3D Capabilities Create a Festive Cocktail Using Photoshop’s 3D Capabilities

      For many of our readers, this time of year is filled with family, friends, and celebration. In this tutorial, we will explain how to create a festive cocktail using Photoshop’s 3D capabilities just in time for your New Year’s celebrations. Let’s get started!

      Visit Article

    • Create a Dark, Conceptual Photo Manipulation With Stock Photography Create a Dark, Conceptual Photo Manipulation With Stock Photography

      In this tutorial we will be teaching how to integrate elements from different sources to create a realistic photo manipulation with dark and conceptual elements. You will learn some lighting and blending techniques as well as some interesting post-production tips. Let’s get started!

      Visit Article

    • Create High-End Action Figure Packaging – Tuts +  Premium Tutorial Create High-End Action Figure Packaging – Tuts + Premium Tutorial

      With collectables, the packaging of the product is often as important as the craftsmanship of the product itself. In this two-part Tuts+ Premium tutorial, author Tim Kyde will explain how to create packaging for a high-end 1/6 scale action figure. Part 1 of this tutorial will explain how to shoot your own photography and create a print-ready outer sleeve and inner packaging for our action figure. This tutorial is available exclusively to Tuts+ Premium Members — Join Now to get started!

      Visit Article

    • Nettuts+ — Web Development Tutorials
    • Wrangling with the Facebook Graph API Wrangling with the Facebook Graph API

      Have you ever wanted to learn how to make your applications more social with Facebook? It’s much easier than you think!

      Visit Article

    • How We Built Gradient From Idea to Market: How We Built Gradient

      Retracing the steps you’ve taken is a helpful way to understand how well you’ve executed your vision – whatever that might be. What could you have done better? What should have been avoided? Today, I’ll share what we’ve learned (and are still learning) while crafting Gradient. It’s an experience that has changed everything for us.

      Visit Article

    • Should You Learn CoffeeScript? Should You Learn CoffeeScript?

      I’d imagine that I represent a large portion of the web development community. I’m very intrigued by CoffeeScript; I’ve even learned the syntax and used it in a few demos. However, I haven’t yet taken the plunge and used it in a real project. It comes down to this one question for me: is CoffeeScript something that is truly worth investing time and effort into learning?

      Visit Article

    • Vectortuts+ — Illustrator Tutorials
    • 75 Outstanding Tutorials, Quick Tips, Articles and Interviews from Vectortuts+ in 2011 Outstanding Tutorials, Quick Tips, Articles and Interviews from Vectortuts+ in 2011

      As the year comes to an end and we pack up our vector tools for some well deserved rest and relaxation, let’s take a look back at some of the best and most inspiring Vectortuts+ articles and tutorials for 2011.

      Visit Article

    • 2012 Calendar Design Project Community Project: 2012 Calendar Design Project

      Vectortuts+ loves Illustration and discovering new talent, so today we are proud to be launching a new community project that combines both, the Vectortuts+ 2012 Calendar Design Project. The best thing is, you can be a part of it! Find out how to get involved, at the jump.

      Visit Article

    • How to Create a Watercolor Background Using Adobe Illustrator Quick Tip: How to Create a Watercolor Background Using Adobe Illustrator

      In this tutorial we will learn how to create Watercolor Background using a Gradient Mesh, tools of deformation and Blending Modes. The techniques which are described here allow the creation of complex textural backgrounds in a simple and effective way.

      Visit Article

    • Webdesigntuts+ — Web Design Tutorials
    • How the Experts Saw 2011 A Year in Web Design: How the Experts Saw 2011

      “What did you find most memorable about the world of web design in 2011?” That’s the question I posed to some of our industry’s shining stars last week. One word cropped up more than any other (can you guess?) and everyone had plenty to say. See for yourself after the jump, and let us know what rocked your boat in 2011!

      Visit Article

    • the Programmable Stylesheet Language Get Into LESS: the Programmable Stylesheet Language

      I don’t like CSS. Plain and simple. It makes the World go round on the web, yet the language is restrictive and hard to manage. It’s time to spruce up the language and make it more helpful by using dynamic CSS with the help of LESS.

      Visit Article

    • Say Hello to the HTML Email Boilerplate Say Hello to the HTML Email Boilerplate

      Figuring out html email will test the patience of any human being. A seemingly small formatting issue will inevitably arise and you think to yourself, “self, I’m a world class web developer type person schooled in the latest and greatest html5/css3/whatever, I can tackle this with plenty o’ keystrokes to spare.”

      Visit Article

    • Phototuts+ — Photography Tutorials
    • 10 Tips to Get Started with Still Life Photography Tips to Get Started with Still Life Photography

      There arent many photographic practices that date back further than still life photography. When photography originated, it was necessary for exposures to be quite long, so photographing static objects was the ideal subject matter. However, as the technology developed, the fascination for capturing still life has remained and is still one of the most viable photographic professions today.

      Visit Article

    • Is It Worth It? Some Gear Buying Advice Is It Worth It? Some Gear Buying Advice

      A lot people believe their photography will improve “if only…” With the holidays approaching, a lot of avid wanna-be photographers, amateurs, and professionals will be making wish lists for gear that they erroneously believe will make them better photographers. There are many forums, YouTube videos, and articles pandering how camera/lens/light/brand/voodoo doll will make your photos better. Today, we’ll examine that idea.

      Visit Article

    • 50 Superb Photos of Paths and Stairways Superb Photos of Paths and Stairways

      “Follow the Yellow Brick Road,” an infamous movie quote inspired by a pathway to a land of dreams. Wherever your paths take you and whatever amount of stairs you have to climb, its always worth it to see whats at the end, but more importantly to enjoy the journey. Today’s collection gathers dozens of images of paths and stairways, images that symbolize something different to every person.

      Visit Article

    • Cgtuts+ — Computer Graphics Tutorials
    • Epic 3D Character Model Of Pyro From Team Fortress 2 Freebie: Epic 3D Character Model Of Pyro From Team Fortress 2

      Today we’re super excited to bring you this amazingly detailed character model from Cgtuts+ regular Shaun Keenan. Shaun has re-created “Pyro” from Valve’s hit game Team Fortress 2 in glorious detail, and is making the model available to the Cgtuts+ community for free!

      Visit Article

    • From Photoshop To Maya To Nuke, Part 1 – Tuts+ Premium Digital Matte Painting And Projection Basics: From Photoshop To Maya To Nuke, Part 1 – Tuts+ Premium

      This Tuts+ Premium tutorial series covers a variety of basic techniques for both creating and projecting matte paintings using Photoshop, Maya and Nuke. The first part of the tutorial will cover how to approach the creation of a matte painting, the research and background knowledge you need, the concept, and finally starting to create your matte painting in Photoshop. Log in or Join Now to get started!

      Visit Article

    • Create A Flying Paper Animation In 3D Studio Max With Thinking Particles Create A Flying Paper Animation In 3D Studio Max With Thinking Particles

      In this tutorial by Cristian Pop, you’ll learn how to create a nice flying papers effect in 3d Studio Max using the power of Thinking Particles. We’ll start by creating the paper shapes and materials, then move into Thinking Particles to set up the rules and look at how we can combine them to create the flying paper effect.

      Visit Article

    • Aetuts+ — After Effects Tutorials
    • How To Track Footage That Is Out Of Focus How To Track Footage That Is Out Of Focus

      In this tutorial we are going to take a look at a simple, but interesting idea. The main point will be to show you how to work with footage that is out of focus making if difficult to track. After we track it we are going to attach the camera interface elements and fake some depth of field to create the illusion that they are floating in space and shift in and out of focus like the rest of the scene.

      Visit Article

    • DIY – Create A Camera Dolly Completely From Scratch DIY – Create A Camera Dolly Completely From Scratch

      Ever wonder how to get smooth footage from your video camera? Today you will learn how to build a Camera Dolly that will help you acquire this type of footage. Get out those dusty power tools, buy some cheap supplies at your local hardware store, and you’ll be on your way to capturing some amazing footage in no time!.

      Visit Article

    • How To Create A Dr. Who Time And Space Vortex – Tutsplus Premium How To Create A Dr. Who Time And Space Vortex – Tutsplus Premium

      In this tutorial well be creating a Time & Space Vortex (like that used in Doctor Who) completely inside of After Effects. We will be using Trapcode Particular and Trapcode Shine to create the vortex. I will then teach a vital Expression that drives the camera and completes the Effect. Once you have mastered the effect, you can personalize it to create whatever Time-Tunnel you desire! All of Time and Space awaits you…

      Visit Article

    • Audiotuts+ — Audio & Production Tutorials
    • Get Your Attack and Release Times Correct Drum Compression: Get Your Attack and Release Times Correct

      Compression can be a tricky one to get your head around, and even if you’ve got your head around the threshold and ratio settings without the attack and release times being set correctly it will always be difficult to get the desired effect. This quick tip will outline a really handy trick I learned from a friend a few years ago which allows you to get your attack and release times just right. It’s primarily designed to work on drums but the same principles will apply to any percussive sound.

      Visit Article

    • Punchier Drums with the New York Compression Trick Quick Tip: Punchier Drums with the New York Compression Trick

      Ever have a mix where you wish the drums were bigger, more energetic, more in-your-face? I first heard about this technique in Bobby Owinksis, The Mixing Engineers Handbook, and it has since become a staple in my bag of tricks. The technique is a more aggressive take on parallel compression that can really add punch to your mix.

      Visit Article

    • Depth D Mixing Part 6: Depth

      In this segment of our mix down tutorial, we are going to begin to look in depth into depth. Depth within any mix and listening situation is paramount to proper sonic understanding. Much like we see in 3D, we hear in 3D and taking out any one of these dimensions only serves to create a flat and unnatural sound. As such, the most common tools which give the illusion of depth (reverb and delay) become an important and necessary part of mixing.

      Visit Article

    • Activetuts+ — Flash, Flex & ActionScript Tutorials
    • A Flash-Like Interface for the HTML5 Canvas Getting Started With EaselJS: A Flash-Like Interface for the HTML5 Canvas

      There’s been some resistance from Flash developers to our new HTML5 content. In this article – aimed at experienced AS3 coders – we’ll look at EaselJS, a JavaScript library that makes working with the HTML5 canvas very similar to working with the Flash display list.

      Visit Article

    • Hacking the Event Flow AS3 Quick Tip: Hacking the Event Flow

      Sometimes you may find yourself needing to modify the behavior of a component for a user input event. This article will explain how to do so by modifying the event object in-flight, before it’s processed by the component. That’s right, you can lie and cheat. In code.

      Visit Article

    • A Retrospective in Flash and Web Apps: A Retrospective

      With the year 2011 at a close, it is time to reflect upon some of the major industry events of the year. A lot happened… we’ll pick out some of the bits and pieces that will be most interesting to browser app and game developers from the world of industry, web, runtimes, operating systems, mobile, and more!

      Visit Article

    • Wptuts+ — WordPress Tutorials
    • WordPress 3.3 “Sonny” Is Finally Here! What’s New? WordPress 3.3 “Sonny” Is Finally Here! What’s New?

      The latest and greatest version of the WordPress software — 3.3, named ’Sonny” in honor of the great jazz saxophonist Sonny Stitt — is immediately available for download or update inside your WordPress dashboard. We’ll be covering lots of the new features of 3.3 this week, but for now, go and great the latest version! As we’ve mentioned before, it’s the best way to keep your WordPress site safe and stable.

      Visit Article

    • Getting Loopy – Ajax Powered Loops with jQuery and WordPress Getting Loopy – Ajax Powered Loops with jQuery and WordPress

      In this tutorial, we give you a starting point for creating AJAX interaction in your blog. We follow a step by step process, showing you how to load posts based on the viewers page scroll. The tutorial covers enqueueing scripts, setting up an AJAX handler, how to get a file outside of WordPress to use WordPress functions and access the database, and logic for loading posts on user page scroll.

      Visit Article

    • 5 “Saintly” Practices that All WordPress Developers Should Strive For Saintly” Practices that All WordPress Developers Should Strive For

      Here on Wptuts+, we talk a lot about the ‘how’ and less about the ‘why.’ Of course, we are a tutorial site, so that’s the goal, right? Well, as a followup to last month’s article on the “Cardinal Sins of WordPress Plugin Development“, today we’re going to look at a few practices that, if every developer followed, would make the world a better place (well, at least our world!).

      Visit Article

    • Mobiletuts+ — Mobile Development Tutorials
    • Getting Started With Kindle Fire Development Getting Started With Kindle Fire Development

      The Kindle Fire is the new touchscreen and e-book reader from Amazon. This device has generated a lot of buzz, and for good reason! It is currently the best selling Android tablet, with millions of units already sold. This tutorial will teach you how to begin making apps with the Android SDK specifically targeted for the Kindle Fire.

      Visit Article

    • Storyboards iOS 5 SDK: Storyboards

      Storyboarding is one of the most exciting new features about the iOS 5 SDK. Take a look at the wealth of functionality offered by Storyboards in today’s iOS 5 SDK tutorial!

      Visit Article

    • Build an Image Uploader Titanium Mobile: Build an Image Uploader

      This tutorial will demonstrate how to build a custom progress bar by creating an image uploader with Titanium Mobile. Specifically, the demo project will allow you to select an image from the device photo gallery and upload it to a remote server for storage. Both the Titanium Mobile code and the server-side code will be explained. Now, let’s get started!

      Visit Article

    Happy New Year!

    We’d like to wish all our readers a very Happy New Year! Why not take a look at our Holiday Wishes post to see a video message from the Envato HQ team, and find out more about what you might have missed over the Christmas period.

    We hope you’ve enjoyed everything that we’ve had to share this year, and look forward to publishing thousands more top-quality tutorials, articles, freebies, and resources in 2012.

    Thanks for being part of the Tuts+ community!


  • Permalink for 'The Tools of Modern Mac-Based Web Development: New on Premium'

    The Tools of Modern Mac-Based Web Development: New on Premium

    Posted: January 1st, 2012, 9:34am MST by Jeffrey Way

    In this week’s Premium screencast, I provide a brain-dump on all of the various tools I use for web development. Sometimes, simply watching another person work can be incredibly helpful. What tools do they use? How do they work with their code editor? I’ll cover all of these things today.

    If you’re not a Tuts+ Premium member, it’s our subscription-based portion of Tuts+, where we provide high quality tutorials, ebooks, and courses on a variety of subjects. Be sure to check it out!

    Tools Discussed in the Video


  • Permalink for 'Nettuts+ – A Year in Review (And What’s Next)'

    Nettuts+ – A Year in Review (And What’s Next)

    Posted: December 30th, 2011, 12:43pm MST by Jeffrey Way

    Good gosh; another year comes to a close. Sometimes, it feels as if every year passes by more quickly than the one before it. Nonetheless, 2011 was a great year for Nettuts+. Here’s why…

    Traffic

    Honestly, these days, I don’t focus on traffic too much. That might come as a surprise, considering that this is a blog that, yes, brings in income. However, I’ve come to learn that obsessing over traffic only translates to you spending less time creating content. I’ve never taken a stance, such as, “Next month’s traffic needs to be up by 15%.” It doesn’t work that way.

    Personally, I only use Google Analytics to:

    • Determine what sorts of content you readers don’t enjoy as much.
    • Get a birds eye view of how the site is performing. For example, 2011′s numbers, as a whole, are up 23% over 2010′s. That may not sound like much, but for us, that amounts to millions and millions of new visitors.
    • Pinpoint which search queries are most popular. That way, I can be sure to commission appropriate tutorials.

    Beyond that, I honestly don’t see much point in obsessively focusing on traffic.

    Dedicate your life to a given topic, write about it as well as you are capable of, and I promise that the traffic will come as a result.

    In 2012…

    To project numbers for 2012 would almost be a contradiction of what I just wrote. That said, I suppose it would be nice for us to continue reaching more and more people!

    Editorials

    Nettuts+ was initially created with one simple goal: provide high quality, step-by-step web development tutorials. This year, I decided that we need to have more of a voice in the community. Initially, this took the form of me venting to an online journal… read by millions of people. Since then, though, the Editorials category has morphed into developers providing their own strong opinions on one issue or another. The reader is then left with the article (and the comments) to determine what his or her own views on the subject are. The most important thing is that it gets us talking.

    In 2012…

    I hope to provide even more opinion-based editorials on Nettuts+. My goal is that, when a well-known developer needs to get something off his chest – whether it be the state of the industry, the people, or the tools available – he comes to Nettuts+ to write and publish it.

    I want Nettuts+ to be the central location for the web development industry to come together and discuss important issues and events.

    Apps

    One of my goals for 2011 was to have Nettuts+ branch out a bit. Yes, we have the blog, but what about books, tools, and apps? We’re still very much in the early stages of these goals, though, we’ve made some good progress. Nettuts+ Prefixr Nettuts+ Prefixr

    Prefixr was built out of necessity, and provides us with a way to automate the creation of all those tedious CSS vendor prefixes. Now, from your favorite code editor, you only need to type a shortcut key, and your entire stylesheet will be run through the Prefixr web service, and automatically optimized. No longer do you need to worry about which browsers support which CSS3 properties. Prefixr does that for you.

    Nettuts+ Builder

    Unfortunately, it costs money to commission these apps; so we’ve experimented with selling them as cheaply as possible on the popular CodeCanyon marketplace.

    Nettuts+ Builder

    Nettuts+ Builder turns the process of compressing scripts and stylesheets, and uploading a project to your server into as simple a process as possible.

    Let’s say that you finished a coding project or demo. Simply drag the folder onto the Builder menu icon, and it will:

    • Create a new “Publish” directory
    • Compress all JavaScript files
    • Compress all Stylesheets
    • Concatenate all assets
    • Optionally upload them, via FTP , to a designated folder on your server.

    If you’ve found yourself manually compressing your files and uploading them to your server, this automates the entire process!

    Structurer Pro Structurer Pro

    Structurer is a wonderful project tempting interface for the Mac. It allows you to rapidly create directory structures with ease, and a few of the features include:

    • Always find yourself manually creating the same files and directories? Not anymore.
    • Need to download the latest version of the CodeIgniter framework? Or how about WordPress? With Structurer, it can be done in two seconds!
    • Need to assign custom text to new files – for example, adding a base plugin snippet to a JavaScript file? That’s a cinch in Structurer!
    In 2012…

    Branching out to provide apps and web services is a fantastic way to both spread your brand, and provide helpful services to your peers. In 2012, I’ll be focusing on commissioning more cross-OS apps, and creating additional web applications and services. For example, I don’t think that the online code snippet management and community idea has been executed well enough by anyone. Sites like Snipplr are helpful, but fall far short of what they could be.

    Additionally, we’ll also focus on smaller tools, such as plugins, code editor extensions, and more.

    The Best Way to Learn…

    Newcomers are begging for these sorts of resources.

    Something I’ve thought about quite a bit – particularly in the last several months – is syllabus based education. For instance, if you want to learn JavaScript, you have literally thousands of resources available to you. As amazing as that is, it’s almost a hindrance; where do you start? Very quickly, you can become overwhelmed. Wouldn’t it be helpful if you were given a syllabus by a pro? Want to learn JavaScript? Great – read this, then this, then this, follow and become friends with these people on Twitter, try out this first project, etc. Newcomers are begging for these sorts of resources.

    As a first step, we’ve created a series tailor-made for this group of people: The Best Way to Learn.

    In 2012…

    We’re only four entries in so far; in 2012, I’d like to increase this number to cover all sorts of languages and tools.

    Two Man Ship

    While Nettuts+ is a part of the Envato network, when it comes to the day-to-day management, it had always been little-ole me at the helm. Thankfully, this year, Siddharth has come on board as my assistant, and has been doing an excellent job. In addition to helping me edit and publish articles (so that I can focus more on Premium courses and books), he’s also the man behind our fun Nettuts+ Quizzes that you guys seem to enjoy. He’s been a huge asset to the site.

    Nettuts+ Quizzes In 2012…

    I hope to transition Sid into more of a co-pilot, rather than assistant. It’ll be nice to reach a point when we are both responsible for finding, commissioning, and scheduling top quality content.

    Nettuts+ Live

    Take the Nettuts+ format (step by step tutorial), and translate it to a live, real-time coding tutorial on stage.

    A few months ago, when speaking at a WordPress meetup in New York, I experimented with a format that I call “Nettuts+ Live.” The basic idea is that you take the Nettuts+ format (step by step tutorials), and translate it to a live, real-time coding tutorial on stage.

    For my presentation, I discussed WordPress custom post types and taxonomies, and how they can be used to extend your WordPress application. Now, in hindsight, I’m not sure I would do it the same way again. Coding from scratch in front of a hundred people is very, very difficult. With that in mind, I think I did quite well, though there were a few points when I had to stop and stare at the code blankly for a couple moments…desperately trying to determine what typo I had made.

    And then, when I finished the presentation, I was met with the realization that only a handful of the people in the audience were actual coders; the rest were mostly WordPress users. Yikes!

    In 2012…

    Nonetheless, I think the format has merit, if molded a bit more. In 2012, I’m going to experiment with more local meetups and this format. No slides; just a code editor, a speaker, and lots of questions from the audience along the way. It may crash and burn, but it also may…not!

    Courses Tuts+ Premium

    As part of the newly relaunched Premium brand of Tuts+, Tuts+ Premium, I’m the head of web development courses. Mostly, what this translates to is me creating the best possible content for learning how to be a web developer – in video form.

    Particularly in the last few months, I’ve immersed myself in the art of screencasting and teaching. I’ve watched countless video tutorials around the web to determine what I enjoyed, what it irritated me, and what makes me press stop. At a glance…

    • Umms: I can’t help it; when a teacher speaks too many umms and ahhs, it drives me crazy. “Next we’re uhhhhhhh going to create this div.
    • Massive Snippets: If you’re creating a screencast, your goal is to teach right? In that case, don’t paste twenty lines of code into the editor at a time. Many of the viewers will be working along; don’t flood them with unexplained code snippets. Write that stuff by hand, but…
    • Wasting Time: Don’t make the viewer wait for you. A pet peeve of mine is watching a screencaster take 60 seconds to write a single line. You can edit these pauses out when you’re finished recording. For instance, rather than, over the course of twenty seconds, writing document.getElementById('myElem');, simply say, “Next, we’re going to retrieve the element with an id of myElem. Then, either immediately cut to the finished line, or speed up the video while you write it. It’s painful otherwise.
    • Teach, Fool: I’m amazed by how many people don’t make the connection that they should be teaching. A screencast is not a place to illustrate how smart and clever you are. Explain exactly what each line is doing; never assume that all viewers are on the same skill-level. In my videos, I often say, “I’m going to explain this section in more detail, but, if you already understand it, fast-forward a couple minutes in the video.”
    • Audio Quality: My first videos were awful, and used the built-in microphone. Thankfully, I’ve come a long ways since then. If you enjoy creating video tutorials, please invest in a good microphone; it makes an enormous difference. In the last few months, I’ve switched to the Rode NTG. Highly recommended!
    • Zooming: This is the worst of the bunch; especially for coding tutorials, don’t record at 600×400, and make the viewer dizzy every time your mouse moves from one side of your screen to the other, while the video recorder transitions left to right quickly. Instead, reduce the resolution of your monitor to around 1280×720, and record full screen.
    In 2012…

    At the moment, I’m still working to get the bread and butter courses up on the site, such as CSS3, JavaScript, jQuery, PHP, etc. Once the staples are finished, we’ll transition into more specific courses, such as Backbone Essentials, CodeIgniter, Dojo, etc. It’s a really exciting time to be a Tut+ Premium member.

    Changing the Landscape of Online Education

    Brick and mortar colleges are dated, and incredibly expensive.

    Nettuts+ began in 2008, when Envato was still referred to as Eden. Since then, the site has come a really long way. My favorite part has been the process of determining and defining exactly what sort of site it is. I love that we offer video tutorials, and sessions, and in depth articles from some of the most respected developers in our industry. Every time one of my dev heroes links to a Nettuts+ article, it makes me feel amazing. This site will continue to grow; so “stay the course” is the name of the game for Nettuts+ and 2012.

    In 2012…

    Tuts+ Premium has taken the first step. The next one will be a significantly larger leap forward.

    For me, I want to redefine the landscape of online web development education entirely. I want to take the basic college experience, and translate it to the web. No, I’m not talking about keg parties, I’m talking about a community for students.

    I’ve heard it too many times: “My college hasn’t taught me a fraction of what Nettuts+ has in two weeks.” I’m not being conceited here; replace Nettuts+ with any popular web development blog, and the outcome will still be true. Because our industry is accelerating at such an incredible speed, traditional schools and professors can not keep up. Brick and mortar colleges are dated, and incredibly expensive.

    I want Tuts+ Premium to bridge the gap: provide students with instructors, courses, quizzes, assignments, one-on-one lessons, certifications, and forums to learn and collaborate with their peers. In its current form, Tuts+ Premium has taken the first step. The next one will be a significantly larger leap forward.

    Help Me

    This final question is for you, John Q Reader. How can I make Nettuts+ the best web development resource on the web? In the last three years, we’ve come a very long way toward this goal. How can I take it further? What do you need more of from us? In return, I promise we’ll do our best to provide it. We’re currently working on the next design for the Tuts+ sites; your input will help define the shape it takes!


  • Permalink for 'Creating an API-Centric Web Application'

    Creating an API-Centric Web Application

    Posted: December 30th, 2011, 10:28am MST by Nikko Bautista

    Planning to start working on a new web application? In this tutorial, we’ll discuss how to create an API-centric web application, and explain why this is essential in today’s multi-platform world.

    Introduction API?

    For those who are unfamiliar with the term, API is short for Application Programming Interface. According to Wikipedia:

    An application programming interface (API) is a source code based specification intended to be used as an interface by software components to communicate with each other. An API may include specifications for routines, data structures, object classes, and variables.

    API Visualization

    API Visualization

    Image courtesy of [blog.zoho.com]

    In simpler terms, an API refers to a set of functions built into an application, which can be used by other applications (or by itself, as we’ll see later), to interact with the application. An API is a great way to expose an application’s functionality to external applications safely and securely, since all functionality that these external applications can do is limited with what functionality is exposed in the API.

    What’s an “API-Centric” Web Application?

    An API-Centric Web Application is a web application that basically executes most, if not, all its functionality through API calls.

    An API-Centric Web Application is a web application that basically executes most, if not, all its functionality through API calls. For example, if you were to log in a user, you would send his credentials to the API, and the API would return to you a result saying if the user provided the correct user-password combination.

    Another characteristic of an API-Centric Web Application is that the API will always be stateless, meaning it can’t recognize API calls by session. Since API calls will be made by usually via the backend code, it will be hard to implement session handling, since there are usually no cookies involved in that. This limitation is actually good — this “forces” a developer to build an API that works not based on the state of the current user, but rather on functionality, which in turn, makes it easier to test, since the current state of a user doesn’t need to be recreated.

    Why go through all this trouble?

    As web developers, we’ve seen technology evolve first hand. It’s common knowledge that people today don’t just use applications via a browser, but through other gadgets, like mobile phones and tablets. For example, this article on Mashable, entitled “Consumers Now Spending More Time on Mobile Apps Than the Web”, states:

    Consumers are spending more time on mobile apps than on the web for the first time, a new report claims.

    Flurry compared its mobile data to stats from comScore and Alexa, and found that in June, consumers spent 81 minutes per day using mobile apps, compared to 74 minutes of web surfing.

    Here’s a more recent article from ReadWriteWeb, entitled “More People Browse On Mobile Than Use IE6 & IE7 Combined:

    The latest data on browser trends from Sitepoint show that more people browse the Web on smartphones than use Internet Explorer 6 and 7 combined. Those two old clunkers have been the bugbears of Web developers for years, requiring sites to degrade as nicely as possible to that least common denominator of browsers. But it’s a new world now; 6.95% of Web activity in November 2011 was on mobile browsers, and only 6.49% was on IE 6 or 7.

    As we can clearly see, more and more people get their news from alternative venues, specifically mobile devices.

    What does this have to do with me creating an API-Centric Web Application?

    This would inevitably lead to more usage of our application, since it can be used anywhere a person wants.

    One of the main advantages of creating an API-centric application is that it helps you build functionality that can be used by ANY device, be it a browser, a mobile phone, a tablet, or even a desktop app. All you need to do is to create the API in such a way that all these devices can communicate with it, and voila! You’ll have built a centralized application that can take input and execute functionality from any device that a person has!

    API-Centric Application Diagram

    API-Centric Application Diagram

    By creating an application in this manner, we’re able to easily take advantage of the different mediums used by different people. This would inevitably lead to more usage of an application, since it can be used anywhere a person wants.

    To drive the point home, here’s an article about Twitter’s new redesigned website, which tells us about how they now use their API to power Twitter.com, essentially making it API-centric:

    One of the most important architectural changes is that Twitter.com is now a client of our own API. It fetches data from the same endpoints that the mobile site, our apps for iPhone, iPad, Android, and every third-party application use. This shift allowed us to allocate more resources to the API team, generating over 40 patches. In the initial page load and every call from the client, all data is now fetched from a highly optimized JSON fragment cache.

    In this tutorial, we’ll be creating a simple TODO list application that is API-Centric and create one front-end client on the browser that interacts with our TODO list application. By the end, you’ll know the integral parts of an API-Centric application, and at the same time, how to facilitate secure communication between the two. With that in mind, let’s begin!

    Step 1: Plan the Application’s Functions

    The TODO application we’ll be building in this tutorial will have the basic CRUD functions:

    • Create TODO Items
    • Read TODO Items
    • Update TODO Items (rename, mark as done, mark as undone)
    • Delete TODO Items

    Each TODO item will have:

    • a Title
    • a Date Due
    • a Description
    • a flag to tell if the TODO Item Is Done
    • Let’s mockup the application as well so we have a guide on how it should look like afterwards:

      SimpleTODO Mockup

      SimpleTODO Mockup Step 2: Create the API Server

      Since we’re developing an API-Centric application, we’ll be creating two “projects”: the API Server, and the Front-end Client. Let’s begin by creating the API server first.

      On your web server’s folder, create a folder named simpletodo_api, and create an index.php file. This index.php file will act as a front controller for the API, so all requests to the API server will be made through this file. Open it up and put the following code inside:

      <?php
      // Define path to data folder
      define('DATA_PATH', realpath(dirname(__FILE__).'/data'));
      
      //include our models
      include_once 'models/TodoItem.php';
      
      //wrap the whole thing in a try-catch block to catch any wayward exceptions!
      try {
      	//get all of the parameters in the POST/GET request
      	$params = $_REQUEST;
      
      	//get the controller and format it correctly so the first
      	//letter is always capitalized
      	$controller = ucfirst(strtolower($params['controller']));
      
      	//get the action and format it correctly so all the
      	//letters are not capitalized, and append 'Action'
      	$action = strtolower($params['action']).'Action';
      
      	//check if the controller exists. if not, throw an exception
      	if( file_exists("controllers/{$controller}.php") ) {
      		include_once "controllers/{$controller}.php";
      	} else {
      		throw new Exception('Controller is invalid.');
      	}
      
      	//create a new instance of the controller, and pass
      	//it the parameters from the request
      	$controller = new $controller($params);
      
      	//check if the action exists in the controller. if not, throw an exception.
      	if( method_exists($controller, $action) === false ) {
      		throw new Exception('Action is invalid.');
      	}
      
      	//execute the action
      	$result['data'] = $controller->$action();
      	$result['success'] = true;
      
      } catch( Exception $e ) {
      	//catch any exceptions and report the problem
      	$result = array();
      	$result['success'] = false;
      	$result['errormsg'] = $e->getMessage();
      }
      
      //echo the result of the API call
      echo json_encode($result);
      exit();
      

      What we’ve essentially built here is a simple front controller that does the following:

      • Accept an API call with any number of parameters
      • Extract the Controller and Action for the API call
      • Make the necessary checks to ensure that the Controller and Action exist
      • Execute the API call
      • Catch errors, if any
      • Send back a result to the caller

      Besides the index.php file, create three folders: a controllers, models and data folder.

      API server folders
      • The controllers folder will contain all the controllers we’ll be using for the API server. We’ll be building it using the MVC architecture to make the structure of the API server cleaner and more organized.
      • The models folder will contain all the data models for the API server.
      • The data folder will be where the API server saves any data

      Go into the controllers folder and create a file called Todo.php. This will be our controller for any TODO list related tasks. With the functions we’ll be needing for our TODO application in mind, create the necessary methods for the Todo controller:

      
      <?php
      class Todo
      {
      	private $_params;
      
      	public function __construct($params)
      	{
      		$this->_params = $params;
      	}
      
      	public function createAction()
      	{
      		//create a new todo item
      	}
      
      	public function readAction()
      	{
      		//read all the todo items
      	}
      
      	public function updateAction()
      	{
      		//update a todo item
      	}
      
      	public function deleteAction()
      	{
      		//delete a todo item
      	}
      }
      

      Now, add the necessary functionality to each action. I’ll provide the code for the createAction method and I’ll leave it up to you to create the code for the other methods. If you’re not in the mood though, you can just download the source code for the demo and copy it from there.

      
      public function createAction()
      {
      	//create a new todo item
      	$todo = new TodoItem();
      	$todo->title = $this->_params['title'];
      	$todo->description = $this->_params['description'];
      	$todo->due_date = $this->_params['due_date'];
      	$todo->is_done = 'false';
      
      	//pass the user's username and password to authenticate the user
      	$todo->save($this->_params['username'], $this->_params['userpass']);
      
      	//return the todo item in array format
      	return $todo->toArray();
      }
      

      Create TodoItem.php inside the models folder so we can create the “item creation” code. Take note that I won’t be connecting to a database, rather, I’ll be saving the information into files. It should be relatively easy though to make this work with any database.

      
      <?php
      class TodoItem
      {
      	public $todo_id;
      	public $title;
      	public $description;
      	public $due_date;
      	public $is_done;
      
      	public function save($username, $userpass)
      	{
      		//get the username/password hash
      		$userhash = sha1("{$username}_{$userpass}");
      		if( is_dir(DATA_PATH."/{$userhash}") === false ) {
      			mkdir(DATA_PATH."/{$userhash}");
      		}
      
      		//if the $todo_id isn't set yet, it means we need to create a new todo item
      		if( is_null($this->todo_id) || !is_numeric($this->todo_id) ) {
      			//the todo id is the current time
      			$this->todo_id = time();
      		}
      
      		//get the array version of this todo item
      		$todo_item_array = $this->toArray();
      
      		//save the serialized array version into a file
      		$success = file_put_contents(DATA_PATH."/{$userhash}/{$this->todo_id}.txt", serialize($todo_item_array));
      
      		//if saving was not successful, throw an exception
      		if( $success === false ) {
      			throw new Exception('Failed to save todo item');
      		}
      
      		//return the array version
      		return $todo_item_array;
      	}
      
      	public function toArray()
      	{
      		//return an array version of the todo item
      		return array(
      			'todo_id' => $this->todo_id,
      			'title' => $this->title,
      			'description' => $this->description,
      			'due_date' => $this->due_date,
      			'is_done' => $this->is_done
      		);
      	}
      }
      

      The createAction method calls two functions on the TodoItem model:

      • save() – this saves the TodoItem into a file, as well as set the todo_id for the TodoItem if necessary
      • toArray() – this returns an array version of the TodoItem, where the variables are the array’s indexes

      Since the API is called via HTTP requests, let’s test that API call by calling it through the browser:

      [localhost]

      If everything worked, you should see a new folder inside the data folder, and inside that folder, you should see a file with the following content:

      createAction() result

      createAction() result

      Congratulations! You’ve successfully created an API server and made an API call!

      Step 3: Secure the API Server with an APP ID and APP SECRET

      Currently, the API server is set to accept ALL API requests. We’ll need to limit it to our own applications only, to ensure that only our own front-end clients are able to make API requests. Alternatively, you can actually create a system wherein users can create their own applications that have access to your API server, similar to how Facebook and Twitter applications work.

      Begin by creating a set of id-key pairs for the clients that will be using the API server. Since this is just a demo, we can use any random, 32 character string. For the APP ID, let’s say it’s application APP001.

      Open the index.php file again, and then update it with the following code:

      
      <?php
      // Define path to data folder
      define('DATA_PATH', realpath(dirname(__FILE__).'/data'));
      
      //Define our id-key pairs
      $applications = array(
      	'APP001' => '28e336ac6c9423d946ba02d19c6a2632', //randomly generated app key
      );
      //include our models
      include_once 'models/TodoItem.php';
      
      //wrap the whole thing in a try-catch block to catch any wayward exceptions!
      try {
      	//*UPDATED*
      	//get the encrypted request
      	$enc_request = $_REQUEST['enc_request'];
      
      	//get the provided app id
      	$app_id = $_REQUEST['app_id'];
      
      	//check first if the app id exists in the list of applications
      	if( !isset($applications[$app_id]) ) {
      		throw new Exception('Application does not exist!');
      	}
      
      	//decrypt the request
      	$params = json_decode(trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $applications[$app_id], base64_decode($enc_request), MCRYPT_MODE_ECB)));
      
      	//check if the request is valid by checking if it's an array and looking for the controller and action
      	if( $params == false || isset($params->controller) == false || isset($params->action) == false ) {
      		throw new Exception('Request is not valid');
      	}
      
      	//cast it into an array
      	$params = (array) $params;
      	...
      	...
      	...
      

      What we’ve done here is actually implement a very simple way of authenticating our front-end clients using a system similar to public-private key authentication. Basically, here is the step-by-step breakdown of how the authentication happens:

      Public-key encryption

      Public-key encryption
      • an API call is made, in it an $app_id and $enc_request is provided.
      • the $enc_request value is the API call parameters, encrypted using APP KEY. The APP KEY is NEVER sent to the server, it’s only used to hash the request. Additionally, the request can only be decrypted using the APP KEY.
      • once the API call arrives to the API server, it will check its own list of applications for the APP ID provided
      • when found, the API server attempt to decrypt the request using the key that matches the APP ID sent
      • if it was successful in decrypting it, then continue on with the program

      Now that the API server is secured with an APP ID and APP SECRET, we can begin programming a front-end client to use the API server.

      Step 4: Create the Browser Front-end Client

      We’ll begin by setting up a new folder for the front-end client. Create a folder called simpletodo_client_browser on your web server’s folder. When that’s done, create an index.php file and put this code inside:

      
      <!DOCTYPE html>
      <html>
      <head>
      	<title>SimpleTODO</title>
      
      	<link rel="stylesheet" href="css/reset.css" type="text/css" />
      	<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
      
      	<script src="js/jquery.min.js"></script>
      	<script src="js/jquery-ui-1.8.16.custom.min.js"></script>
      
      	<style>
      	body {
      		padding-top: 40px;
      	}
      	#main {
      		margin-top: 80px;
      		text-align: center;
      	}
      	</style>
      </head>
      <body>
      	<div class="topbar">
      		<div class="fill">
      			<div class="container">
      				<a class="brand" href="index.php">SimpleTODO</a>
      			</div>
      		</div>
      	</div>
      	<div id="main" class="container">
      		<form class="form-stacked" method="POST" action="login.php">
      			<div class="row">
      				<div class="span5 offset5">
      					<label for="login_username">Username:</label>
      					<input type="text" id="login_username" name="login_username" placeholder="username" />
      
      					<label for="login_password">Password:</label>
      					<input type="password" id="login_password" name="login_password" placeholder="password" />
      
      				</div>
      			</div>
      			<div class="actions">
      				<button type="submit" name="login_submit" class="btn primary large">Login or Register</button>
      			</div>
      		</form>
      	</div>
      </body>
      </html>
      

      That should look something like this:

      SimpleTODO Login Page

      SimpleTODO Login Page

      Take note that I’ve included 2 JavaScript files and 2 CSS files here:

      Next, let’s create the login.php file so we store the username and password inside a session on the client.

      
      <?php
      //get the form values
      $username = $_POST['login_username'];
      $userpass = $_POST['login_password'];
      
      session_start();
      $_SESSION['username'] = $username;
      $_SESSION['userpass'] = $userpass;
      header('Location: todo.php');
      exit();
      

      Here, we simply start a session for the user, based on the username and password combination the user will provide. This acts as a simple combination key, which will allow a user to access stored TODO items for a specific combination of both the username and password. We then redirect to todo.php, where we start interacting with the API server. Before we start coding the todo.php file though, let’s first create an ApiCaller class, which will encapsulate all the API calling methods we’ll need, including encrypting the requests.

      Create apicaller.php and put the following inside:

      
      <?php
      class ApiCaller
      {
      	//some variables for the object
      	private $_app_id;
      	private $_app_key;
      	private $_api_url;
      
      	//construct an ApiCaller object, taking an
      	//APP ID, APP KEY and API URL parameter
      	public function __construct($app_id, $app_key, $api_url)
      	{
      		$this->_app_id = $app_id;
      		$this->_app_key = $app_key;
      		$this->_api_url = $api_url;
      	}
      
      	//send the request to the API server
      	//also encrypts the request, then checks
      	//if the results are valid
      	public function sendRequest($request_params)
      	{
      		//encrypt the request parameters
      		$enc_request = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->_app_key, json_encode($request_params), MCRYPT_MODE_ECB));
      
      		//create the params array, which will
      		//be the POST parameters
      		$params = array();
      		$params['enc_request'] = $enc_request;
      		$params['app_id'] = $this->_app_id;
      
      		//initialize and setup the curl handler
      		$ch = curl_init();
      		curl_setopt($ch, CURLOPT_URL, $this->_api_url);
      		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      		curl_setopt($ch, CURLOPT_POST, count($params));
      		curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
      
      		//execute the request
      		$result = curl_exec($ch);
      
      		//json_decode the result
      		$result = @json_decode($result);
      
      		//check if we're able to json_decode the result correctly
      		if( $result == false || isset($result['success']) == false ) {
      			throw new Exception('Request was not correct');
      		}
      
      		//if there was an error in the request, throw an exception
      		if( $result['success'] == false ) {
      			throw new Exception($result['errormsg']);
      		}
      
      		//if everything went great, return the data
      		return $result['data'];
      	}
      }
      

      We’ll be using the ApiCaller class to send requests to our API server. This way, all the necessary encryption and cURL initialization code will be in one place, and we won’t have to repeat our code.

      • the __construct function takes in three parameters:

        1. $app_id – the APP ID for the client (which is APP001 for the browser client)
        2. $app_key – the APP KEY for the client (which is 28e336ac6c9423d946ba02d19c6a2632 for the browser client)
        3. $api_url – the URL of the API server, which is http://localhost/simpletodo_api/
      • the sendRequest() function:

        1. encrypts the request parameters using the mcrypt library in the same manner that the API server decrypts it
        2. generates the $_POST parameters to be sent to the API server
        3. executes the API call via cURL
        4. checks the result of the API call was successful or not
        5. returns the data when everything went according to plan

      Now, let’s begin with the todo.php page. First off, let’s create some code to retrieve the current list of todo items for the user nikko with the password test1234 (this is the user/password combination we used earlier to test the API server).

      
      <?php
      session_start();
      include_once 'apicaller.php';
      
      $apicaller = new ApiCaller('APP001', '28e336ac6c9423d946ba02d19c6a2632', 'http://localhost/simpletodo_api/');
      
      $todo_items = $apicaller->sendRequest(array(
      	'controller' => 'todo',
      	'action' => 'read',
      	'username' => $_SESSION['username'],
      	'userpass' => $_SESSION['userpass']
      ));
      
      echo '';
      var_dump($todo_items);
      

      Go to the index.php page, login as nikko/test1234, and you should see a var_dump() of the TODO item we created earlier.

      TODO item var_dump()

      Congratulations, you’ve successfully made an API call to the API server! In this code, we’ve:

      • started the session so we have access to the username and userpass in the $_SESSION
      • instantiated a new ApiCaller class, giving it the APP ID, APP KEY and the URL of the API server
      • send a request via the sendRequest() method

      Now, let’s reformat the data so it looks better. Add the following HTML to the todo.php code. Don’t forget to remove the var_dump()!

      
      <!DOCTYPE html>
      <html>
      <head>
      	<title>SimpleTODO</title>
      
      	<link rel="stylesheet" href="css/reset.css" type="text/css" />
      	<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
      	<link rel="stylesheet" href="css/flick/jquery-ui-1.8.16.custom.css" type="text/css" />
      
      	<script src="js/jquery.min.js"></script>
      	<script src="js/jquery-ui-1.8.16.custom.min.js"></script>
      
      	<style>
      	body {
      		padding-top: 40px;
      	}
      	#main {
      		margin-top: 80px;
      	}
      
      	.textalignright {
      		text-align: right;
      	}
      
      	.marginbottom10 {
      		margin-bottom: 10px;
      	}
      	#newtodo_window {
      		text-align: left;
      		display: none;
      	}
      	</style>
      
      	<script>
      	$(document).ready(function() {
      		$("#todolist").accordion({
      			collapsible: true
      		});
      		$(".datepicker").datepicker();
      		$('#newtodo_window').dialog({
      			autoOpen: false,
      			height: 'auto',
      			width: 'auto',
      			modal: true
      		});
      		$('#newtodo').click(function() {
      			$('#newtodo_window').dialog('open');
      		});
      	});
      	</script>
      </head>
      <body>
      	<div class="topbar">
      		<div class="fill">
      			<div class="container">
      				<a class="brand" href="index.php">SimpleTODO</a>
      			</div>
      		</div>
      	</div>
      	<div id="main" class="container">
      		<div class="textalignright marginbottom10">
      			<span id="newtodo" class="btn info">Create a new TODO item</span>
      			<div id="newtodo_window" title="Create a new TODO item">
      				<form method="POST" action="new_todo.php">
      					<p>Title:<br /><input type="text" class="title" name="title" placeholder="TODO title" /></p>
      					<p>Date Due:<br /><input type="text" class="datepicker" name="due_date" placeholder="MM/DD/YYYY" /></p>
      					<p>Description:<br /><textarea class="description" name="description"></textarea></p>
      					<div class="actions">
      						<input type="submit" value="Create" name="new_submit" class="btn primary" />
      					</div>
      				</form>
      			</div>
      		</div>
      		<div id="todolist">
      			<?php foreach($todo_items as $todo): ?>
      			<h3><a href="#"><?php echo $todo->title; ?></a></h3>
      			<div>
      				<form method="POST" action="update_todo.php">
      				<div class="textalignright">
      					<a href="delete_todo.php?todo_id=<?php echo $todo->todo_id; ?>">Delete</a>
      				</div>
      				<div>
      					<p>Date Due:<br /><input type="text" id="datepicker_<?php echo $todo->todo_id; ?>" class="datepicker" name="due_date" value="12/09/2011" /></p>
      					<p>Description:<br /><textarea class="span8" id="description_<?php echo $todo->todo_id; ?>" class="description" name="description"><?php echo $todo->description; ?></textarea></p>
      				</div>
      				<div class="textalignright">
      					<?php if( $todo->is_done == 'false' ): ?>
      					<input type="hidden" value="false" name="is_done" />
      					<input type="submit" class="btn" value="Mark as Done?" name="markasdone_button" />
      					<?php else: ?>
      					<input type="hidden" value="true" name="is_done" />
      					<input type="button" class="btn success" value="Done!" name="done_button" />
      					<?php endif; ?>
      					<input type="hidden" value="<?php echo $todo->todo_id; ?>" name="todo_id" />
      					<input type="hidden" value="<?php echo $todo->title; ?>" name="title" />
      					<input type="submit" class="btn primary" value="Save Changes" name="update_button" />
      				</div>
      				</form>
      			</div>
      			<?php endforeach; ?>
      		</div>
      	</div>
      </body>
      </html>
      

      It should now look something like this:

      TODO Home

      Pretty cool huh? But this currently does nothing, so let’s begin adding some functionality. I’ll provide the code for new_todo.php, which will call the todo/create API call to create a new TODO item. Creating the other pages (update_todo.php and delete_todo.php) should be very similar to this one, so I’ll leave it up to you to create those. Open up new_todo.php and add the following code:

      
      <?php
      session_start();
      include_once 'apicaller.php';
      
      $apicaller = new ApiCaller('APP001', '28e336ac6c9423d946ba02d19c6a2632', 'http://localhost/simpletodo_api/');
      
      $new_item = $apicaller->sendRequest(array(
      	'controller' => 'todo',
      	'action' => 'create',
      	'title' => $_POST['title'],
      	'due_date' => $_POST['due_date'],
      	'description' => $_POST['description'],
      	'username' => $_SESSION['username'],
      	'userpass' => $_SESSION['userpass']
      ));
      
      header('Location: todo.php');
      exit();
      ?>
      

      As you can see, the new_todo.php page uses the ApiCaller again to facilitate the sending the todo/create request to the API server. This basically does the same thing as before:

      • start a session so it has access to the $username and $userpass saved in the $_SESSION
      • instantiate a new ApiCaller class, giving it the APP ID, APP KEY and the URL of the API server
      • send the request via the sendRequest() method
      • redirect back to todo.php
      New TODO!

      Congratulations, it works! You’ve successfully created an API-centric application!

      Conclusion

      There are so many advantages to developing an application that’s built around an API. Want to create an Android application version of SimpleTODO? All the functionality you would need is already in the API server, so all you need to do is just create the client! Want to refactor or optimize some of the classes? No problem — just make sure the output is the same. Need to add more functionality? You can do it wihtout affecting any of the client’s code!

      Though there are some disadvantages like longer development times or more complexity, the advantages of developing a web application in this manner greatly outweight the disadvantages. It’s up to us to leverage on this kind of development today so we can reap the benefits later on.

      Are you planning to use an API server for your next web application, or have you already used the same technique for a project in the past? Let me know in the comments!


  • Permalink for 'Create a Scalable Widget Using YUI3: Part 3'

    Create a Scalable Widget Using YUI3: Part 3

    Posted: December 28th, 2011, 3:00pm MST by Dan Wellman

    In the last part of this series, we looked at the life-cycle methods, automatic methods and the custom methods that our widget requires or can make use of. In this part, we’re going to finish defining the widget’s class by adding the attribute change-handling methods that we attached in the bindUI() life-cycle method.

    Let’s get started right away!

    Attribute Change Handlers

    The attribute change-handling group of methods are called when some of our attributes change values. We’ll start by adding the method that is called when the showTitle attribute changes; add the following code directly after the _uiSetTitle() method:

    _afterShowTitleChange: function () {
        var contentBox = this.get("contentBox"),
            title = contentBox.one(".yui3-tweetsearch-title");
    
        if (title) {
            title.remove();
            this._titleNode = null;
        } else {
            this._createTitle();
        }
    },

    We first get a reference to the contentBox, and then use this to select the title node. Remember this is the container in which reside the title and subtitle in the header of the widget.

    If the title node already exists, we remove it using YUI’s remove() method. We also set the _titleNode of the widget to null. If the node doesn’t exist, we simple call the _createTitle() method of our widget to generate and display it.

    Next we can handle the showUI attribute changing:

    _afterShowUIChange: function () {
        var contentBox = this.get("contentBox"),
            ui = contentBox.one(".yui3-tweetsearch-ui");
    
        if (ui) {
            ui.remove();
            this._uiNode = null;
        } else {
            this._createSearchUI();
        }
    },

    This method is almost identical to the last one — all that changes is that we are looking for the change of a different attribute, and either removing or creating a different group of elements. Again, we set the _uiNode property of our widget to null, so that the widget is aware of the latest state of its UI.

    Our next method is called after the term attribute changes:

    _afterTermChange: function () {
        this._viewerNode.empty().hide();
        this._loadingNode.show();
    
        this._retrieveTweets();
        if (this._titleNode) {
            this._uiSetTitle(this.get("term"));
    	}
    },

    When the term attribute changes, we first remove any previous search results from the viewer by calling YUI’s (specifically the Node module’s) empty() method followed by the hide() method. We also show our loader node for some visual feedback that something is happening.

    We then call our _retrieveTweets() method to initiate a new request to Twitter’s search API. This will trigger a cascade of additional methods to be called, that result ultimately in the viewer being updated with a new set of tweets. Finally, we check whether the widget currently has a _titleNode, and if so we call the _uiSetTitle() method in order to update the subtitle with the new search term.

    Our last attribute change-handler is by far the largest and deals with the tweets attribute changes, which will occur as a result of the request to Twitter being made:

    _afterTweetsChange: function () {
        var x,
            results = this.get("tweets").results,
            not = this.get("numberOfTweets"),
            limit = (not > results.length - 1) ? results.length : not;
    
        if (results.length) {
    
            for (x = 0; x < limit; x++) {
                var tweet = results[x],
                    text = this._formatTweet(tweet.text),
                    tweetNode = Node.create(Y.substitute(TweetSearch.TWEET_TEMPLATE, {
                        userurl: " [twitter.com] + tweet.from_user, avatar: tweet.profile_image_url,
                        username: tweet.from_user, text: text
                    }));
    
                if (this.get("showUI") === false && x === limit - 1) {
                    tweetNode.addClass("last");
                }
                this._viewerNode.appendChild(tweetNode);
            }
    
            this._loadingNode.hide();
            this._viewerNode.show();
        } else {
            var errorNode = Node.create(Y.substitute(TweetSearch.ERROR_TEMPLATE, {
    	        errorclass: TweetSearch.ERROR_CLASS,
                message: this.get("strings").errorMsg
            }));
    
            this._viewerNode.appendChild(errorNode);
            this._loadingNode.hide();
            this._viewerNode.show();
        }
    },

    First up, we set the variables we’ll need within the method including a counter variable for use in the for loop, the results array from the response that is stored in the tweets attribute, the value of the numberOfTweets attribute and the limit, which is either the number of results in the results array, or the configured number of tweets if there are fewer items in the array than the number of tweets.

    The remaining code for this method is encased within an if conditional which checks to see if there are actually results, which may not be the case if there were no tweets containing the search term. If there are results in the array, we iterate over each of them using a for loop. On each iteration, we get the current tweet and pass it to a _formatTweet() utility method that will add any links, usernames or hash tags found within the text, and then create a new node for the tweet using the same principles that we looked at in the last part of this tutorial.

    When the searchUI is not visible, we should alter the styling of the widget slightly to prevent a double border at the bottom of the widget. We check whether the showUI attribute is set to false, and is the last tweet being processed, and if so add the class name last to the tweet using YUI’s addClass() method. We then add the newly created node to the viewer node to display it in the widget.

    After the for loop has completed, we hide the loading node, which will at this point be visible having already been displayed earlier on, and then show the viewer node.

    If the results array does not have a length, it means that the search did not return any results. In this case, we create an error node to display to the user and append it to the viewer node, then hide the loading node and show the viewer node as before.

    A Final Utility Method

    We’ve added all of the methods that support changing attribute values. At this point, we have just one further method to add; the _formatTweet() method that we reference from the within the for loop of the method we just added. This method is as follows:

    _formatTweet: function (text) {
    
        var linkExpr = /(\b [https?|ftp):\]         atExpr = /(@[\w]+)/g,
            hashExpr = /[#]+[A-Za-z0-9-_]+/g,
            string = text.replace(linkExpr, function (match) {
                return match.link(match);
            });
    
        string = string.replace(atExpr, function (match) {
            return match.link(" [twitter.com] + match.substring(1));
        });
        string = string.replace(hashExpr, function (match) {
            return match.link(" [twitter.com] + encodeURI(match));
        });
    
        return string;
    }

    This method accepts a single argument, which is the text from the ‘current’ item of the results array that we want to linkify/atify/hashify. We start by defining three regular expressions, the first will match any links within the text that start with [http,] https or ftp and contain any characters that are allowed within URLs. The second will match any Twitter usernames (any strings that start with the @ symbol), and the last will match any strings that start with the # symbol.

    We then set a variable called string which is used to contain the transformed text. First, we add the links. JavaScript’s replace() function accepts the regular expression for matching links as the first argument and a function as the second argument — the function will be executed each time a match is found and is passed the matching text as an argument. The function then returns the match having converted it to a link element using JavaScript’s link() function. This function accepts a URL that is used for the href of the resulting link. The matching text is used for the href.

    We then use the replace() function on the string once again, but this time we pass in the @ matching regular expression as the first argument. This function works in the same way as before, but also adds Twitter’s URL to the start of the href that is used to wrap the matching text. The string variable is then operated on in the same way to match and convert any hashed words, but this time Twitter’s search API URL is used to create the link(s). After the text has been operated on, we return the resulting string.

    This brings us to the end of our widget’s class; at this point we should have an almost fully functioning widget (we haven’t yet added the paging, this will be the subject of the next and final instalment in this series). We should be able to run the page and get results:

    Nettuts+ Image Styling the Widget

    We should provide at least 2 style sheets for our widget; a base style sheet that contains the basic styles that the widget requires in order to display correctly, and a theme style sheet that controls how the widget appears visually. We’ll look at the base style sheet first; add the following code to a new file:

    .yui3-tweetsearch-title { padding:1%; }
    .yui3-tweetsearch-title h1, .yui3-tweetsearch-title h2 { margin:0; float:left; }
    .yui3-tweetsearch-title h1 { padding-left:60px; margin-right:1%; background:url(/img/logo.png) no-repeat 0 50%; }
    .yui3-tweetsearch-title h2 { padding-top:5px; float:right; font-size:100%; }
    .yui3-tweetsearch-content { margin:1%; }
    .yui3-tweetsearch-viewer article, .yui3-tweetsearch-ui { padding:1%; }
    .yui3-tweetsearch-viewer img { width:48px; height:48px; margin-right:1%; float:left; }
    .yui3-tweetsearch-viewer h1 { margin:0; }
    .yui3-tweetsearch-label { margin-right:1%; }
    .yui3-tweetsearch-input { padding:0 0 .3%; margin-right:.5%; }
    .yui3-tweetsearch-title:after, .yui3-tweetsearch-viewer article:after,
    .yui3-tweetsearch-ui:after { content:""; display:block; height:0; visibility:hidden; clear:both; }

    Save this style sheet as tweet-search-base.css in the css folder. As you can see, we target all of the elements within the widget using the class names we generated in part one. There may be multiple instances of the widget on a single page and we don’t want our styles to affect any other elements on the page outside of our widget, so using class names in this way is really the only reliable solution.

    The styling has been kept as light as possible, using only the barest necessary styles. The widget has no fixed width and uses percentages for things like padding and margins so that it can be put into any sized container by the implementing developer.

    Next, we can add the skin file; add the following code in another new file:

    .yui3-skin-sam .yui3-tweetsearch-content { border:1px solid #A3A3A3; border-radius:7px; }
    .yui3-skin-sam .yui3-tweetsearch-title { border-bottom:1px solid #A3A3A3; border-top:1px solid #fff; background-color:#EDF5FF; }
    .yui3-skin-sam .yui3-tweetsearch-title span { color:#EB8C28; }
    .yui3-skin-sam .yui3-tweetsearch-loader, .yui3-skin-sam .yui3-tweetsearch-error { padding-top:9%; margin:2% 0; color:#EB8C28; font-weight:bold; text-align:center; background:url(/img/ajax-loader.gif) no-repeat 50% 0; }
    .yui3-skin-sam .yui3-tweetsearch-error { background-image:url(/img/error.png); }
    .yui3-skin-sam .yui3-tweetsearch article { border-bottom:1px solid #A3A3A3; border-top:2px solid #fff; background:#f9f9f9; background:-moz-linear-gradient(top, #f9f9f9 0%, #f3f3f3 100%, #ffffff 100%); background:-webkit-gradient(linear, left top, left bottom, color-stop(0%,#f9f9f9), color-stop(100%,#f3f3f3), color-stop(100%,#ffffff)); background:-webkit-linear-gradient(top, #f9f9f9 0%,#f3f3f3 100%,#ffffff 100%); background:-o-linear-gradient(top, #f9f9f9 0%,#f3f3f3 100%,#ffffff 100%); background:-ms-linear-gradient(top, #f9f9f9 0%,#f3f3f3 100%,#ffffff 100%); background:linear-gradient(top, #f9f9f9 0%,#f3f3f3 100%,#ffffff 100%); filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#f9f9f9', endColorstr='#ffffff',GradientType=0); }
    .yui3-skin-sam .yui3-tweetsearch article.last { border-bottom:none; }
    .yui3-skin-sam .yui3-tweetsearch a { color:#356DE4; }
    .yui3-skin-sam .yui3-tweetsearch a:hover { color:#EB8C28; }
    .yui3-skin-sam .yui3-tweetsearch-ui { border-top:1px solid #fff; background-color:#EDF5FF; }

    Save this file as tweet-search-skin.css in the css folder. Although we also use our generated class names here, each rule is prefixed with the yui3-skin-sam class name so that the rules are only applied when the default Sam theme is in use. This makes it very easy for the overall look of the widget to be changed. This does mean however that the implementing developer will need to add the yui3-skin-sam class name to an element on the page, usually the , but this is likely to be in use already if other modules of the library are being used.

    Like before, we’ve added quite light styling, although we do have a little more freedom of expression with a skin file, hence the subtle niceties such as the rounded-corners and css-gradients. We should also recommended that the css-reset, css-fonts and css-base YUI style sheets are also used when implementing our widget, as doing so is part of the reason the custom style sheets used by the widget are nice and small.

    Implementing the Widget

    Our work as widget builders is complete (for now), but we should spend a little while looking at how the widget is actually used. Create the following HTML page in your text editor:

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <title>YUI3 Twitter Search Client</title>
            <link rel="stylesheet" href=" [yui.yahooapis.com]         <link rel="stylesheet" href="css/tweet-search-base.css" />
            <link rel="stylesheet" href="css/tweet-search-skin.css" />
        </head>
        <body class="yui3-skin-sam">
            <div id="ts"></div>
            <script src="//yui.yahooapis.com/3.4.1/build/yui/yui-min.js"></script>
            <script src="js/tweet-search.js"></script>
            <script>
                YUI().use("tweet-search", function (Y) {
                    var myTweetSearch = new Y.DW.TweetSearch({
                        srcNode: "#ts"
                    });
                    myTweetSearch.render();
                });
            </script>
        </body>
    </html>

    The only YUI script file we need to link to is the YUI seed file which sets up the YUI global object and loads the required modules.

    Save this file in the root project directory. First of all we link to the CDN hosted YUI reset, base and fonts combined style sheet, as well as our two custom style sheets that we just created. We also add the yui3-skin-sam class name to the of the page to pick up the theme styling for our widget. On the page, we add a container for our widget and give it an id attribute for easy selecting.

    The only YUI script file we need to link to is the YUI seed file; this file sets up the YUI global object and contains the YUI loader which dynamically loads the modules required by the page. We also link to our plugin’s script file, of course.

    Within the final script element we instantiate the YUI global object and call the use() method specifying our widget’s name (not the static NAME used internally by our widget, but the name specified in the add() method of our widget’s class wrapper) as the first argument.

    Each YUI instance is a self-contained sandbox in which only the named modules are accessible.

    The second argument is an anonymous function in which the initialisation code for our widget is added. This function accepts a single argument which refers to the current YUI instance. We can use any number of YUI objects on the page, each with its own modules. Each YUI instance is a self-contained sandbox in which only the named modules (and their dependencies) are accessible. This means we can have any number of self-contained blocks of code, all independent from each other on the same page.

    Within the callback function, we create a new instance of our widget stored in a variable. Our widget’s constructor is available via the namespace we specified in the widget’s class, which is attached to the YUI instance as a property. Our widget’s constructor accepts a configuration object as an argument; we use this to specify the container that we want to render our widget into, in this case the empty <div> we added to the page. The specified element will become the contentBox of our widget. Finally, we call the render() method on the variable our widget instance is stored in, which renders the HTML for our widget into the specified container.

    In the configuration object, we can override any of the default attributes of our widget, so if we wanted to disable the title of the widget and the search UI, we could pass the following configuration object into our widget’s constructor:

    {
        srcNode: "#ts",
        showTitle: false,
        showUI: false
    }

    I mentioned in an earlier part of the widget that by including all of the text strings used by the widget in an attribute, we could easily enable extremely easy internationalization. To render the widget in Spanish, for example, all we need to do is override the strings attribute, like this:

    {
        srcNode: "#ts",
        strings: {
            title: "Twitter Search Widget",
            subTitle: "Mostrando resultados de:",
            label: "Término de búsqueda",
            button: "Búsqueda",
            errorMsg: "Lo siento, ese término de búsqueda no ha obtenido ningún resultado. Por favor, intente un término diferente"
        }
    }

    Now when we run the widget, all of the visible text (aside from the tweets of course) for the widget is in Spanish:

    Nettuts+ Image Summary

    In this part of the tutorial, we completed our widget by adding the attribute change-handling methods and a small utility method for formatting the flat text of each tweet into mark-up. We also looked at the styling required by our widget and how the styles should be categorized, i.e. whether they are base styles or skin styles.

    We also saw how easy it is to initialise and configure the widget and how it can easily be converted into display in another language. In the next part of this tutorial, we’ll look at a close relative to the widget – the plugin and add a paging feature to our widget.


  • Permalink for 'Ten New Year’s Resolutions Every Web Developer Should Make'

    Ten New Year’s Resolutions Every Web Developer Should Make

    Posted: December 27th, 2011, 9:00am MST by Andrew Burgess

    In less than a week, we’ll be in 2012. I know it’s a cliché, but where has the year gone? Naturally, we’re now at the time of year when folks set goals for the new year. While you might have some goals for your “real” life, how about a few resolutions for your developer life?

    1 - Learn a New Language, Framework, Or Methodology Learn a New Language

    We must continue learning about the latest technologies.

    About the only constant when it comes to developing for the web is change. Take NodeJS, for example: two or three years ago, it didn’t exist, and there was very little (if any) JavaScript being done on the server. Now, you can’t get away from it. Every web developer wants to stay on top of their game. To do so, we must continue learning about the latest technologies. If you’re a back-end dev, that could mean learning JavaScript and Node.js. It could mean taking up Ruby and Rails. For the front-end developer, that could mean really grokking CSS3, or understanding the new HTML5 APIs. Of course, that doesn’t mean you have to use it regularly; just keep yourself learning.

    Along the same lines, now is as good a time as ever to re-evaluate your workflow, and learn better and different tools to get the job done more quickly.

    2 - Get Better At What You Know Get Better

    Set aside some time to also focus on existing languages and software.

    Of course, staying sharp means more than learning new things. It also refers to improving in your use of your daily tools. I know I’ve been guilty of sticking with the patterns and methods that I’m comfortable with, and not learning new ones that might be better for a given situation. How knowledgeable are you about JavaScript design patterns? Do you have a solid understanding of object-oriented and functional programming in PHP? Have you used SQL joins? Are there any features your text editor offers that you aren’t using? These aren’t new technologies, but, if you aren’t using them, they’re new to you! Set aside some time to also focus on existing languages and software.

    3 - Explore a New Field Explore

    This resolution is a different twist on the first one. Learning a new language, framework, or methodology in your own field is great, and might even be useful to your daily practice. But if you’re like me, you’re fascinated with every part of the web. Try exploring new fields. Back-end devs: look into front-end development. Front-ends, explore usability or user experience more than you have before. If you enjoy writing, you might be interested in content strategy, or fostering that design flare. There are dozens of fields on the web; explore!

    4 - Engage the Community Engage

    Call it engaging, call it networking, call it whatever your want.

    The web is a pretty incredible place: I can’t think of any other phenomenon that has ever made such strong friendships between people so far apart. In 2012, why don’t you try to engage this group of amazing people a bit more? Talk to them on Twitter; read their blog posts and comment or write your own articles in response; contribute to their code via Github, or another code-sharing site. Or, go to meet-ups, user groups and conferences. Call it engaging, call it networking, call it whatever your want; but one thing’s for sure: it will (in most cases) benefit both you and the other person. In addition to building great personal relationships, you’ll likely gain new referrals!

    5 - Teach Others Teach

    The most beneficial comments are the ones that hurt your feelings.

    Going hand-in-hand with our previous point, you should resolve to teach others more in 2012. Why? Well, how does it go, “Teaching something is the best way to learn it”? I’ve been writing for Nettuts+ for close to three years, and I can attest that that statement is completely true. Writing down exactly how a concept works forces you to understand it completely; you’ll be surprised how much you’ll learn about your topic when you try to teach it. On top of that, there’s the incredible feeling you get when you know that you’ve helped someone learn a new skill set.

    Undoubtedly, you’ll face a few trolls, pointing out legitimate mistakes ( or just making stabby comments). Not to worry (too much); teaching is a learning process, and you’ll improve the more you do it. The most beneficial comments are the ones that hurt your feelings.

    6 - Take Better Care Of Yourself Take Care

    We are the martyrs of the web.

    We web developers seem to pride ourselves on our dedication to our craft. We’ll work long hours, hunched over a computer in the dark, so absorbed in our work that we forget to shower or eat. We are the martyrs of the web, suffering to make the internet a better place.

    Sounds heroic, but it really isn’t.

    At the risk of mommying you, I’m going to suggest that you take care of yourself in 2012. Besides sleeping and eating well, make sure your workplace is ergonomic. It stands to reason that, if you spend a third of your life in your office, it might make sense to make it as comfortable as possible!

    7 - Manage Your Time (and Other Resources) Better Manage Your Time

    Over 1 trillion videos were watched on Youtube this past year.

    Perhaps this isn’t specificly related to web developers, but it is, nonetheless, something that almost every “knowledge worker” can afford to get better at. For a lot of us—especially freelancers—what you’re doing with your time could be the difference between feasting and fasting. Remember all those fun, new web technologies I recommended you learn about? Well, don’t let their lure limit your bacon-bringing hours to few and far between. Of coures, the internet at large can be just as much of a distraction. I’m sure you saw this recently; it gave pause when I did:

    Over 1 trillion videos were watched on Youtube this past year. That's 550 videos per person with internet access. Insane. - John Resig on Twitter

    Assuming that the average YouTube video is 2 – 3 minutes long, we’re looking at something to the tune of one whole day. Something tells me I’m not much better off for it.

    Of course, “all work, no play” and all that, right? I’m not suggesting you be a slave to your clients, or an unbearably dull workaholic. I’m merely stating that we would all be wise to track exactly where our hours are going and make an effort to use them a little better.

    8 - Use Better Programming Practices Use Better Practices

    I don’t think you’ll ever have an issue with over-documentation.

    No, I’m not repeating resolution two in different words. This time, I’m talking about the practices that surround the actual coding itself. I can’t tell you how many times I’ve eagerly started a new project, and—half an hour later—said, “Hmmm . . . I should create a branch to try this feature. Oh, wait, I forgot to initialize Git when I started . . .” Making sure I remember to use code versioning from the beginning is something I’m going to be working on in 2012; it keeps your project history so much cleaner.

    Another meta-coding practice I usually neglect (to my detriment) is commenting. I’ll conjure up a few clever lines of code, and be tickled for the rest of the day. Next week, I’ll return and spend twenty minutes trying to figure out what it does. This plagues you too? Do yourself a favor and leave useful comments to yourself, and others. Documentation is right along the same lines as commenting. When I was recently learning Dojo, I found its in-code documentation to be invaluable. Of course, the level of documentation will depend on the publicity of your project, but I don’t think you’ll ever have an issue with over-documentation.

    9 - Generate Passive Income Generate Passive Income

    I’m guessing that most of the Nettuts+ audience performs client work, either as a freelancer or otherwise. Well why not make some passive income on the side? Envato has ten (count `em!) marketplaces where anyone with the right skills can profit. Build a theme for Themeforest, write a script for CodeCanyon, the possibilities are close to endless. Of course, if your skills don’t trade on the Envato marketplaces—or even if they do—there are bunches of other ways to make passive income. If you’re a writer, for example, check out Tuts+ Premium. They’re always looking for new passionate teachers.

    The manager of Tuts+ Premium, Skellie, recently opened the Passive Income Author blog, where you’ll find great information on self-publishing.

    Selling items on a marketplace or personal website is a brilliant way to passively make some extra cash while still doing exactly what you enjoy.

    10 - Take a Break Take a Break

    Photo by brettanicus

    Put on a completely different hat… sometimes

    So far, every resolution has been something you can do to improve your craft as a developer. I’ll close by noting that one of the best things you can do to become a better developer is to not be a developer . . . sometimes. Put on a completely different hat… sometimes. Keep another hobby that’s not even tangentially related to development, and, preferably, doesn’t involve computers. Some play an instrument, some read, some write, some cook. Whatever you do, set aside some get-away time. When you do so, you’ll find that solutions to programming problems often show up on during time off.

    I solve so many coding issues while thinking on my way home in the car

    Certainly, regular breaks are important, but so are those longer, couple-times-a-year vacation / holiday breaks. Throw a few of those in your annual schedule as well!

    Your Resolutions?

    Well, that’s my list of ten resolutions all web developers should make. Have any of your own that aren’t on my list? Let’s hear them in the comments!


  • Permalink for 'Recently in Web Development (December Edition)'

    Recently in Web Development (December Edition)

    Posted: December 26th, 2011, 8:27pm MST by Siddharth

    Web development is an industry that’s in a state of constant flux with technologies and jargon changing and mutating in an endless cycle. Not to mention the sheer deluge of information one has to process everyday.

    In this series, published monthly, we’ll seek to rectify this by bringing you all the important news, announcements, releases and interesting discussions within the web development industry in a concise package. Join me after the jump!

    News and Releases

    All of the important news in a single place: releases, announcements, companies bickering, security issues and all related hoopla.

    Nettuts image Chrome Overtakes Firefox Globally for First Time

    I admit I saw this coming but never so quickly. Chrome has overtaken Firefox in global marketshare. Chrome accounts for 25.69% of the user pie while Firefox is at 25.23%.

    Chrome’s number has been increasing lately, overtaking Firefox in the UK, for example. This month, though, sees it leading Firefox for the first time on a global scale. Congrats to the Chrome team!

    Read more

    Nettuts image Facebook Creates HipHop VM to Improve Performance with PHP

    It’s no secret that Facebook utilizes PHP on the backend to serve its multi-billion pageviews a month service. PHP’s ease of use has also lead to dismal performance and inability to scale.

    In the past, Facebook resorted to optimizing the Zend engine but later went with creating their own PHP interpreter. The new HipHop VM is just another step towards making their PHP codebase run faster.

    Read more

    Nettuts image SOPA Protests Wash Over the Internet

    I don’t wish to editorialize the contents and ramifications of SOPA so it’s best you read up on the Wikipedia page linked below.

    Internet users and services worldwide, however, have organized widespread protests in opposition of this bill with the backing of internet giants like the Wikimedia foundation and Mozilla. If you live in the US, do write to your local representatives!

    Read more

    Nettuts image Dojo 1.7 Released

    Version 1.7 of Dojo got released early this month with substantial improvements including a lot of API changes under the hood.

    Make sure to hit the link below for more information. And if you’re looking to gain mastery over Dojo, make sure to check out our session on the topic.

    Read more

    Nettuts image SproutCore 2.0 Gets Renamed. And Renamed Again, For Good Measure

    I love Sproutcore and tend to use it in a lot of my experiments. The framework has been moving steadily towards version 2.0 and was renamed to Amber.js in the process. Due to a naming collision, with Smalltalk people no less, SproutCore 2.0 is now officially Ember.js

    If you’re curious as to the rationale behind all this renaming, you can find a lot more at the link below.

    Read more

    Nettuts image WordPress 3.3 is Now Live

    The WordPress juggernaut rolls on with version 3.3 codenamed ‘Sonny’. The version ships with, to quote the devs themselves, “significant polish around the new user experience, navigation, uploading, and imports”.

    WP.Tuts+ has a great overview of the new version, if you’re interested. Also, remember to check out the sweet, short video at the link below.

    Read more

    Nettuts image Sencha Fiddle is Out

    Sencha Fiddle is an IDE that lets you start creating mobile applications through your browser. Even though it’s not finished yet, the features already in place are great and work well.

    Read more

    Nettuts image Rails Hits 4.0 Beta

    The Rails master branch has officially hit the 4.0 beta mark. Big changes here include dropping support for Ruby 1.8.7. If you’re running the older version of Ruby, stick to the 3.x branch and hang tight for 3.2 to be released!

    Read more

    Nettuts image Arduino 1.0 Released

    And to get slightly nerdy, Arduino has finally hit version 1.0. If you’re unsure as to what Arduino is, it’s a microcontroller which you can program through the Arduino environment.

    Version 1 brings a lot of changes including API changes, new classes and much more. You can get to the release notes directly here.

    Read more

    New Kids on the Block

    As web developers, the sheer amount of resources we can tap into increases exponentially with time. Here is just a quick look at some recently created resources that deserve your attention — everything from new books to scripts and frameworks.

    Nettuts image stopcensorship.js

    Use this script on your site to protest censorship of the Internet.

    After the page is loaded the script randomly censors text on the page by replacing the text with black bars. It also places a black bar at the top of the page with a link to [americancensorship.org] Viewers can remove censoring for the current session by clicking on the “Remove this” link.

    Read more

    Nettuts image Sinatra::Synchrony

    Sinatra::Synchrony is a small extension for Sinatra that dramatically improves the concurrency of your web application. Powered by EventMachine and EM-Synchrony, it increases the number of clients your application can serve per process when you have a lot of traffic and slow IO calls (like HTTP calls to external APIs).

    Read more

    Nettuts image jQuery Gantt Chart

    jQuery Gantt Chart is a simple chart that implements gantt functionality as
    a jQuery component. It’s able to page results and read JSON data amongst a ton of other features.

    Read more

    Nettuts image Create

    Create, from the Midgard Project is a comprehensive web editing interface for Content Management Systems. It is designed to provide a modern, fully browser-based HTML5 environment for managing content. Create can be adapted to work on almost any content management backend.

    Read more

    Nettuts image Rickshaw

    Rickshaw is a JavaScript toolkit for creating interactive time series graphs.

    Read more

    Nettuts image nanoScroller.js

    nanoScroller.js is a jQuery plugin that offers a simplistic way of implementing Lion-styled scrollbars for your website. It uses minimal HTML markup and the latest version utilizes native scrolling and works with the iPad, iPhone, and some Android Tablets.

    Read more

    Nettuts image bootbox.js

    Enter bootbox.js – alert() and confirm() like behaviour using twitter’s modal dialog boxes.

    Read more

    Nettuts image Broadway

    A JavaScript H.264 and VP8/WebM decoder.

    Read more

    Nettuts image gitdocs

    Open-source dropbox alternative powered by git. Collaborate on files and tasks without any extra hassle. gitdocs will automatically keep everyone’s repos in sync by pushing and pulling changes. This allows any git repo to be used as a collaborative task list, file share, or wiki for a team. Supports a web front-end allowing each repo to be accessed through your browser.

    Read more

    Best of the Internet

    Often, you’re not really looking for a tutorial as much as you’re looking for a rant, an opinion or the musings of a tired developer or just something cool with absolutely zero real world use. This sections contains links to precisely those — interesting and cool stuff from the developer community.

    Nettuts image Why HTML5 Media is not Enough

    Amos Wenger on why the media elements introduced with the HTML5 spec aren’t evolving fast enough and how he’s countering the issues he’s facing.

    Read more

    Nettuts image What Tools Developers Actually Use

    A great inforgraphic charting out the tools that developers use and love. There isn’t too much data here but should give you a quick overview as to what your peers are using.

    Read more

    Nettuts image Backbone.js Fundamentals

    Addy Osmani is back again with a great little ebook on working with Backbone.js. The content goes over every aspect of the Backbone framework so if you’re even remotely interested in working with it, this is a great place to start.

    Read more

    Nettuts image Cracks in the Foundation

    A clear, concise look at what’s wrong with the PHP platform. If you’re a PHP user, prepare to go in with some denial.

    Read more

    Wrapping Up

    Well, that’s about all the major changes that happened in our industry lately.

    Do you want us to cover more standard news? A focus on upcoming scripts maybe? Or just more interesting posts and discussions from the community? Let us know in the comments and thank you so much for reading!


  • Permalink for 'Happy Holidays from Tuts+!'

    Happy Holidays from Tuts+!

    Posted: December 25th, 2011, 10:06am MST by David Appleyard

    The holidays are upon us, and we’re feeling festive at Tuts+ this weekend! We’d like to take this opportunity to say a huge Christmas thank you to all our readers, and wish you a very Happy Holiday. Read on for a video message from the HQ team, and a few freebies from around the Tuts+ and Envato network!

    A Message from Envato HQ

    Although the Tuts+ team is spread over the globe, Envato HQ is where much of the Tuts+ magic happens! It isn’t looking traditionally Christmassy in Melbourne at the moment, but we have a special holiday message from everyone at head office:

    From everyone at Envato we want to wish you a Happy Holidays and look forward to seeing you all refreshed and ready for another big year in 2012! From Envato HQ to the community, we’ve created a little video to share the holiday cheer. Enjoy!

    Music is Kids Holiday Theme by AudioJungle Author CraigHall

    Gift Guides & Freebies!

    Wondering what to buy your fellow geek this Christmas? Never fear! You may have left it it a little late, but our holiday gift guides can still come in handy. Here are a few great places to start:

    We also have a couple of exclusive freebies and discounts, just in time for the holidays:

    The Christmas Freelance Freedom Comic

    The “holiday jingle” comic encapsulates everything that we love and hate about freelancing. Don’t forget to sing along to the “Jungle Bells” theme music as you read it…!

    You can also enjoy the whole back catalog of Freelance Freedom comics over at FreelanceSwitch.

    AppStorm Giveaways

    We have two fantastic competitions running over at the AppStorm network over the holiday period, and there’s still time to get your entry in to stand a chance of winning:

    1. Business Productivity Bundle Giveaway —Each bundle includes a license to Daylite and Billings Pro – it’s the perfect combination for getting your business organised and making money!
    2. The AppStorm Holiday ’11 Video Game Giveaway — In the spirit of this season we’ve hand picked a few critically acclaimed, and award-winning, games released over this year to give away to our readers!
    Merry Christmas, and Happy New Year!

    All that’s left is to wish you a very happy holiday on behalf of everyone at Tuts+! We hope you’ve enjoyed everything that we’ve had to share this year, and look forward to publishing thousands more top-quality tutorials, articles, freebies, and resources in 2012.

    Here’s to another exciting year at Tuts+, and thank you for joining us on the journey!


  • Permalink for 'Object-Oriented PHP for Beginners'

    Object-Oriented PHP for Beginners

    Posted: December 23rd, 2011, 6:53am MST by Jason Lengstorf

    Twice a month, we revisit some of our readers’ favorite posts from through out the history of Nettuts+. This tutorial was first published in July, 2010.

    For many PHP programmers, object-oriented programming is a frightening concept, full of complicated syntax and other roadblocks. As detailed in my book, Pro PHP and jQuery, you’ll learn the concepts behind object-oriented programming (OOP), a style of coding in which related actions are grouped into classes to aid in creating more-compact, effective code.

    Understanding Object-Oriented Programming

    Object-oriented programming is a style of coding that allows developers to group similar tasks into classes. This helps keep code following the tenet “don’t repeat yourself” (DRY) and easy-to-maintain.

    “Object-oriented programming is a style of coding that allows developers to group similar tasks into classes.”

    One of the major benefits of DRY programming is that, if a piece of information changes in your program, usually only one change is required to update the code. One of the biggest nightmares for developers is maintaining code where data is declared over and over again, meaning any changes to the program become an infinitely more frustrating game of Where’s Waldo? as they hunt for duplicated data and functionality.

    OOP is intimidating to a lot of developers because it introduces new syntax and, at a glance, appears to be far more complex than simple procedural, or inline, code. However, upon closer inspection, OOP is actually a very straightforward and ultimately simpler approach to programming.

    Understanding Objects and Classes

    Before you can get too deep into the finer points of OOP, a basic understanding of the differences between objects and classes is necessary. This section will go over the building blocks of classes, their different capabilities, and some of their uses.

    Recognizing the Differences Between Objects and Classes

    Photos by Instant Jefferson and John Wardell

    “Developers start talking about objects and classes, and they appear to be interchangeable terms. This is not the case, however.”

    Right off the bat, there’s confusion in OOP: seasoned developers start talking about objects and classes, and they appear to be interchangeable terms. This is not the case, however, though the difference can be tough to wrap your head around at first.

    A class, for example, is like a blueprint for a house. It defines the shape of the house on paper, with relationships between the different parts of the house clearly defined and planned out, even though the house doesn’t exist.

    An object, then, is like the actual house built according to that blueprint. The data stored in the object is like the wood, wires, and concrete that compose the house: without being assembled according to the blueprint, it’s just a pile of stuff. However, when it all comes together, it becomes an organized, useful house.

    Classes form the structure of data and actions and use that information to build objects. More than one object can be built from the same class at the same time, each one independent of the others. Continuing with our construction analogy, it’s similar to the way an entire subdivision can be built from the same blueprint: 150 different houses that all look the same but have different
    families and decorations inside.

    Structuring Classes

    The syntax to create a class is pretty straightforward: declare a class using the class keyword, followed by the name of the class and a set of curly braces ({}):

    <?php
    
    class MyClass
    {
        // Class properties and methods go here
    }
    
    ?>
    

    After creating the class, a new class can be instantiated and stored in a variable using the new keyword:

    $obj = new MyClass;
    

    To see the contents of the class, use var_dump():

    var_dump($obj);
    

    Try out this process by putting all the preceding code in a new file called test.php in [your local] testing folder:

    <?php
    
    class MyClass
    {
    	// Class properties and methods go here
    }
    
    $obj = new MyClass;
    
    var_dump($obj);
    
    ?>
    

    Load the page in your browser at http://localhost/test.php and the following should display:

    object(MyClass)#1 (0) { }
    

    In its simplest form, you’ve just completed your first OOP script.

    Defining Class Properties

    To add data to a class, properties, or class-specific variables, are used. These work exactly like regular variables, except they’re bound to the object and therefore can only be accessed using the object.

    To add a property to MyClass, add the following code to your script:

    <?php
    
    class MyClass
    {
        public $prop1 = "I'm a class property!";
    }
    
    $obj = new MyClass;
    
    var_dump($obj);
    
    ?>
    

    The keyword public determines the visibility of the property, which you’ll learn about a little later in this chapter. Next, the property is named using standard variable syntax, and a value is assigned (though class properties do not need an initial value).

    To read this property and output it to the browser, reference the object from which to read and the property to be read:

    echo $obj->prop1;
    

    Because multiple instances of a class can exist, if the individual object is not referenced, the script would be unable to determine which object to read from. The use of the arrow (->) is an OOP construct that accesses the contained properties and methods of a given object.

    Modify the script in test.php to read out the property rather than dumping the whole class by modifying the code as shown:

    <?php
    
    class MyClass
    {
        public $prop1 = "I'm a class property!";
    }
    
    $obj = new MyClass;
    
    echo $obj->prop1; // Output the property
    
    ?>
    

    Reloading your browser now outputs the following:

    I'm a class property!
    
    Defining Class Methods

    Methods are class-specific functions. Individual actions that an object will be able to perform are defined within the class as methods.

    For instance, to create methods that would set and get the value of the class property $prop1, add the following to your code:

    <?php
    
    class MyClass
    {
        public $prop1 = "I'm a class property!";
    
        public function setProperty($newval)
        {
            $this->prop1 = $newval;
        }
    
        public function getProperty()
        {
            return $this->prop1 . "<br />";
        }
    }
    
    $obj = new MyClass;
    
    echo $obj->prop1;
    
    ?>
    

    Note — OOP allows objects to reference themselves using $this. When working within a method, use $this in the same way you would use the object name outside the class.

    To use these methods, call them just like regular functions, but first, reference the object they belong to. Read the property from MyClass, change its value, and read it out again by making the modifications below:

    <?php
    
    class MyClass
    {
        public $prop1 = "I'm a class property!";
    
        public function setProperty($newval)
        {
            $this->prop1 = $newval;
        }
    
        public function getProperty()
        {
            return $this->prop1 . "<br />";
        }
    }
    
    $obj = new MyClass;
    
    echo $obj->getProperty(); // Get the property value
    
    $obj->setProperty("I'm a new property value!"); // Set a new one
    
    echo $obj->getProperty(); // Read it out again to show the change
    
    ?>
    

    Reload your browser, and you’ll see the following:

    I'm a class property!
    I'm a new property value!
    

    “The power of OOP becomes apparent when using multiple instances of the
    same class.”

    <?php
    
    class MyClass
    {
        public $prop1 = "I'm a class property!";
    
        public function setProperty($newval)
        {
            $this->prop1 = $newval;
        }
    
        public function getProperty()
        {
            return $this->prop1 . "<br />";
        }
    }
    
    // Create two objects
    $obj = new MyClass;
    $obj2 = new MyClass;
    
    // Get the value of $prop1 from both objects
    echo $obj->getProperty();
    echo $obj2->getProperty();
    
    // Set new values for both objects
    $obj->setProperty("I'm a new property value!");
    $obj2->setProperty("I belong to the second instance!");
    
    // Output both objects' $prop1 value
    echo $obj->getProperty();
    echo $obj2->getProperty();
    
    ?>
    

    When you load the results in your browser, they read as follows:

    I'm a class property!
    I'm a class property!
    I'm a new property value!
    I belong to the second instance!
    

    As you can see, OOP keeps objects as separate entities, which makes for easy separation of different pieces of code into small, related bundles.

    Magic Methods in OOP

    To make the use of objects easier, PHP also provides a number of magic methods, or special methods that are called when certain common actions occur within objects. This allows developers to perform a number of useful tasks with relative ease.

    Using Constructors and Destructors

    When an object is instantiated, it’s often desirable to set a few things right off the bat. To handle this, PHP provides the magic method __construct(), which is called automatically whenever a new object is
    created.

    For the purpose of illustrating the concept of constructors, add a constructor to MyClass that will output a message whenever a new instance of the class is created:

    <?php
    
    class MyClass
    {
        public $prop1 = "I'm a class property!";
    
        public function __construct()
        {
            echo 'The class "', __CLASS__, '" was initiated!<br />';
        }
    
        public function setProperty($newval)
        {
            $this->prop1 = $newval;
        }
    
        public function getProperty()
        {
            return $this->prop1 . "<br />";
        }
    }
    
    // Create a new object
    $obj = new MyClass;
    
    // Get the value of $prop1
    echo $obj->getProperty();
    
    // Output a message at the end of the file
    echo "End of file.<br />";
    
    ?>
    

    Note — __CLASS__ returns the name of the class in which it is called; this is what is known as a magic constant. There are several available magic constants, which you can read more about in the PHP manual.

    Reloading the file in your browser will produce the following result:

    The class "MyClass" was initiated!
    I'm a class property!
    End of file.
    

    To call a function when the object is destroyed, the __destruct() magic method is available. This is useful for class cleanup (closing a database connection, for instance).

    Output a message when the object is destroyed by defining the magic method
    __destruct() in MyClass:

    <?php
    
    class MyClass
    {
        public $prop1 = "I'm a class property!";
    
        public function __construct()
        {
            echo 'The class "', __CLASS__, '" was initiated!<br />';
        }
    
        public function __destruct()
        {
            echo 'The class "', __CLASS__, '" was destroyed.<br />';
        }
    
        public function setProperty($newval)
        {
            $this->prop1 = $newval;
        }
    
        public function getProperty()
        {
            return $this->prop1 . "<br />";
        }
    }
    
    // Create a new object
    $obj = new MyClass;
    
    // Get the value of $prop1
    echo $obj->getProperty();
    
    // Output a message at the end of the file
    echo "End of file.<br />";
    
    ?>
    

    With a destructor defined, reloading the test file results in the following output:

    The class "MyClass" was initiated!
    I'm a class property!
    End of file.
    The class "MyClass" was destroyed.
    

    “When the end of a file is reached, PHP automatically releases all resources.”

    To explicitly trigger the destructor, you can destroy the object using the
    function unset():

    <?php
    
    class MyClass
    {
        public $prop1 = "I'm a class property!";
    
        public function __construct()
        {
            echo 'The class "', __CLASS__, '" was initiated!<br />';
        }
    
        public function __destruct()
        {
            echo 'The class "', __CLASS__, '" was destroyed.<br />';
        }
    
        public function setProperty($newval)
        {
            $this->prop1 = $newval;
        }
    
        public function getProperty()
        {
            return $this->prop1 . "<br />";
        }
    }
    
    // Create a new object
    $obj = new MyClass;
    
    // Get the value of $prop1
    echo $obj->getProperty();
    
    // Destroy the object
    unset($obj);
    
    // Output a message at the end of the file
    echo "End of file.<br />";
    
    ?>
    

    Now the result changes to the following when loaded in your browser:

    The class "MyClass" was initiated!
    I'm a class property!
    The class "MyClass" was destroyed.
    End of file.
    
    Converting to a String

    To avoid an error if a script attempts to output MyClass as a string, another magic method is used called __toString().

    Without __toString(), attempting to output the object as a string results in a fatal error. Attempt to use echo to output the object without a magic method in place:

    <?php
    
    class MyClass
    {
        public $prop1 = "I'm a class property!";
    
        public function __construct()
        {
            echo 'The class "', __CLASS__, '" was initiated!<br />';
        }
    
        public function __destruct()
        {
            echo 'The class "', __CLASS__, '" was destroyed.<br />';
        }
    
        public function setProperty($newval)
        {
            $this->prop1 = $newval;
        }
    
        public function getProperty()
        {
            return $this->prop1 . "<br />";
        }
    }
    
    // Create a new object
    $obj = new MyClass;
    
    // Output the object as a string
    echo $obj;
    
    // Destroy the object
    unset($obj);
    
    // Output a message at the end of the file
    echo "End of file.<br />";
    
    ?>
    

    This results in the following:

    The class "MyClass" was initiated!
    
    Catchable fatal error: Object of class MyClass could not be converted to string in /Applications/XAMPP/xamppfiles/htdocs/testing/test.php on line 40
    

    To avoid this error, add a __toString() method:

    <?php
    
    class MyClass
    {
        public $prop1 = "I'm a class property!";
    
        public function __construct()
        {
            echo 'The class "', __CLASS__, '" was initiated!<br />';
        }
    
        public function __destruct()
        {
            echo 'The class "', __CLASS__, '" was destroyed.<br />';
        }
    
        public function __toString()
        {
            echo "Using the toString method: ";
            return $this->getProperty();
        }
    
        public function setProperty($newval)
        {
            $this->prop1 = $newval;
        }
    
        public function getProperty()
        {
            return $this->prop1 . "<br />";
        }
    }
    
    // Create a new object
    $obj = new MyClass;
    
    // Output the object as a string
    echo $obj;
    
    // Destroy the object
    unset($obj);
    
    // Output a message at the end of the file
    echo "End of file.<br />";
    
    ?>
    

    In this case, attempting to convert the object to a string results in a call to the getProperty() method. Load the test script in your browser to see the result:

    The class "MyClass" was initiated!
    Using the toString method: I'm a class property!
    The class "MyClass" was destroyed.
    End of file.
    

    Tip — In addition to the magic methods discussed in this section, several others are available. For a complete list of magic methods, see the PHP manual page.

    Using Class Inheritance

    Classes can inherit the methods and properties of another class using the extends keyword. For instance, to create a second class that extends MyClass and adds a method, you would add the following to your test file:

    <?php
    
    class MyClass
    {
        public $prop1 = "I'm a class property!";
    
        public function __construct()
        {
            echo 'The class "', __CLASS__, '" was initiated!<br />';
        }
    
        public function __destruct()
        {
            echo 'The class "', __CLASS__, '" was destroyed.<br />';
        }
    
        public function __toString()
        {
            echo "Using the toString method: ";
            return $this->getProperty();
        }
    
        public function setProperty($newval)
        {
            $this->prop1 = $newval;
        }
    
        public function getProperty()
        {
            return $this->prop1 . "<br />";
        }
    }
    
    class MyOtherClass extends MyClass
    {
        public function newMethod()
        {
            echo "From a new method in " . __CLASS__ . ".<br />";
        }
    }
    
    // Create a new object
    $newobj = new MyOtherClass;
    
    // Output the object as a string
    echo $newobj->newMethod();
    
    // Use a method from the parent class
    echo $newobj->getProperty();
    
    ?>
    

    Upon reloading the test file in your browser, the following is output:

    The class "MyClass" was initiated!
    From a new method in MyOtherClass.
    I'm a class property!
    The class "MyClass" was destroyed.
    
    Overwriting Inherited Properties and Methods

    To change the behavior of an existing property or method in the new class, you can simply overwrite it by declaring it again in the new class:

    <?php
    
    class MyClass
    {
        public $prop1 = "I'm a class property!";
    
        public function __construct()
        {
            echo 'The class "', __CLASS__, '" was initiated!<br />';
        }
    
        public function __destruct()
        {
            echo 'The class "', __CLASS__, '" was destroyed.<br />';
        }
    
        public function __toString()
        {
            echo "Using the toString method: ";
            return $this->getProperty();
        }
    
        public function setProperty($newval)
        {
            $this->prop1 = $newval;
        }
    
        public function getProperty()
        {
            return $this->prop1 . "<br />";
        }
    }
    
    class MyOtherClass extends MyClass
    {
        public function __construct()
        {
            echo "A new constructor in " . __CLASS__ . ".<br />";
        }
    
        public function newMethod()
        {
            echo "From a new method in " . __CLASS__ . ".<br />";
        }
    }
    
    // Create a new object
    $newobj = new MyOtherClass;
    
    // Output the object as a string
    echo $newobj->newMethod();
    
    // Use a method from the parent class
    echo $newobj->getProperty();
    
    ?>
    

    This changes the output in the browser to:

    A new constructor in MyOtherClass.
    From a new method in MyOtherClass.
    I'm a class property!
    The class "MyClass" was destroyed.
    
    Preserving Original Method Functionality While Overwriting Methods

    To add new functionality to an inherited method while keeping the original method intact, use the parent keyword with the scope resolution operator (::):

    <?php
    
    class MyClass
    {
        public $prop1 = "I'm a class property!";
    
        public function __construct()
        {
            echo 'The class "', __CLASS__, '" was initiated!<br />';
        }
    
        public function __destruct()
        {
            echo 'The class "', __CLASS__, '" was destroyed.<br />';
        }
    
        public function __toString()
        {
            echo "Using the toString method: ";
            return $this->getProperty();
        }
    
        public function setProperty($newval)
        {
            $this->prop1 = $newval;
        }
    
        public function getProperty()
        {
            return $this->prop1 . "<br />";
        }
    }
    
    class MyOtherClass extends MyClass
    {
        public function __construct()
        {
            parent::__construct(); // Call the parent class's constructor
            echo "A new constructor in " . __CLASS__ . ".<br />";
        }
    
        public function newMethod()
        {
            echo "From a new method in " . __CLASS__ . ".<br />";
        }
    }
    
    // Create a new object
    $newobj = new MyOtherClass;
    
    // Output the object as a string
    echo $newobj->newMethod();
    
    // Use a method from the parent class
    echo $newobj->getProperty();
    
    ?>
    

    This outputs the result of both the parent constructor and the new class’s constructor:

    The class "MyClass" was initiated!
    A new constructor in MyOtherClass.
    From a new method in MyOtherClass.
    I'm a class property!
    The class "MyClass" was destroyed.
    
    Assigning the Visibility of Properties and Methods

    For added control over objects, methods and properties are assigned visibility. This controls how and from where properties and methods can be accessed. There are three visibility keywords: public, protected, and private. In addition to its visibility, a method or property can be declared as static, which allows them to be accessed without an instantiation of the class.

    “For added control over objects, methods and properties are assigned visibility.”

    Note — Visibility is a new feature as of PHP 5. For information on OOP compatibility with PHP 4, see the PHP manual page.

    Public Properties and Methods

    All the methods and properties you’ve used so far have been public. This means that they can be accessed anywhere, both within the class and externally.

    Protected Properties and Methods

    When a property or method is declared protected, it can only be accessed within the class itself or in descendant classes (classes that extend the class containing the protected method).

    Declare the getProperty() method as protected in MyClass and try to access it directly from outside the class:

    <?php
    
    class MyClass
    {
        public $prop1 = "I'm a class property!";
    
        public function __construct()
        {
            echo 'The class "', __CLASS__, '" was initiated!<br />';
        }
    
        public function __destruct()
        {
            echo 'The class "', __CLASS__, '" was destroyed.<br />';
        }
    
        public function __toString()
        {
            echo "Using the toString method: ";
            return $this->getProperty();
        }
    
        public function setProperty($newval)
        {
            $this->prop1 = $newval;
        }
    
        protected function getProperty()
        {
            return $this->prop1 . "<br />";
        }
    }
    
    class MyOtherClass extends MyClass
    {
        public function __construct()
        {
            parent::__construct();
    		echo "A new constructor in " . __CLASS__ . ".<br />";
        }
    
        public function newMethod()
        {
            echo "From a new method in " . __CLASS__ . ".<br />";
        }
    }
    
    // Create a new object
    $newobj = new MyOtherClass;
    
    // Attempt to call a protected method
    echo $newobj->getProperty();
    
    ?>
    

    Upon attempting to run this script, the following error shows up:

    The class "MyClass" was initiated!
    A new constructor in MyOtherClass.
    
    Fatal error: Call to protected method MyClass::getProperty() from context '' in /Applications/XAMPP/xamppfiles/htdocs/testing/test.php on line 55
    

    Now, create a new method in MyOtherClass to call the getProperty() method:

    <?php
    
    class MyClass
    {
        public $prop1 = "I'm a class property!";
    
        public function __construct()
        {
            echo 'The class "', __CLASS__, '" was initiated!<br />';
        }
    
        public function __destruct()
        {
            echo 'The class "', __CLASS__, '" was destroyed.<br />';
        }
    
        public function __toString()
        {
            echo "Using the toString method: ";
            return $this->getProperty();
        }
    
        public function setProperty($newval)
        {
            $this->prop1 = $newval;
        }
    
        protected function getProperty()
        {
            return $this->prop1 . "<br />";
        }
    }
    
    class MyOtherClass extends MyClass
    {
        public function __construct()
        {
            parent::__construct();
    		echo "A new constructor in " . __CLASS__ . ".<br />";
        }
    
        public function newMethod()
        {
            echo "From a new method in " . __CLASS__ . ".<br />";
        }
    
        public function callProtected()
        {
            return $this->getProperty();
        }
    }
    
    // Create a new object
    $newobj = new MyOtherClass;
    
    // Call the protected method from within a public method
    echo $newobj->callProtected();
    
    ?>
    

    This generates the desired result:

    The class "MyClass" was initiated!
    A new constructor in MyOtherClass.
    I'm a class property!
    The class "MyClass" was destroyed.
    
    Private Properties and Methods

    A property or method declared private is accessible only from within the class that defines it. This means that even if a new class extends the class that defines a private property, that property or method will not be available at all within the child class.

    To demonstrate this, declare getProperty() as private in MyClass, and attempt to call callProtected() from
    MyOtherClass:

    <?php
    
    class MyClass
    {
        public $prop1 = "I'm a class property!";
    
        public function __construct()
        {
            echo 'The class "', __CLASS__, '" was initiated!<br />';
        }
    
        public function __destruct()
        {
            echo 'The class "', __CLASS__, '" was destroyed.<br />';
        }
    
        public function __toString()
        {
            echo "Using the toString method: ";
            return $this->getProperty();
        }
    
        public function setProperty($newval)
        {
            $this->prop1 = $newval;
        }
    
        private function getProperty()
        {
            return $this->prop1 . "<br />";
        }
    }
    
    class MyOtherClass extends MyClass
    {
        public function __construct()
        {
            parent::__construct();
            echo "A new constructor in " . __CLASS__ . ".<br />";
        }
    
        public function newMethod()
        {
            echo "From a new method in " . __CLASS__ . ".<br />";
        }
    
        public function callProtected()
        {
            return $this->getProperty();
        }
    }
    
    // Create a new object
    $newobj = new MyOtherClass;
    
    // Use a method from the parent class
    echo $newobj->callProtected();
    
    ?>
    

    Reload your browser, and the following error appears:

    The class "MyClass" was initiated!
    A new constructor in MyOtherClass.
    
    Fatal error: Call to private method MyClass::getProperty() from context 'MyOtherClass' in /Applications/XAMPP/xamppfiles/htdocs/testing/test.php on line 49
    
    Static Properties and Methods

    A method or property declared static can be accessed without first instantiating the class; you simply supply the class name, scope resolution operator, and the property or method name.

    “One of the major benefits to using static properties is that they keep their stored values for the duration of the script.”

    To demonstrate this, add a static property called $count and a static method called plusOne() to MyClass. Then set up a do...while loop to output the incremented value of $count as long as the value is less than 10:

    <?php
    
    class MyClass
    {
        public $prop1 = "I'm a class property!";
    
        public static $count = 0;
    
        public function __construct()
        {
            echo 'The class "', __CLASS__, '" was initiated!<br />';
        }
    
        public function __destruct()
        {
            echo 'The class "', __CLASS__, '" was destroyed.<br />';
        }
    
        public function __toString()
        {
            echo "Using the toString method: ";
            return $this->getProperty();
        }
    
        public function setProperty($newval)
        {
            $this->prop1 = $newval;
        }
    
        private function getProperty()
        {
            return $this->prop1 . "<br />";
        }
    
        public static function plusOne()
        {
            return "The count is " . ++self::$count . ".<br />";
        }
    }
    
    class MyOtherClass extends MyClass
    {
        public function __construct()
        {
            parent::__construct();
            echo "A new constructor in " . __CLASS__ . ".<br />";
        }
    
        public function newMethod()
        {
            echo "From a new method in " . __CLASS__ . ".<br />";
        }
    
        public function callProtected()
        {
            return $this->getProperty();
        }
    }
    
    do
    {
        // Call plusOne without instantiating MyClass
        echo MyClass::plusOne();
    } while ( MyClass::$count < 10 );
    
    ?>
    

    Note — When accessing static properties, the dollar sign
    ($) comes after the scope resolution operator.

    When you load this script in your browser, the following is output:

    The count is 1.
    The count is 2.
    The count is 3.
    The count is 4.
    The count is 5.
    The count is 6.
    The count is 7.
    The count is 8.
    The count is 9.
    The count is 10.
    
    Commenting with DocBlocks

    “The DocBlock commenting style is a widely
    accepted method of documenting classes.”

    While not an official part of OOP, the DocBlock commenting style is a widely accepted method of documenting classes. Aside from providing a standard for
    developers to use when writing code, it has also been adopted by many of the most popular software development kits (SDKs), such as Eclipse and NetBeans, and will be used to generate code hints.

    A DocBlock is defined by using a block comment that starts with an additional asterisk:

    /**
     * This is a very basic DocBlock
     */
    

    The real power of DocBlocks comes with the ability to use tags, which start with an at symbol (@) immediately followed by the tag name and the value of the tag. DocBlock tags allow developers to define authors of a file, the license for a class, the property or method information, and other useful information.

    The most common tags used follow:

    • @author: The author of the current element (which might be a class, file, method, or any bit of code) are listed using this tag. Multiple author tags can be used in the same DocBlock if more than one author is credited. The format for the author name is John Doe <john.doe@email.com>.
    • @copyright: This signifies the copyright year and name of the copyright holder for the current element. The format is 2010 Copyright Holder.
    • @license: This links to the license for the current element. The format for the license information is
      http://www.example.com/path/to/license.txt License Name.
    • @var: This holds the type and description of a variable or class property. The format is type element description.
    • @param: This tag shows the type and description of a function or method parameter. The format is type $element_name element description.
    • @return: The type and description of the return value of a function or method are provided in this tag. The format is type return element description.

    A sample class commented with DocBlocks might look like this:

    <?php
    
    /**
     * A simple class
     *
     * This is the long description for this class,
     * which can span as many lines as needed. It is
     * not required, whereas the short description is
     * necessary.
     *
     * It can also span multiple paragraphs if the
     * description merits that much verbiage.
     *
     * @author Jason Lengstorf <jason.lengstorf@ennuidesign.com>
     * @copyright 2010 Ennui Design
     * @license [www.php.net] PHP License 3.01
     */
    class SimpleClass
    {
        /**
         * A public variable
         *
         * @var string stores data for the class
         */
        public $foo;
    
        /**
         * Sets $foo to a new value upon class instantiation
         *
         * @param string $val a value required for the class
         * @return void
         */
        public function __construct($val)
        {
            $this->foo = $val;
        }
    
        /**
         * Multiplies two integers
         *
         * Accepts a pair of integers and returns the
         * product of the two.
         *
         * @param int $bat a number to be multiplied
         * @param int $baz a number to be multiplied
         * @return int the product of the two parameters
         */
        public function bar($bat, $baz)
        {
            return $bat * $baz;
        }
    }
    
    ?>
    

    Once you scan the preceding class, the benefits of DocBlock are apparent: everything is clearly defined so that the next developer can pick up the code and never have to wonder what a snippet of code does or what it should contain.

    Comparing Object-Oriented and Procedural Code

    There’s not really a right and wrong way to write code. That being said, this section outlines a strong argument for adopting an object-oriented approach in software development, especially in large applications.

    Reason 1: Ease of Implementation

    “While it may be daunting at first, OOP actually provides an easier approach to dealing with data.”

    While it may be daunting at first, OOP actually provides an easier approach to dealing with data. Because an object can store data internally, variables don’t need to be passed from function to function to work properly.

    Also, because multiple instances of the same class can exist simultaneously, dealing with large data sets is infinitely easier. For instance, imagine you have two people’s information being processed in a file. They need names, occupations, and ages.

    The Procedural Approach

    Here’s the procedural approach to our example:

    <?php
    
    function changeJob($person, $newjob)
    {
        $person['job'] = $newjob; // Change the person's job
        return $person;
    }
    
    function happyBirthday($person)
    {
        ++$person['age']; // Add 1 to the person's age
        return $person;
    }
    
    $person1 = array(
        'name' => 'Tom',
        'job' => 'Button-Pusher',
        'age' => 34
    );
    
    $person2 = array(
        'name' => 'John',
        'job' => 'Lever-Puller',
        'age' => 41
    );
    
    // Output the starting values for the people
    echo "<pre>Person 1: ", print_r($person1, TRUE), "</pre>";
    echo "<pre>Person 2: ", print_r($person2, TRUE), "</pre>";
    
    // Tom got a promotion and had a birthday
    $person1 = changeJob($person1, 'Box-Mover');
    $person1 = happyBirthday($person1);
    
    // John just had a birthday
    $person2 = happyBirthday($person2);
    
    // Output the new values for the people
    echo "<pre>Person 1: ", print_r($person1, TRUE), "</pre>";
    echo "<pre>Person 2: ", print_r($person2, TRUE), "</pre>";
    
    ?>
    

    When executed, the code outputs the following:

    Person 1: Array
    (
        [name] => Tom
        [job] => Button-Pusher
        [age] => 34
    )
    Person 2: Array
    (
        [name] => John
        [job] => Lever-Puller
        [age] => 41
    )
    Person 1: Array
    (
        [name] => Tom
        [job] => Box-Mover
        [age] => 35
    )
    Person 2: Array
    (
        [name] => John
        [job] => Lever-Puller
        [age] => 42
    )
    

    While this code isn’t necessarily bad, there’s a lot to keep in mind while coding. The array of the affected person’s attributes must be passed and returned from each function call, which leaves margin for error.

    To clean up this example, it would be desirable to leave as few things up to the developer as possible. Only absolutely essential information for the current operation should need to be passed to the functions.

    This is where OOP steps in and helps you clean things up.

    The OOP Approach

    Here’s the OOP approach to our example:

    <?php
    
    class Person
    {
        private $_name;
        private $_job;
        private $_age;
    
        public function __construct($name, $job, $age)
        {
            $this->_name = $name;
            $this->_job = $job;
            $this->_age = $age;
        }
    
        public function changeJob($newjob)
        {
            $this->_job = $newjob;
        }
    
        public function happyBirthday()
        {
            ++$this->_age;
        }
    }
    
    // Create two new people
    $person1 = new Person("Tom", "Button-Pusher", 34);
    $person2 = new Person("John", "Lever Puller", 41);
    
    // Output their starting point
    echo "<pre>Person 1: ", print_r($person1, TRUE), "</pre>";
    echo "<pre>Person 2: ", print_r($person2, TRUE), "</pre>";
    
    // Give Tom a promotion and a birthday
    $person1->changeJob("Box-Mover");
    $person1->happyBirthday();
    
    // John just gets a year older
    $person2->happyBirthday();
    
    // Output the ending values
    echo "<pre>Person 1: ", print_r($person1, TRUE), "</pre>";
    echo "<pre>Person 2: ", print_r($person2, TRUE), "</pre>";
    
    ?>
    

    This outputs the following in the browser:

    Person 1: Person Object
    (
        [_name:private] => Tom
        [_job:private] => Button-Pusher
        [_age:private] => 34
    )
    
    Person 2: Person Object
    (
        [_name:private] => John
        [_job:private] => Lever Puller
        [_age:private] => 41
    )
    
    Person 1: Person Object
    (
        [_name:private] => Tom
        [_job:private] => Box-Mover
        [_age:private] => 35
    )
    
    Person 2: Person Object
    (
        [_name:private] => John
        [_job:private] => Lever Puller
        [_age:private] => 42
    )
    

    There’s a little bit more setup involved to make the approach object oriented, but after the class is defined, creating and modifying people is a breeze; a person’s information does not need to be passed or returned from methods, and only absolutely essential information is passed to each method.

    “OOP will significantly reduce your workload if implemented properly.”

    On the small scale, this difference may not seem like much, but as your applications grow in size, OOP will significantly reduce your workload if implemented properly.

    Tip — Not everything needs to be object oriented. A quick function that handles something small in one place inside the application does not necessarily need to be wrapped in a class. Use your best judgment when deciding between object-oriented and procedural approaches.

    Reason 2: Better Organization

    Another benefit of OOP is how well it lends itself to being easily packaged and cataloged. Each class can generally be kept in its own separate file, and if a uniform naming convention is used, accessing the classes is extremely simple.

    Assume you’ve got an application with 150 classes that are called dynamically through a controller file at the root of your application filesystem. All 150 classes follow the naming convention class.classname.inc.php and reside in the inc folder of your application.

    The controller can implement PHP’s __autoload() function to dynamically pull in only the classes it needs as they are called, rather than including all 150 in the controller file just in case or coming up with some clever way of including the files in your own code:

    <?php
        function __autoload($class_name)
        {
            include_once 'inc/class.' . $class_name . '.inc.php';
        }
    ?>
    

    Having each class in a separate file also makes code more portable and easier to reuse in new applications without a bunch of copying and pasting.

    Reason 3: Easier Maintenance

    Due to the more compact nature of OOP when done correctly, changes in the code are usually much easier to spot and make than in a long spaghetti code procedural implementation.

    If a particular array of information gains a new attribute, a procedural piece of software may require (in a worst-case scenario) that the new attribute be added to each function that uses the array.

    An OOP application could potentially be updated as easily adding the new property and then adding the methods that deal with said property.

    A lot of the benefits covered in this section are the product of OOP in combination with DRY programming practices. It is definitely possible to create easy-to-maintain procedural code that doesn’t cause nightmares, and it is equally possible to create awful object-oriented code. [Pro PHP and jQuery] will attempt to demonstrate a combination of good coding habits in conjunction with OOP to generate clean code that’s easy to read and maintain.

    Summary

    At this point, you should feel comfortable with the object-oriented programming style. Learning OOP is a great way to take your programming to that next level. When implemented properly, OOP will help you produce easy-to-read, easy-to-maintain, portable code that will save you (and the developers who work with you) hours of extra work. Are you stuck on something that wasn’t covered in this article? Are you already using OOP and have some tips for beginners? Share them in the comments!

    Author’s Note — This tutorial was an excerpt from Pro PHP and jQuery (Apress, 2010).


  • Permalink for 'Say Hello to Webkit Filters'

    Say Hello to Webkit Filters

    Posted: December 22nd, 2011, 1:41pm MST by Jeffrey Way

    Earlier this month, a new specification, Filter Effects 1.0, was released. It presents some exciting new Photoshop-like effects that we can use in the browser. Even better, Webkit has already landed support (in the nightlies)!

    According to the Spec…

    “A filter effect is a graphical operation that is applied to an element as it is drawn into the document. It is an image-based effect, in that it takes zero or more images as input, a number of parameters specific to the effect, and then produces an image as output.”

    Now, at least at this point, I wouldn’t presume to be able to show you everything that’s possible with these new filters. I’m still learning them myself! That said, I’ll show you a handful of the new filters, how we can use them in our projects, and then, hopefully, we can all brainstorm and learn from each other within the comments. Let’s get started.

    Filters are typically associated with images (though they can also be applied to video). As such, for the handful of demos below, we’ll be using the Nettuts+ logo as input.

     Nettuts+ Logo
    
    Nettuts+ Logo

    Remember: these effects aren’t yet available in the public releases of Webkit browsers. For now, download Canary when testing these demos.

    hue-rotate

    Ever played around with the Hue/Saturation panel in Photoshop? Well now you can play around with it in the browser.

    img {
       -webkit-filter: hue-rotate(50deg);
    }
    

    If specifying this value in degrees seems confusing, just imagine a color wheel. The number of degrees you specify determines where that wheel stops. This means, that 0deg won’t do a thing, while 50deg will turn the dial, accordingly.

    In this case, the Nettuts+ logo will take on a blu-ish hue.


    View Demo

    Or, let’s say that you want your image to continuously change colors. Likely, in a real-world project, the color transitions will be far more subtle, but for this demo, we’ll be a bit obnoxious.

    img {
       -webkit-animation: adjustHue 1s alternate infinite;
    }
    
    @-webkit-keyframes adjustHue {
       0% { -webkit-filter: hue-rotate(30deg); }
       50% { -webkit-filter: hue-rotate(60deg); }
       100% { -webkit-filter: hue-rotate(90deg); }
    }
    

    Simple enough. View Demo

    grayscale

    We’ve used a variety of hacks in the past to transition an image from black and white to color in the browser. One technique calls for two images stacked on top of one another. Another option is to use canvas. Or… we can use the grayscale filter.

    img {
       -webkit-filter: grayscale(100%);
    }
    

    When applying a percentage to the grayscale function, just think to yourself, “On a scale of 0 to 100%, how gray do I want this image to be?


    View Demo

    When used in tandem with CSS3 transitions, we can apply a nice and clean hover effect.

    img {
      -webkit-transition: -webkit-filter 1s;
    }
    img:hover {
        -webkit-filter: grayscale(100%);
    }
    

    In the future, you’ll want to provide prefixes for the other browsers, however, it’s not necessary at this point. No need in applying Mozilla transitions to accomodate for a filter that’s only implemented in Webkit (so far).

    View Demo

    sepia

    Enjoy the sepia-flavored Instagram effect? Let’s see what Nettuts+ looked like in the old west.

    img {
          -webkit-filter: sepia(100%);
    }
    

    View Demo

    Typically, though, this effect is applied to photos. Let’s see how the greatest artist who ever lived looks in sepia.


    View Demo

    Excellent.

    blur

    By passing a radius, we can blur an image in the browser with ease.

    img {
          -webkit-filter: blur(2px);
    }
    

    View Demo

    Or by upping the blur radius to 50px.


    View Demo brightness

    We use the brightness filter to specify…wait for it…how bright the input image should appear.

    img {
          -webkit-filter: brightness(15%);
    }
    

    View Demo

    Think of 100% as home base. brightness(100%) keeps the image unchanged. As we reduce this percentage, however, the image will continue to darken.

    Don’t forget: you can combine all of these filters.

    img {
          -webkit-filter: brightness(60%) sepia(100%);
    }
    

    View Demo contrast

    We can now adjust the contrast of an image quite easily.

    img {
          -webkit-filter: contrast(200%);
    }
    

    View Demo

    Once again, think of 100% as resting position. We can then reduce or increase this value to adjust the contrast of the image. According to the spec, applying a value of 0% should make the image 100% black, similar to what you might expect from -webkit-filter: brightness(0%);. However, I’m seeing more of a dark gray.

    img {
          -webkit-filter: contrast(0%);
    }
    

    View Demo

    Now if we up the percentage considerably, to 2000%:

    img {
          -webkit-filter: contrast(2000%);
    }
    

    View Demo

    Just for fun, let’s create a throbbing Matrix version of the Nettuts+ logo. We’ll combine CSS3 animations and filters.

    img {
        -webkit-animation: bluePill 1s alternate infinite;
    }
    
    @-webkit-keyframes bluePill {
       0% { -webkit-filter: contrast(2000%); }
       100% { -webkit-filter: contrast(100%); }
    }
    

    View Demo

    invert

    Mac users: press Control + Option + Command + 8. Notice how it inverts your screen (of course you noticed). I use this trick late at night when I’m reading on the computer, and my eyes are sore.

    By applying a percentage of 100 to the new invert filter, we can achieve the exact same effect.

    img {
          -webkit-filter: invert(100%);
    }
    

    View Demo

    Note that 0% will leave the image unchanged.

    Now, you could technically apply this to, say, the body of your website, and it would work. However, you’ll notice considerable slow down, and lose the ability to scroll the page. AKA – Don’t do it, except for fun.

    saturate

    In addition to setting grayscale(100%), we could also achieve a similar effect by desaturating the image entirely.

    In this case, 100% is the unchanged state, at which point you can either decrease or increase this value. As such, reducing this value to 0% should remove all color from the image.

    img {
          -webkit-filter: saturate(0%);
    }
    

    View Demo

    Or, by upping the value to 700%:


    View Demo That’s All For Now

    Stay tuned to this article over the course of the next week. As these techniques are still super new, we all need time to figure out how to use them. I’ll update this article as I learn more!


  • Permalink for 'From Idea to Market: How We Built Gradient'

    From Idea to Market: How We Built Gradient

    Posted: December 21st, 2011, 3:10pm MST by Nicola Armellini

    Retracing the steps you’ve taken is a helpful way to understand how well you’ve executed your vision – whatever that might be. What could you have done better? What should have been avoided? Today, I’ll share what we’ve learned (and are still learning) while crafting Gradient. It’s an experience that has changed everything for us.

    First Sketch

    Building a product, be it a native app, web app, or service, is always a challenging task. However, once we convinced ourselves to follow a few pieces of advice, we managed to ship something we believed in. And this is what I’d like to talk about.

    It All Starts with a Simple Idea

    For as long as I can remember, I’ve always felt that great products needed unreachably smart ideas to be built. I was exceptionally pleased to find that this is not necessarily true.

    More often than not, if you find a simple way to solve a problem that you personally have, you’re probably going to make other people’s life easier as well.

    Turning that solution into something you end up selling or giving away for free (that really depends on your vision, which I’ll talk about later) is the most logical following step.

    In our specific case, we were building our own website, which is rich with linear gradients, and I found myself complaining loudly about the tedious process of writing lines and lines of CSS code – all for the purpose of making every browser agree on the fact that you’re actually writing something they can understand.

    “What if”, I asked Yari (@yariok, the developer), “we had a native app that took care of it?”

    Your Vision Will Lead the Way

    Once you have your idea, however simple it might be, you get to decide what goals you’re setting for yourself (or your team).

    • Do you want to make money with your application or service?
    • Do you want to be glorified for your incredible prowess in development or design, while not making a single buck in the process – with the side-effect of becoming a respected authority?
    • Do you simply just want to have fun?
    • Do you desire a one-time release with no further hassle? Or, would you prefer to follow an iterative process

    Every choice will be influenced by what you want your path to be.

    The investments differ dramatically. Maybe you dream of turning this project into the only revenue source you have and finally get rid of client or office work. Whichever the case might be, stick to that. Every choice will be influenced by what you want your path to be and you will have a much easier time when facing a fork if your vision is strong since the beginning.

    Our Choice

    Here’s more or less what we decided for Gradient:

    • Paid App: So that we can cover our investment at least in part.
    • Iterative Development: This will allow us to add features gradually and grant exposure for a longer time-span.
    • 100% Custom UI: My fault!
    • Exposure: We want to be recognized as competent in what we do (glory!)

    As with anything, there were also a few bonus goals. It would be nice if people I learned CSS from used my app. Also, what if this app created new possibilities with people around the world?

    Once all this was set, we did everything we could to make the app a reality.

    Have a Plan Before Writing a Single Line of Code

    It’s quite simple, actually. If you have a good plan laid out, you can have a measure of how much work is going to be required to develop your project. This means that you can start marking dates on your calendar. This also means that you can begin creating expectations for those dates. Ultimately, this helps if you plan to create some hype among users and the media.

    These trivial tasks will undoubtedly turn into huge time sinks.

    Many times, especially if you’re not used to promoting or communicating your work, when laying down the plan, you will forget about some apparently trivial aspects. Of course, you’re focused on getting your “creature” just perfect for the launch or beta, and you think the rest will be taken care of in no more than a couple of hours. These trivial tasks will undoubtedly turn into huge time sinks.

    For instance, you’re not used to marketing lingo… or you haven’t thought of everything that might happen when your product finally reaches your potential first users…or you forgot about a banner…or the mail you will be sending to your beta testers. Countless little things like this will add up quickly!

    A Note on Focus

    Often, when you’re excited about what you’re creating, new ideas, beta tester suggestions, and nice-to-have features will come to you during your sleep.

    These ideas have the potential to deter you from your planned path.

    It happens all the time – and certainly did to us. Take time to consider thoroughly if these new ideas are truly worth the diversion. In most cases, stick to the plan.

    Prototype Like There’s no Tomorrow

    There’s nothing quite as valuable as building something usable quickly. Weaknesses in the UX design of your product are so much easier to spot when you’re actually using what you’ve built. There’s not much theory here, really. I think this is the most straightforward step.

    A couple of hours after my initial complaint, we had the first rough incarnation of the app. It had HEX input and the output was messy code, but the idea was definitely in front of us.

    First Incarnation

    We added from there, building what we decided was the very basic array of features our first version needed to have, and then refining the usage patterns in order to streamline the user experience as much as we possibly could. We wanted it to be the fastest solution for that problem. We were and are aware of free and well established competition and our focus went on refining those features our competition couldn’t have.

    Don’t Be Afraid of Talking to Strangers

    In fact, they’re your best friends. There’s no room for introversion, if you plan on creating your own application or service. You absolutely must get in touch with other people, such as opinion leaders and those who you admire (or even intimidated by). But beyond these folks, also connect with lots of geeks like you! You definitely want people to talk about your project and the only way to let them know is to speak to them directly.

    Once you do so, expect one of the following reactions:

    • questions / problems / complaints
    • ideas / suggestions
    • thumbs-up / hi-fivers / hugs
    • nothing at all (frustrating, but common with some “celebrities”)

    Seek publicly available email addresses, reach out on Twitter, use every instrument you think might be relevant to your target audience (Dribbble, Facebook, you name it), listen to what the others are saying, and engage people in relevant conversations. It’s time consuming but it will make a huge difference.

    If executed correct, the pieces quickly fall into place.

    For us, this engagement pattern led us from less than 300 followers on Twitter at the beginning of September, when we began our closed beta, to 1000 and counting on launch day in November and a growth in actual amplification that went from no more than 5 retweets on the first beta announcement, to more than 70 retweets and many other support messages from the entire community in November – including many of our heroes. Visits to the website and registration increased exponentially.

    Additionally, this led to new interesting business opportunities, connections we could only dream of just a couple of months ago, a lot more visibility and also some new good friends. If executed correct, the pieces quickly fall into place.

    There’s a Price

    It’s tricky, though – especially for people like us who prefer creating things over pricing them. Again, your vision will help you with this, providing you with at least a range of options.

    Studying your market of choice, especially in contexts like the App Store, where the data is mostly kept secret, is difficult and takes time, but, again, rational thought comes in handy. Here are the questions we answered when coming to our decision:

    • What’s the price of similar products? (on the App Store in this case)
    • Do we want it to be an impulse or a well-pondered purchase?
    • Based on the development effort, how much money do we expect to make? Can we estimate how many units we could sell?
    • How much would we be willing to pay for it?
    • What benefit will people have from our app? Is it countable? In this specific case, how much would they be willing to pay for the relevant amount of time saved?

    As a reasonable indicator of how things are going, we’re right now evaluating user feedback. Unless what you build is free, there will always be someone screaming at you because your product costs money. However, if some of these buyers reply to you, explaining why the price is reasonable in their eyes, you’ve likely hit a sweet spot. (And you have awesome users.)

    Hit the Shelves or the Screens

    Building your own product is both a challenge and the most rewarding adventure in our industry.

    It’s a wonderful experience; building your own product is both a challenge and the most rewarding adventure in our industry. Ironically, the things you learn in the process serve to be the best prize at the end of your path. The connections you build along the way are extremely valuable. You gain respect, because you demonstrate you’re able to ship. You transition from an idea, to execution.

    Once your product reaches the public, a new journey begins, and many new interaction possibilities open up. Still, though, the same rules that you’ve followed still apply. Don’t stray from the path.

    We’re sticking to our plan. So far, things are going exactly according to plan!


  • Permalink for 'Create a Scalable Widget Using YUI3: Part 2'

    Create a Scalable Widget Using YUI3: Part 2

    Posted: December 20th, 2011, 9:17pm MST by Dan Wellman

    In part one of this series, we reviewed some of the necessary constructs to use when creating a widget with YUI3. We looked at the static properties we needed to set, the class constructor and namespacing, and briefly looked at the extend() method.

    In this part of the tutorial, we’ll review the prototype methods we can override or create in order to make our widget function.

    Before we begin, let’s just remind ourselves of the method now, as this method houses all the code below:

    TweetSearch = Y.extend(TweetSearch, Y.Widget, {
    
    });

    The third argument is what we are interested in, in this part of the tutorial. All of the functionality we add that is specific to our widget will be within functions that are added as values to different properties of the object passed to the extend() method. Some of these methods are added automatically for us –we just need to override them with custom functionality. We’ll look at these methods first.

    Lifecycle Methods

    Several methods executed at different points in the widget instances life cycle. The first of these is an initializer method (remember to add this code within the extend() method shown above):

    initializer: function () {
        this._retrieveTweets();
    },

    The underscore convention to indicate the method should be treated as private, and not called directly by any implementing developer.

    The initializer method is provided to allow us to do any tasks that are required as soon as the widget is initialized. Within any prototype methods we attach to our widget, whether inherited or created ourselves, the value of this is set to the widget instance.

    All our widget needs to do at this point is retrieve the search results from Twitter. We package this up as a separate function (which we’ll look at in more detail a little later), instead of just retrieving the results directly within initializer so that we can reuse the functionality and retrieve search results any time we wish. The _retrieveTweets() method uses the underscore convention to indicate the method should be treated as private, and not called directly by any implementing developer. It can be called directly of course, but may result in weirdness.

    The next life-cycle method inherited from Widget is renderUI(), which we can use to perform any necessary setup, the creation and insertion of new elements, etc, our widget requires. Add this code directly after that shown above:

    renderUI: function () {
        var contentBox = this.get("contentBox"),
            strings = this.get("strings"),
            viewer = Node.create(Y.substitute(TweetSearch.VIEWER_TEMPLATE, { viewerclass: TweetSearch.VIEWER_CLASS })),
            loadingNode = Node.create(Y.substitute(TweetSearch.LOADER_TEMPLATE, { loaderclass: TweetSearch.LOADER_CLASS }));
    
        if (this.get("showTitle")) {
            this._createTitle();
        }
        this._loadingNode = contentBox.appendChild(loadingNode);
        this._viewerNode = contentBox.appendChild(viewer);
    
        if (this.get("showUI")) {
            this._createSearchUI();
        }
    
        contentBox.addClass("yui3-widget-content");
    },

    When a widget is initialised, YUI will automatically create a wrapper element for the element that was passed to the constructor.

    Within the renderUI() method, we first store a reference to the contentBox attribute of the widget. The contentBox represents the inner container of the widget and is one of the attributes automatically inherited from Widget, like the srcNode attribute that we saw briefly in part 1. When a widget is initialised, YUI will automatically create a wrapper element for the element that was passed to the constructor, with the inner element becoming the contentBox. The wrapper is known as the bounding box (available as the boundingBox attribute).

    We also get a reference to the strings attribute that contains the localizable strings used by elements created by the widget. We then create two new elements; the viewer which will be used to contain the list of tweets returned by Twitter’s search API, and a loading element that will be displayed while the request is in progress.

    We use the create() method of the YUI Node module to create our new elements. This element can accept the string representation of an element, which it will then create. Instead of passing it a string directly however, we use YUI’s substitute() method to replace the tokenised templates that we created in part one of this tutorial.

    The substitute() method takes two arguments;

    • the first is the string to perform substitution on.
    • the second is an object whose keys map directly to the tokens within the string.

    The values of each property are swapped into the string, so for example, our viewer template will be stored like this:

    "<div class={viewerclass}></div>"

    The object passed as the second argument to the substitute() method used to create the viewer node contains a key called viewerclass, so the value of this key will be swapped with the matching token in the source string. In this case, we use the stored class name as the substitution, so the viewer will be given the class name yui3-tweetsearch-viewer (the class names were all created and stored on our widget instance in part one).

    We then check whether the showTitle attribute of our widget is set to true, which it is by default, but may be disabled by the implementing developer. If the attribute is set to true we call the custom (i.e. not inherited) _createTitle() method. The reason we package this up as a separate unit of code, instead of just creating the widget is because the showTitle attribute may be set at any time by someone implementing our widget, so it can’t just reside within a life-cycle method. We will look at our custom methods in detail after looking at the inherited life-cycle methods.

    After we do or do not (depending on configuration) create the title node, we then insert the new elements into the DOM by adding them as child nodes of the contentBox. Note that we also store the new elements on the widget instance so that we can easily refer to them later on.

    We then check whether the showUI attribute is enabled (again, it is by default, but it could be changed in the configuration), and if so call the _createSearchUI() method. This is a separate method for the same reason as last time – so that it can be reused throughout the widget instance’s life.

    Finally, we add the class name yui3-widget-content to the contentBox. This isn’t strictly necessary, as the implementing developer may not be using any of the YUI’s style sheets (base, fonts, reset, etc), but as the class name isn’t added for us automatically, we should include in case the developer does wish to pick up some of the styling provided by the library.

    The final life-cycle method we are going to use is bindUI(), which allows us to hook up any handlers that should be called when an attribute changes value, or an event occurs. Add the following code directly after the renderUI() method:

    bindUI: function () {
        if (this.get("showUI")) {
    
            Y.on("click", Y.bind(this._setTerm, this), this._buttonNode);
            this.after("termChange", this._afterTermChange);
        }
    
        this.after("showTitleChange", this._afterShowTitleChange);
        this.after("showUIChange", this._afterShowUIChange);
        this.after("tweetsChange", this._afterTweetsChange);
    },

    The first thing we do is check whether the showUI attribute is enabled; if it has been disabled we don’t need to worry about adding event handlers for it. If it is enabled, we use YUI’s on() method to add a click-handler bound to the custom _setTerm() method. We ensure the widget instance remains bound to the this keyword within the event handler by passing this (which at this point refers to the widget instance) as the second argument to the bind() method.

    We also use the after() method that is automatically attached to our widget instance by the library to add a listener that reacts to the term attribute changing. A listener can be bound to any of our custom attributes by simply suffixing After to any attribute name. The term attribute will only change if the search UI is enabled. We then add listeners for each of the other attributes we need to monitor; showTitle, showUI and tweets, hooking these up with the relevant handlers.

    Note: There is another life cycle method provided by the Widget class, but in this particular example we don’t need to make use of it. This method is the destructor, which will be called just before the widget is destroyed. It is used to tidy up after the widget, but only needs to be used if elements are added to the DOM outside of the boundingBox (the outer wrapper) of the widget.

    Automated Prototype Methods

    Remember the validator we specified as part of the ATTRS object in the first part of this tutorial? The method that we set as the value of this property will be called automatically whenever an attempt is made to update the attribute. Let’s take a look at it now; add the following code directly after bindUI():

    _validateTerm: function (val) {
        return val !== this.get("term");
    },

    The method must return true or false and automatically receives the new value (that is, the value that may become the new value if it passes validation) as the first argument; if true is returned, the attribute is updated with the new value, if false is returned the attribute is not updated.

    The logic we supply is pretty simple in this example – we simply check that the new value is not the same as the old value. There’s no point after all in making another AJAX call only to receive exactly the same set of results.

    Non-Inherited Prototype Methods

    Next we can start adding our custom methods that will add more functionality to our widget. The first function we referenced within the initializer method was _retrieveTweets(), so we’ll look at that first:

    _retrieveTweets: function () {
        var that = this,
            url = [this.get("baseURL"), "&q=", encodeURI(this.get("term")), "&rpp=", this.get("numberOfTweets")].join(""),
            handler = function (data) {
            that.set("tweets", data);
        },
        request = new Y.JSONPRequest(url, handler);
    
        request.send();
    },

    We first set a few variables; the this keyword will no longer point to our widget instance inside the success callback that we’ll specify when we make the request to Twitter, so we store a reference to this in a variable called that, as convention dictates.

    We also create the request URL; we retrieve the baseURL, the term and the numberOfTweets attributes, storing each as an item in an array and then using JavaScript’s join() function to concatenate them all into a string. Using an array and the join() method is way faster than concatenating strings with the + operator.

    Next we define our success callback; all this simple function needs to do is set the widget’s tweets attribute to the response received from the request. The response will be automatically passed to the callback function.

    The last variable we define is for the request itself, which is initialised using YUI’s JSONPRequest() method. This method accepts two arguments; the first is the URL to make the request to and the second is the callback function to invoke on success. Finally, to initiate the request we simply call the send() method.

    Our next custom method is _createTitle(), which we call from the renderUI() method:

    _createTitle: function () {
        var strings = this.get("strings"),
            titleNode = Node.create(Y.substitute(TweetSearch.TITLE_TEMPLATE, {
    	        titleclass: TweetSearch.TITLE_CLASS,
                title: strings.title,
                subtitle: strings.subTitle,
                term: this.get("term")
            }));
    
        this._titleNode = this.get("contentBox").prepend(titleNode);
    },

    We also store a reference to the strings attribute for use within the function. A title is created using the same principles as before, although this time we have a few more tokens to replace in our substitute() method. This method is only called if the showTitle attribute is set to true. Note that the get() method is chainable, so we can call the prepend() method to insert the title directly after it.

    The code here is very similar to what has been used before, as is the case for our next method, _createSearchUI():

    _createSearchUI: function () {
    
            var contentBox = this.get("contentBox"),
                strings = this.get("strings"),
                ui = Node.create(Y.substitute(TweetSearch.UI_TEMPLATE, { uiclass: TweetSearch.UI_CLASS })),
                label = Node.create(Y.substitute(TweetSearch.LABEL_TEMPLATE, { labelclass: TweetSearch.LABEL_CLASS, labeltext: strings.label })),
                input = Node.create(Y.substitute(TweetSearch.INPUT_TEMPLATE, { inputclass: TweetSearch.INPUT_CLASS })),
                button = Node.create(Y.substitute(TweetSearch.BUTTON_TEMPLATE, { buttonclass: TweetSearch.BUTTON_CLASS, buttontext: strings.button }));
    
            this._uiNode = ui;
    
            this._labelNode = this._uiNode.appendChild(label);
            this._inputNode = this._uiNode.appendChild(input);
            this._buttonNode = this._uiNode.appendChild(button);
    
            this._uiNode.appendTo(contentBox);
        },

    Again, very similar to what we have seen before. Remember, the only reason this is in a separate function is so that the UI can be switched on or off at any point during the widget’s life-cycle. This method is only called if the showUI attribute is set to true.

    Next up is the _setTerm() method, which is called by the event listener attached to the _buttonNode when the button is clicked:

    _setTerm: function () {
            this.set("term", this._inputNode.get("value"));
        },

    In this simple method, we just try to set the term attribute to the string entered into the <input>. In trying to set the attribute, our validator will be called and will only update the attribute if the value is different to the attribute’s current value.

    The last of our custom methods is another simple method used to update the subtitle in the header of the widget to the new search term; add the following code:

    _uiSetTitle: function (val) {
            this._titleNode.one("h2 span").setContent(val);
            },

    This method will receive the new value as an argument (we’ll call this method manually from an attribute change-handling method that we’ll look at in the next part of this series). We call YUI’s one() method on our title node to select the <span> within the subtitle, and then use the setContent() method to update its inner-text.

    Summary

    In this part of the tutorial, we first looked at the life-cycle methods that we get as a result of extending the Widget superclass. These methods are called automatically for us by the library at different points in the widget’s life-cycle.

    Although the methods that we’ve added all look similar in structure, there are distinctions between the two; for example, the life-cycle methods receive more ‘protection’ than those methods we add ourselves, hence why these methods are not prefixed with an underscore. These methods, unlike our custom ones, can’t be called directly by the implementing developer.

    We also took a look at a validator method; these methods will also be called by the library automatically when appropriate which makes them incredibly useful for ensuring data is in a particular format, or meets a particular requirement before an attribute is updated.

    Lastly, we looked at the custom prototype methods that we need in order to make our widget function. We saw that we can easily use the built-in get() and set() methods to get and set attributes, and that within each method the this keyword Is helpfully set to our widget’s instance, so that we can easily obtain and manipulate different aspects of the widget.

    In the next part of this tutorial, we’ll look at the attribute change-handling methods that need to be added in order to make our widget respond to user interaction or changes in the page’s state. We can also look at the CSS we need to provide for our widget, and how the widget is initialized and used.

    If you have any questions, please let me know in the comments section below. Thank you so much for reading!


  • Permalink for 'The Official 2011 Nettuts+ Holiday Gift Guide'

    The Official 2011 Nettuts+ Holiday Gift Guide

    Posted: December 19th, 2011, 2:00pm MST by Siddharth

    I needn’t remind you that Christmas is almost upon us. If you still haven’t bought gifts for your loved ones, this is the perfect time to start panicking. If your loved one is a developer though, we have an easy way out for you: pick a few from the list below and you’ll be off the hook!

    In this mini gift guide, we’ll take a look at what we, as developers, want our stockings to be filled with. Hopefully, Santa hasn’t figured out that we’ve been feigning innocence all year!

    Subscriptions and Software

    Subscriptions are the gifts that keep on giving. Depending on whether you want to gift something for work or pleasure, you’ll find something here.

    Nettuts+ Holiday 2011 Gift Guide Netflix

    Let’s face it — we’re busy people and can’t always catch a show at the right time. Heck, we’re the ones missing dinners with our special ones, right? And DVRing things can get pretty messy pretty quickly. This is where Netflix comes in. Unlimited movies and TV episodes over the internet? Yes please. Gift this to the geek in your life and watch him light up.

    Get it here

    Nettuts+ Holiday 2011 Gift Guide Linode / Other VPS

    Show your cutting edge web developer a shared hosting plan and he’d balk. Get them a yearly subscription to a virtual private server and watch as he formulates all the sheer uses he’d eke out of it. While there are plenty of options out there, I’ve personally used Linode for a few years now and gets my recommendation.

    Get it here

    Nettuts+ Holiday 2011 Gift Guide Heroku / Platform as a Service

    Or you could be a bit more forward and present them with a subscription to a PaaS [platform as a service]. Unlike a VPS, most of the sys-admin grunt work is taken care for you, including load management, letting you focus on just the code. Again, there are lots of options here but Heroku gets my vote for being so darn good.

    Get it here

    Nettuts+ Holiday 2011 Gift Guide Litmus / Browser Testing

    Browser compatibility testing still remains a scourge on the workflow of a modern developer but it really doesn’t need to be. Get them, or yourself, a subscription to the Litmus service and forget about having gazillion browser windows and versions open to test things out.

    Get it here

    Nettuts+ Holiday 2011 Gift Guide Magazine

    People have been harking on about the death of the print medium for years now but they’ve still been chugging on. I don’t have a specific recommendation since these tend to be intensely personal so take your pick. As opposed to gaming and tech magazines, I think people like me would appreciate something related to business, travel, lifestyle, or let’s go crazy for a second here, fashion.

    Nettuts+ Holiday 2011 Gift Guide Evernote

    Evernote is awesome. There, I said it. It basically focuses on getting all your mental threads together and then syncs it all across any of your devices. If it sounds simple and you let yourself believe that, smack yourselves on the head — it’s much more complicated than that.

    Evernote goes above and beyond the call and provides a ton of nifty features including extracting data from images. While the free version is more than serviceable, the premium version ships with just a few more enticing features.

    Get it here

    Nettuts+ Holiday 2011 Gift Guide Tuts+ Premium

    Not to toot our own horn but our Tuts+ premium program offers one of the best ways to learn new technologies and skill sets or hone existing ones. In addition to a massive 700+ exclusive tutorial roster, you also get access to nearly 30 top selling ebooks. At $180 for an entire year of learning, you can’t do better than this!

    Get it here

    Nettuts+ Holiday 2011 Gift Guide Sublime Text

    And finally, don’t forget a good text editor or an IDE. They are the heart and soul of a developer’s workflow and an informed gift here will definitely elevate you in a developer’s eyes.

    A lot of people will go with the Coda/Textmate hoopla but, for a change, try SublimeText. It’s cross platform, feature laden, stable and cheap for a software of such stature.

    Get it here

    Gadgets

    The Venn diagram of web developers and tech enthusiasts is primarily largely intersecting. Be it the new all mighty smartphone or an innocuous desk toy, gadgets make for excellent gifts.

    Nettuts+ Holiday 2011 Gift Guide Tablets

    Tablets have been the all the rage recently and I can certainly see why: they make for excellent consumption devices. Checking your all important work email or catching up on your silly kitten videos? Do it from the comfort of your couch and through an intuitive interface. Couple this with the abundance of games and other apps and you have a bonafide winner on your hands.

    Which tablet to get is an argument in itself. The iPad’s software lineup is a definite advantage but don’t discount its Android brethren either. The Transformer Prime looks incredible.

    Get it here

    Nettuts+ Holiday 2011 Gift Guide E-reader

    Or if you’re feeling a little bit old school, get them an e-reader. These feature e-ink technology, making reading a lot less strenuous on your eyes [as opposed to gazing at an incandescent light bulb that is a tablet's screen] and provide an experience that’s as close to a real book as possible whilst providing superior battery life.

    I personally like the Kindle but there are tons of options available in this segment.

    Get it here

    Nettuts+ Holiday 2011 Gift Guide USB Coffee Warmer

    It’s a well known fact that web developers account for roughly 97% of the world’s caffeine intake. And a vast majority of that is ingested in front of a monitor whilst mulling over some arcane piece of code that just refuses to work. Get him, or her, this magical coffee warmer that conveniently works over USB and win over their goodwill for the rest of your natural life.

    Get it here

    Nettuts+ Holiday 2011 Gift Guide IronKey USB Drive

    You can never really be too secure — specially in this digital age. Data gets swiped, accounts get hacked and passwords get broken on a daily basis.

    The IronKey USB drive provides you with a plethora of features including military grade encryption, hardware level authentication, anti-keystroke logger amongst a ton of others. It’s a little pricey compared to your run of the mill USB drive but the features definitely make it worth it.

    Get it here

    Nettuts+ Holiday 2011 Gift Guide Universal Remote

    The sheer number of remotes in a modern home is staggering. You need to have one for your television, receiver, speaker, settop box, DVD/BluRay and a lot more whamathingies. Not fun at all.

    While universal remotes have been around for a while now, the recent ones have really started kicking it up a notch. The Logitech Harmony series deserves a special mention since they feature great build quality, support a staggering number of devices and are quite easy to set up. There are also touch screen versions if you’re into that sort of thing.

    Get it here

    Nettuts+ Holiday 2011 Gift Guide MiFi

    Your mobile phone probably has access to a decently quick internet connection but you’ll mostly be limited to tethering it to your laptop or, worse, no tethering support at all. What happens if you’re a technophile and travel with a tablet and maybe a handheld gaming device that you’d like to get online?

    The MiFi range of devices are custom made for these specific scenarios. These connect to your carrier and provide internet access to the devices of your choice. It only supports upto 5 devices but hey, that should cover 99% of y’all.

    Get it here

    Nettuts+ Holiday 2011 Gift Guide Nerdy Desk Toys

    I’m sure you can’t count the sheer number of times you’ve given up on a piece of code and sat staring at a random dent on my desk wondering where it all went wrong. Let’s get this out of the way: I can’t fix your code for you and I really can’t fix the dent on your desk. However, completely unbiased, unquestionable studies from the toy making companies state that staring at a worthwhile nerdy toy on your desk should get your creative and analytical juices flowing.

    I’m pretty partial to physics based items but you can find a ton more options at the link below.

    Get it here

    Hardware

    Moving away from gadgets and toys, here are additions to your workstation and your workplace that are worth considering. Often overlooked, these are very obvious additions that can directly improve how you work.

    Nettuts+ Holiday 2011 Gift Guide A Second [or Third] Display

    Yes, it’s that simple — get them, or yourself, another display. It doesn’t matter whether it’s a 15″ TN panel or a 30″ IPS panel. A second monitor can vastly improve one’s workflow, and thus, productivity since there is no need to juggle around windows. Just keep your debugging window on the other display and you can be on your way. Having a video run on the other display is fun too!

    Get it here

    Nettuts+ Holiday 2011 Gift Guide An Ergonomic Chair

    Developers, like most people with white collar jobs, tend to sit for a large portion of their working day. Discounting the issues caused by being static for such long stretches, a major issue is how one tends to pick up lumbar issues quite quickly.

    Ensure their safety by buying them a lumbar supportive, height adjustable, comfortable chair. I’m partial to Aaron chairs but there are plenty of options out there.

    Get it here

    Nettuts+ Holiday 2011 Gift Guide Input Peripherals

    The input peripherals are how you to interact with your workstation and there is no need to be flimsy here. Be it a spiffy tactile keyboard or a touch gizmo to replace your mouse, just make sure it’s ergonomic. As someone who used to have carpal tunnel issues in the past, I can assure you it’s not fun.

    I like keyboard with low travel and illumination so I’m pretty partial towards the Logitech Illuminated keyboard.

    Get it here

    Nettuts+ Holiday 2011 Gift Guide Earbuds or Headphones

    I’m one of those people who tends to have music running constantly. Probably not the heart pounding, whumpa-whumpa sounding things that young people tend to listen to though. Ahh, I digress.

    A good quality headset is critical to your sanity as a developer. Not to mention coexisting with the people around you. Tried working when someone blares ‘Friday’ around you?

    I prefer a proper circumaural pair since it tends to be the most comfortable for me, big head and all.

    Get it here

    Nettuts+ Holiday 2011 Gift Guide MOAR Storage

    You can’t have enough storage space — it’s a fact of life. Chalk it upto cameras that record in much higher resolutions or faster internet speeds, or aliens, the fact remains that we’re constantly filling up our hard drives.

    Cloud solutions are nice but not always optimal. In these cases, get yourself a big hunk of storage that’s network attached and call it a day. I’ve used a Drobo in the past and it’s fairly good at what it does. It’s a little on the expensive side though. Or if you do have a higher budget, get them a nice, fast SSD and watch everything load up quickly.

    Get it here

    Assorted Fun

    If you’re looking for something generic, but fun, this is the place to be!

    Nettuts+ Holiday 2011 Gift Guide Skyrim

    Yes, Skyrim. There’s a very good chance this gift will make the giftee lose his job, relationship and house but goshdarnit, he’ll be a Dovahkiin!

    If that’s not an option, this year had an incredible amount of AAA releases — Assassin’s Creed: Revelations, Arkham City, Battlefield 3, Deus Ex: Human Revolution, Witcher 2, Portal 2, Modern Warfare 3. Phew. Take your pick and gift away.

    And promise to throat punch any whiners on online services and you’ll have their eternal gratitude.

    Get it here

    Nettuts+ Holiday 2011 Gift Guide Books

    Books make for excellent gifts. They’re fairly cheap, don’t require power, can carry it around at will and you won’t get hassled during a flight.

    Choosing which book to get is an incredibly intimate thing though. The best seller list at Amazon is a great place to start but don’t let it constrain you — there are tons of incredible books out there. If you’re fresh out of ideas, may I suggest the recent Steve Jobs biography? Whether you love or hate him, there’s enough material in there for you.

    Get it here

    Nettuts+ Holiday 2011 Gift Guide 30 Rock

    Shows pop up all the time and it comes down to personal preference. That being said, if you can watch this video and not be interested in this show, I’m going to silently weep for humanity and start plotting something fierce.

    Or if you’re looking for something a bit more serious, the debut season of Game of Thrones is incredibly well made and deserves a look. Be warned though — it’s made for an adult audience.

    Get the first season here

    Nettuts+ Holiday 2011 Gift Guide T- Shirts

    Tees makes for low profile, high humor gifts. Just choose something that the receiver will appreciate and you should be golden. Extra points if the tee’s contents contains subtle puns or jargon that no one else can understand. There are lots of places to get such clothing — I’ve linked a few of my recommendations below.

    Get it here

    Work Related Books

    …. or you could take the easy way out and present them with one of the books below. Yes, they’ll be glad that you bought them something that would truly enrich their lives but the next time the developer in your life is late to a movie or dinner, you’ll know you have yourself to blame!

    Professional JavaScript for Web Developers Professional JavaScript for Web Developers

    Author: Nicholas Zakas

    “Starting at the beginning, the book explores how JavaScript originated and evolved into what it is today. A detailed discussion of the components that make up a JavaScript implementation follows, with specific focus on standards such as ECMAScript and the Document Object Model (DOM).”

    JavaScript - The Good Parts JavaScript – The Good Parts

    Author: Douglas Crockford

    “Most programming languages contain good and bad parts, but JavaScript has more than its share of the bad, having been developed and released in a hurry before it could be refined. This authoritative book scrapes away these bad features to reveal a subset of JavaScript that’s more reliable, readable, and maintainable than the language as a whole-a subset you can use to create truly extensible and efficient code.”

    Nettuts image Pro JavaScript Techniques

    Author: John Resig

    “This book addresses all the points above in detail – modern browser support (including information on Internet Explorer 7), Object-Oriented JavaScript, testing and debugging, Unobtrusive JavaScript techniques using DOM Scripting, Ajax, creating and using blocks of reusable code, and looking towards the future of JavaScript.”

    Nettuts image jQuery Enlightenment

    Author: Cody Lindley

    “jQuery Enlightenment was written to express, in short-order, the concepts essential to intermediate and advanced jQuery development. Its purpose is to instill in you, the reader, practices that jQuery developers take as common knowledge. Each chapter contains concepts essential to becoming a seasoned jQuery developer.”

    Nettuts image Introducing HTML5

    Author: Bruce Lawson

    “Written by developers who have been using the new language for the past year in their work, this book shows you how to start adapting the language now to realize its benefits on today’s browsers. Rather than being just an academic investigation, it concentrates on the practical—the problems HTML5 can solve for you right away.”

    Nettuts image Professional WordPress Plugin Development

    Author: Brad Williams, Justin Tadlock, Ozh Richard

    “As one of the most popular open source content management systems available today, WordPress boasts a framework that allows you to easily customize and extend it through plugins. This comprehensive book shows you how plugins work, reviews the tools and APIs available in WordPress, and demonstrates how to extend the functionality of WordPress with plugins.”

    Wrapping Up

    I’m sure I’m missing a ridiculous number of gifts here so holler over at the comments section below. Or if you’ve already bought a gift for the developer in your life, let us know what you bought. Thanks for stopping by!


  • Permalink for 'Introducing Nettuts+ Builder – Version 2'

    Introducing Nettuts+ Builder – Version 2

    Posted: December 17th, 2011, 12:35pm MST by Jeffrey Way

    We’re pleased to announce the release of Version 2 of Nettuts+ Builder, a Mac app that handles the process of concatenating and compressing your assets, optimizing your CSS by running it through Prefixr.com, and uploading to your FTP server.

    What Exactly Does it Do?

    Intended for small projects and demos, all you need to do is drag your project folder onto Builder’s icon in the menu bar. Once you do so, it will:

    • Concatenate all scripts that are contained within <!-- js --> .. <!-- end js --> comments.
    • Concatenate all stylesheets that are contained within <!-- css --> .. <!-- end css --> comments.
    • Compress all CSS, JavaScript, and HTML files.
    • Run your CSS through Prefixr.com
    • Organize folder structures, if necessary
    • Optionally upload to a directory on your server.
    See it in Action Availability

    Nettuts+ Builder V2 is currently available free to all Tuts+ Premium members.


  • Permalink for 'Dig into Dojo: Dijit'

    Dig into Dojo: Dijit

    Posted: December 15th, 2011, 2:30pm MST by Andrew Burgess

    Maybe you saw that tweet: “jQuery is a gateway drug. It leads to full-on JavaScript usage.” Part of that addiction, I contend, is learning other JavaScript frameworks. And that’s what this four-part series on the incredible Dojo Toolkit is all about: taking you to the next level of your JavaScript addiction. In this episode, we’ll take a tour of Dijit, Dojo’s UI library.

    What is Dijit?

    So, what exactly is Dijit? According to the docs, “Dijit is Dojo’s UI Library.” It builds on what we’ve seen in Dojo Core and it’s very extensive: pretty much every UI widget you can think of is available. And, if you want to build your own, specialized widget, that’s certainly possible. If you’re following along with the Premium screencast, we’ll be building a Tuts+ widget. So, if you’re not a Premium member, now’s a good time to sign up.

    Dijit is Dojo’s UI Library

    For terminology’s sake, remember that Dijit is the namespace under which Dojo’s UI widgets live.

    Here’s how this is going to go down: just showing you how to use a bunch of Dijits would be akin to showing you how to use a bunch of jQuery plugins. Of course, Dijits aren’t really comparable to jQuery plugins, but the point stands: once you’ve used one, you’ve used ‘em all (caveats aside). So, we’ll be talking about the diverse and sundry ways to create and use Dijits. Then, we’ll take a brief look at some specific Dijits, just to whet your appetite.

    Of course, we’ll need to use some Dijits as examples while we learn. We’ll keep it basic and use a plain button widget.

    Why Should I Use Dijit?

    After you learn how to use widgets, you might think it’s a lot easier to not use many of them; after all, why not just use the <button> element, instead of the button widget? There are a couple of reasons to consider here:

    • Theming: by using Dijit widgets, you’ll be able to use Dojo’s built-in themes. Four themes are included with the toolkit; or, you can make your own or find others online. Simply add link in the theme CSS file, add the theme name as a body class, and all your widgets are given matching uniforms. Ten-hut!
    • Accessibility: All widgets (at least, the “blessed” ones, distributed with the Dojo toolkit) are made for accessibility. They’ve got high-contrast themes, keyboard accessibility, and are screen reader friendly.
    • Internationalization: Widgets are also made to work well with any language, text-direction, and representation (think numbers and dates).

    So, now that you know the benefits of using Dijit, let’s learn how to use it.

    How do I Use Dijit?

    There are two ways to instantiate widgets: the programmatic way, and the declarative way.

    Dijit widgets are actually just Dojo classes that inherit from Dijit._Widget, and often Dijit._Templated. I know we haven’t discussed Dojo’s object-oriented side, and we won’t be able to in this session (you’ll learn some in the Premium screencast), but just know that Dojo can make JavaScript classes. Of course, they aren’t really classes, they’re JavaScript constructor functions; however, you can flex some serious OO muscle with Dojo’s methods.

    So, back to widgets. There are two ways to instantiate widgets: the programmatic way, and the declarative way. If you’ve used UI widgets in other libraries, you’re probably familiar with the programmatic method: put some widget markup up in your HTML, and interact with it from the JavaScript. Let’s try it!

    I’ll assume you’ve set up a working page, loading Dojo from a CDN, as we have before. So, let’s make a Dijit button.

    Before we start, you’ll definitely want to make sure you have a theme loaded; otherwise, your widgets will stick out like nobody’s business.

    <link rel="stylesheet" href=" [ajax.googleapis.com] />
    

    That’s the Claro theme; you can replace both instances of “claro” with “tundra,” “soria,” or “nihilo.” to try the other bundled themes. To use the loaded theme, you’ll have to add the theme’s name as a class on your <body> (technically, it doesn’t have to be the <body>, but some element that is a parent of any widgets that should be themed.)

    Now that our theme is loaded, let’s programmatically create a button. First, we’ll add the button markup to our document:

     <button id="btn" type="submit">Click Me!</button>
    

    Now, let’s instantiate this in our JavaScript.

    dojo.require("dijit.form.Button");
    
    dojo.ready(function () {
      var btn = new dijit.form.Button({ onClick: handleClick}, "btn");
    });
    
    function handleClick () {
      alert("clicked");
    }
    

    The dijit.form namespace includes any form widgets you might need.

    We have to load the file containing the widget class before we can use; then, we can instantiate the button with new dijit.form.Button. Notice that the “class” (constructor function) is stored at the same “path” we required. While this isn’t forced technically, it’s very much the standard way to do it. The exception to that is when a single file loads multiple classes: this “dojo.form.Button” file is a great example: it loads dijit.form.Button, dijit.form.ComboButton, dijit.form.DropDownButton, and dijit.form.ToggleButton.

    Let’s look a little more closely at the parameters we’ve passed to dijit.form.Button. In this case, we’ve passed an object, and a string, which is the id of the widget node in our DOM; we could instead have passed a reference to the node itself, if we wanted to. Of course, any widget options can be set in that first parameter object; here, we’re setting the click handler via the onClick option.

    You’ve probably figured this out by now, but know that the dijit.form namespace includes any form widgets you might need.

    Now, load up the page and you should see something like this:

    The Button

    Behold, a programmatically-created, Claro-themed, Dijit button. That wasn’t too hard, now, was it?

    Now, open your browser console and check out the DOM; specifically, look at that <button> node. You’ll see that our instantiation have removed our node and replaced it with a <span> with child <span>s, all with many attributes. This is part of how Dijit widgets work: more often than not, they replace the nodes you have with a template of their own. In fact, if we left out the second parameter (the id string or DOM node reference), the new nodes would be made, but just not injected into the DOM. Then, we could place it ourselves:

    var btn = new dijit.form.Button({ label: "Hello" });
    dojo.place(btn.domNode, dojo.body());
    

    Notice that we give the button a label (otherwise, it would be blank); then, our dijit.form.Button instance has a domNode property that reference the nodes it created for itself.

    So, if we can do it this way, and Dijit gets rid of our initial nodes anyway, why not always do it this way? Well, don’t forget that you want your app to work without JavaScript. If you have the nodes in the DOM, you have a basic experience for people with JavaScript turned off. Then, Dojo will replace that with the better experience if it can. Of course, the other benefit is that using hard-coded DOM nodes does fill a lot of the default parameters, depending on widget class, of course. As we saw, when we didn’t use a node, we have to define a label property to get text in the button.

    All this seems pretty natural, right? If you’ve used UI widgets in other libraries, this seems pretty run-of-the-mill. However, Dojo ups the ante by allowing you to put all the properties for the widget in your HTML. This is that declarative way of which I spoke.

    Here’s how you do it. Remove the JavaScript we’d written previously, leaving only this:

    dojo.require("dijit.form.Button");
    
    function handleClick () {
      alert("clicked");
    }
    

    Now, fix up our <button> element so that it looks like this:

    <button id="btn" type="submit" data-dojo-type="dijit.form.Button" data-dojo-props="onClick: handleClick" data-dojo-id="my.btn">Click Me!</button>
    

    We’ve added HTML5 data-* attributes to our <button>: data-dojo-type and data-dojo-props. I think you’re starting to see how these are related: the type is the widget class “path”; the props are the properties, in key-colon-value-comma format. What does this do? It instantiates our widget for us. Since we aren’t creating it in our JS, the data-dojo-id attribute gives us a change to create a variable that points to the widget instance. Notice, it can be as a property of an object, if you want.

    Not so fast though. Dojo isn’t magic after all, so we do have to let it know that we want it to parse out any widgets declared in our HTML when the library loads. Of course, it will only find widgets whose class we have dojo.required. The most common way to do this is to set parseOnLoad: true in your djConfig.

    Let’s take a quick detour and talk about djConfig. This objects sets a few configuration options for Dojo; besides parseOnLoad, there are a number of debugging, localization, and resource-finding settings. There are three ways of settings djConfig. First, you can make a custom build of Dojo, which is beyond the scope of this session. Second, you can create a global djConfig object; if you do this, you have to be sure that it appears before the Dojo base file is loaded.

    <script>djConfig = { parseOnLoad: true };</script>
    <script src=" [ajax.googleapis.com] 

    The other way, which is much more common, is to use the data-dojo-config property on the script node that loads Dojo Base:

    <script src=" [ajax.googleapis.com] data-dojo-config="parseOnLoad: true"></script>
    

    So djConfig: it’s the most common way to parse declared widgets. The other way is to manually call the method that parseOnLoad calls: dojo.parser.parse(). This will parse your HTML, find the widgets and create them.

    We’re just about done with our general overview of how Dijit widgets are used, so I want to wrap up a few loose ends. First, note that all the HTML5 data-* goodness ain’t always been so. Dojo used to use plain, non-standard attributes, and will still accept them. So, instead of data-dojo-type, you would use dojoType. Instead of data-dojo-config, you’d use djConfig. Instead of data-dojo-id, you’ve got jsid. And data-dojo-props was split into individual properties. So, using our button example, this:

    <button id="btn" type="submit" data-dojo-type="dijit.form.Button" data-dojo-props="onClick: handleClick, iconClass: 'dijitIconCopy'" data-dojo-id="my.btn">Click Me!</button>
    

    Would be, with old, non-standard attributes, this:

     <button id="btn" type="submit" dojoType="dijit.form.Button" onClick="handleClick" iconClass="dijitIconCopy" jsid="my.btn">Click Me!</button>
    

    Notice how onClick and iconClass are two separate properties in old-style.

    Both these styles work, but I’ll be sticking with the HTML5 attributes.

    Second, I’ll note that if you don’t set a property when you create a widget, you can do so with the widget instance’s set method:

    var btn = new dijit.form.Button({});
    btn.set("label", "Click here!");
    btn.set("onClick', function () { alert("clicked!"); });
    

    There’s also a get method, so retrieve your properties; of course, this works with those read-only properties, too.

    And the watch method is pretty cool: pass it the property you want to watch, and then a function: if that property is changed, your function will get called:

    var btn = new dijit.form.Button({}, "btn");
    btn.set("onClick", function () { this.set("label", "clicked") });
    btn.watch("label", function (property, oldValue, newValue) {
      alert("Property " + property + " was changed from " + oldValue + " to " + newValue + ".");
    });
    

    I sure was caught off guard by declaratively creating widgets and I’m still not exactly sure how I feel about it.

    Of course, there are other methods and properties that widgets have in common, as well as widget-specific ones; we can’t cover them all here, of course, but skip to the end if you can’t wait for some tips on learning about the specific widgets of your choice.

    Finally, what do you think of this declarative way of creating widgets? I sure was caught off guard when I first saw it, and I’m still not exactly sure how I feel about it. With the programmatic way—the way every other library I’ve seen does it—you have to either match up HTML and JavaScript (which requires work in two places) or place new nodes from the JavaScript (which isn’t no-JS-friendly).

    The benefit of the declarative method is that all the information about a widget is in one place; the UI and the logic. However, is that what you want? I’ve done a bit of desktop programming, but from what I’ve seen on both Windows and Mac, UI and logic are separated, in different files even. So it’s not like this is a throwback to anything. In any case, you’ve got the power to do it however you want. Choose wisely . . .

    A Dijit Amuse-boche

    Let’s wrap this tutorial up by looking at a couple of Dijit widgets, and then talk about how you can learn to use ‘em practically. Remember, however I show you the widgets, they can be created in declaratively or programmatically.

    dijit.ColorPalette

    Exactly what it says, this is a simple little colour picker.

    <div id="colors"></div>
    <p>The selected colour is <span id="selectedColor"></span>.</p>
    
    dojo.require("dijit.ColorPalette");
    
    dojo.ready(function () {
      var selectedColorEl = dojo.byId("selectedColor"),
          colors = new dijit.ColorPalette({
            onChange : function () {
              selectedColorEl.innerHTML = this.value;
            }
          }, "colors");
    });
    
    Color Palette widget

    This is a good example of a widget that takes very little information from a DOM node, unless you give it the Dojo attributes. It’s also a good example of how you can work with widgets that accept / set some kind of value (like a dijit.form.FilteringSelct and dijit.form.verticalSlider).

    dijit.Editor

    A rich text editor: this is a good example of how easy Dijit makes creating complex UI pieces a breeze.

    <div id="editor" data-dojo-type="dijit.Editor" data-dojo-id="editor" data-dojo-props="
    	plugins: ['bold','italic','underline','|','cut', 'copy','paste']"></div>
    
    <button data-dojo-type="dijit.form.Button" data-dojo-id="btn" data-dojo-props="onClick: handleEditor"> Get Text </button>
    
    dojo.require("dijit.Editor");
    dojo.require("dijit.form.Button");
    
    dojo.parser.parse();
    
    function handleEditor () {
      dojo.create("div", { innerHTML: editor.value }, dojo.byId("main"), "last");
      editor.set("value", ""); // editor.value = "" doesn't clear the text
    }
    
    Dijit Editor

    Note, I probably wouldn’t ever connect an event handler via an attribute in real life; however, it’s a good example of Dojo’s flexibility.

    dijit.ProgressBar

    A handy progress bar, useful when doing lengthy AJAX stuff or heavy calculating action:

    <div id="progbar"></div>
    
    dojo.require("dijit.ProgressBar");
    
    dojo.ready(function () {
      var progbar = new dijit.ProgressBar( { maximum: 150 }, "progbar");
    
      function updateProgressBar() {
        progbar.set("value", parseInt(progbar.get("value")) + 1);
        if (progbar.get("value") === 150) {
        progbar.set("label", "Complete!");
        } else {
        setTimeout(updateProgressBar, 100);
        }
      }
      updateProgressBar();
    });
    
    Progress Bar Learning More

    For the most part, you’ll learn by osmosis butwhen you’re ready to dive deeper, you’ll want to check out the API docs.

    Of course there are a ton of Dijits; I can’t teach you to use them all. So, let’s close up by looking at how you can learn to use the widgets your hankering after.

    For the most part, you’ll learn by osmosis (isn’t that the way most dev work is, though?). For example, while reading the reference guide page for dijit.ColorPalette, I learned that most widgets that set some value have an onChange event. In fact, the reference guides are the first of the two best places to get documentation for Dijits. If you head over to the Dojo documentation page, you’ll see three links: Tutorials, Reference Guides, and API Documentation. The tutorials are listed on that page, and they’re great, but we’re interested in the reference guides and API docs.

    So, click Reference Guides, and then Dijit on the right sidebar. Here’s a great place to start when you’re trying to figure out how to use a widget; most articles give you examples of both programmatic and declarative creation, as well as common properties.

    If you’re ready to dive deeper, though, you’ll want to check out the API docs. This neat web app is Dojo Documentation: The Complete Series. Navigate the namespaces on the left, and you’ll get all the details on the right. This can be somewhat cryptic when you’re starting, though, so certainly default to the reference guides.

    Of course, Googling “Dijit <widget-name> tutorial” often serves up something tasty.

    Conclusion

    And that’s a wrap for this third episode of Dig into Dojo. If you’re interested in creating a widget of your own, you’ll want to check out the premium screencast that goes with this tutorial.

    Otherwise, I’ll see you in the final episode of Dig into Dojo, where we’ll discuss Dojox.


  • Permalink for 'Should You Learn CoffeeScript?'

    Should You Learn CoffeeScript?

    Posted: December 14th, 2011, 1:43pm MST by Jeffrey Way

    I’d imagine that I represent a large portion of the web development community. I’m very intrigued by CoffeeScript; I’ve even learned the syntax and used it in a few demos. However, I haven’t yet taken the plunge and used it in a real project. It comes down to this one question for me: is CoffeeScript something that is truly worth investing time and effort into learning?

    I wasn’t sure, so I compiled a list of frequently asked questions (along with a few of my own), and asked some masters in the industry – on both sides of the fence – for their advice.

    The Panel 1 – Perhaps the most common question: if I’m a reasonably solid JavaScript developer, is there any real incentive for me to learn CoffeeScript? Jeremy Ashkenas

    Yes. CoffeeScript is not an entirely new and strange language. It exists to allow “reasonably solid” JavaScript developers to write the same code they were going to write in the first place, in a more readable and fluent way. The basic idea is to write what you mean, instead of writing within the limits of historical accident. For example, if I want to loop over every item in a list, in CoffeeScript, I can write what I mean:

        for item in list
          process item
    

    Whereas in JavaScript, I partially obscure my intention, by writing:

        for (var i = 0, l = list.length; i < l; i++) {
          var item = list[i];
          process(item);
        }
    

    CoffeeScript allows “reasonably solid” JavaScript developers to accomplish the latter by simply writing the former.

    Other Incentives Include
    • The ability to write code that works in old versions of Internet Explorer without having to compromise or shim
    • Not having to worry about JavaScript pitfalls like trailing commas and automatic semicolon insertion
    • Cleaned up semantics where every language construct can be used as part of a larger expression
    • and a boatload of additional features listed on [CoffeeScript.org]
    James Padolsey

    If you’re comfortable in JavaScript, and are able to create expressive APIs that suit you well, then I don’t feel there is a sufficient incentive for learning CoffeeScript. Widening horizons and learning new programming paradigms and patterns is always good, but if you’re learning CoffeeScript so it can eventually replace your need for JavaScript then there are other things to consider.

    John-David Dalton

    If you’re great with JS, I don’t think there is any real incentive to learn CoffeeScript. Things like accidental leaked globals, switch statement fall-throughs, and other potential JS gotchas can be handled by JS linters/text-editors and don’t require a compile step / Node.js. Class sugar is so basic any JS developer can, if needed, simulate it in a handful of lines. I happen to like double equals ==, and switch statement fall-throughs, and know how best to write my JS.

    Having to conform to someone else’s rules of what they feel is appropriate doesn’t mesh well with me.

    Also, don’t forget CoffeeScript isn’t without its own warts.

    Dave Ward

    Continually exposing yourself to new perspectives and technologies is a critical part of keeping yourself relevant in our field.

    Absolutely. Continually exposing yourself to new perspectives and technologies is a critical part of keeping yourself relevant in our field, and CoffeeScript is certainly a great candidate for that in the JavaScript space. Even if you ultimately decide that CoffeeScript doesn’t appeal to you, being able to write a bit of CoffeeScript should be a prerequisite to making an informed decision either way.

    Nathan Smith

    I have been using CoffeeScript for a few months now, as part of my job as a front-end dev on a Rails team. I don’t know if I would say there’s “incentive” to learning CoffeeScript if you already know JavaScript. I’m not sure there would be an incredible speed boost to be gained, because really there is no “best” tool for a job, only one you’re most familiar with to accomplish a given task.

    Though I enjoy the comfy feel of JavaScript (like a well broken-in pair of shoes), there is also a lot to like in CoffeeScript — the “unless” syntax, for example. I would liken using CoffeeScript to having a conversation with a friend who majored in English, correcting your grammar all the while. It’s great if you want that guidance, but sometimes I just want to “keep it casual” and speak slang, without worrying about what that’s going to translate into.

    Note: I suspended judgment until after reading Trevor Burnham’s book on CoffeeScript. Now that I know more about it, I’m fine using CS when I am on a team that already uses it, but I still tend to prefer JS for my own projects.

    Ryan Florence

    Absolutely. CoffeeScript is influencing TC-39′s decisions (like paren-free, class syntax, arrow syntax, etc.). The future versions of JavaScript will likely look a lot like CoffeeScript. I decided to learn it after listening to Brendan mentioning its influence during his talk at TXJS.

    If there is anything to learn about CoffeeScript is that it’s _Just JavaScript™_. I consider it a part of our community and have really enjoyed learning it and using it. It doesn’t feel like a different language when you use it.

    Brendan Eich

    (Limiting my response to responding to Ryan Florence’s comments about TC39, except in my final paragraph.)

    The influence of CoffeeScript on TC39 in practice is mostly me writing and proposing strawmen. None has yet stuck. I’m going to retool paren-free to be more like CoffeeScript in that newlines will be more significant in statement heads (this solves some nasty hard cases Waldemar Horwat identified, see es-discuss). But no indentation-based block structure.

    Arrow function syntax was worth doing but it’s not going to make it. Block lambdas are in better shape but not yet “in”. As Jeremy said, “For the record, I too favor [block lambdas] if arrows in JS will need curlies to delimit blocks. Curlies or arrows, not both.”

    That JS and CoffeeScript are formally co-expressive — have the same semantics — is huge. Yes, this means you could have just written JS. But productivity and beauty (in the eyes of some beholders) matter; syntax matters.

    Oscar Godson

    In short, no. The incentives to CoffeeScript are incentives, in my opinion, that are for developers who don’t fully understand the language. For example, for…in loops and leaking globals and not understanding “this” fully. If you understand those things you don’t make those mistakes in the first place, and if you do, you know what the problem is right away and know how to fix them. Having an entire transpiled language to fix common mistakes seems like overkill.

    Marco Chomut

    Out of professional curiosity, you should always be exploring new languages, technologies, libraries, and frameworks.

    There are a few different approaches to answering this question. First and foremost, out of professional curiosity, you should always be exploring new languages, technologies, libraries, and frameworks. The worst thing that can happen to you as a developer is to become stuck in a rut. If the first language you learned was COBOL, ColdFusion, or PHP, and that’s still the breadth of your knowledge five years later, you’re just asking to become obsolete. Then again, it’s equally worse to jump ship onto the new flavor-of-the-month every time something mildly interesting appears in your news reader or Twitter feed. Have a healthy curiosity while maintaining reasonable skepticism.

    Arriving back on topic, if you and your co-workers are already well-versed in restricting yourselves to the “good parts” of JavaScript, and are painfully aware of its idiosyncrasies, than CoffeeScript probably won’t offer you much. It’s a more Ruby or Python-like approach to syntax for the language that does everything it can to prevent you or your team from shooting themselves in the foot. But it’s not for everyone.

    Trevor Burnham

    Obviously I have a financial stake in this question (my book was released by PragProg in May), so you can take my words with a grain of salt. But yes, I think that learning CoffeeScript is worth the time. It doesn’t take much effort to learn; CoffeeScript is basically the sum of a few dozen syntactic sugars on top of JavaScript. And the reward is that you get to write more beautiful code, when you want it. For instance, some JavaScripters use CoffeeScript just for their unit tests.

    Some folks complain about having to use a compiler on top of JavaScript, but some of JavaScript’s flaws—like automatic global creation when the var keyword is omitted (see here)—more or less necessitate the use of other tools, or strict mode. CoffeeScript is one such tool, and is easily among the most popular.

    Alex MacCaw

    My CoffeeScript programs end up as being about half the length of the equivalent source written in JavaScript.

    Absolutely; in fact I’d say there was even more of an incentive to learn CoffeeScript if you’re a solid JavaScript developer. CoffeeScript certainly requires some JavaScript profiency, there’s no getting away from it. JavaScript knowledge is a pre-requisite, especially when it comes to debugging.

    However, for good JavaScript developers, CoffeeScript offers a lot of advantages, such as fixing common bugs concerning global variables, semicolons and equality comparisons. Frankly, even the best JavaScript developers make these sort of simple mistakes from time to time.

    The other major advantage CoffeeScript offers me over JavaScript is syntactical sugar such as shorter function declarations, comprehensions and a simple class abstraction. My CoffeeScript programs end up as being about half the length of the equivalent source written in JavaScript, with twice the clarity.

    2 – Is CoffeeScript targeted at JavaScript developers? Or, is it for devs who prefer other languages, like Ruby, and haven’t yet learned the ins and outs of JS? Jeremy Ashkenas

    The core idea with CoffeeScript is to express JavaScript semantics in as readable and minimal a syntax as we can find.

    CoffeeScript is targeted at JavaScript developers. It certainly borrows ideas from other dynamic languages, including Python, Ruby and Perl. But ultimately, the core idea with CoffeeScript is to express JavaScript semantics in as readable and minimal a syntax as we can find.

    John-David Dalton

    It seems to me developers who prefer languages like Ruby gravitate more towards CoffeeScript than those that don’t. Although, it’s common to find developers having love / hate opinions about it in any group.

    Nathan Smith

    I think CoffeeScript is targeted at people that understand JavaScript, but for whom it isn’t their language of choice. Otherwise, (obviously) they would prefer to just be writing JS. Whether one knows the ins and outs of JS when starting with CS, it is essential if one is to get the most out of using CS.

    Oscar Godson

    I work at Yammer with a lot of senior JavaScript engineers; none use it. I noticed that the friends who do use it and are extremely happy about it are Rails people. For example, at Posterous, they use it but don’t have any real JavaScript engineers. We have Rails people here, but they only do Rails – not JavaScript.

    Ryan Florence

    I’d have to defer to Jeremy for that one, but I do think it appeals mostly to Rubyists who are finding they spend most of their day in JavaScript. CoffeeScript knowledge is not a substitute for JavaScript knowledge. Scope is kind of different; other than that, it’s just a cleaner syntax.

    Marco Chomut

    I’d definitely say that it’s targeting both existing JavaScript developers and those coming from other dynamic languages who are somewhat new to the front-end web world. I personally discovered it after already having a decent amount of “raw” JS experience, and it was refreshing to work with what I imagine a modern-day client-side language would look like. While it’s just my personal approach to learning things, I don’t think I would have dove straight into CoffeeScript without any prior knowledge of the language it was built upon.

    It’s important to always have at least a rudimentary understanding of whatever “black boxes” of abstraction exist in your toolkit.

    Trevor Burnham

    If you’re someone who likes JavaScript but wants to write more expressive code, CoffeeScript is going to be the obvious choice.

    CoffeeScript’s goal is to stay as close as possible to the underlying JavaScript while improving on the language’s syntax. That makes it very different from, say, Dart, or GWT, or something that reorders code like TameJS. So I think that if you’re someone who likes JavaScript but wants to write more expressive code, CoffeeScript is going to be the obvious choice.

    Obviously it’s disproportionately popular in the Ruby world, since it’s borrowed many Ruby-isms like postfix if/unless and has an extremely prominent evangelist in dhh, but it’s also quite popular in the Node.js world, which says a lot.

    Alex MacCaw

    I’ve used JavaScript for years, and wrote the O’Reilly book on JavaScript web applications. I think you could say I’ve learnt the ‘ins and outs’ of the language. That said, I personally plan to never write plain JavaScript again, not because I don’t like the language, but because I love writing CoffeeScript so much.

    CoffeeScript is for people who deeply understand and respect JavaScript.

    3 – When Dart was announced, it was met with immediate slander by much of the JS community. Though not an entirely different language, the same is partially true for CoffeeScript. Are some developers simply afraid of learning yet another new thing, or are their criticisms justified?

    Jeremy Ashkenas

    With the release of Dart, the web development community was faced with the peril of Google forcing a new, nonstandard language into a shipping web browser.

    Dart is a different story. With the release of Dart, the web development community was faced with the peril of Google forcing a new, nonstandard language into a shipping web browser. As we know well from the web — once you ship something in a browser, it tends to be there forever. In addition, Dart retreats from the dynamism of JavaScript, and instead exists as a somewhat static language, where types can be checked at compile time, but are erased at runtime. The JavaScript community perceived this as a cynical gesture to make Java developers feel more at home in Dart, being able to write types that appear similar to Java types, even though they’re treated as comments when the program runs. It’s not just JavaScript developers being wary of the Dart push, browser implementors are wary as well.

    Now, let’s take the CoffeeScript case. CoffeeScript has felt threatening to a surprising number of JavaScript developers, in a way that other languages have not. You don’t hear JS programmers worrying about other new languages like Clojure or Scala, or even compile-to-JS languages like GWT or Objective-J in anything approaching the same volume.

    Note that I’m not talking about people who simply choose to continue to use JavaScript — I continue to use JavaScript for many projects as well. I’m talking about the fearful rhetoric of “I won’t use your library because you wrote it in CoffeeScript”, or “CoffeeScript makes you forget how to write JavaScript.”

    CoffeeScript feels threatening to JavaScript developers precisely because it’s so close to JavaScript.

    Because the semantics are the same, every CoffeeScript program is fully interoperable with JavaScript, and vice-versa. You may already be using a library written in CoffeeScript without even knowing it (like Zombie.js, Riak-JS, or xml2js). In addition, CoffeeScript is actually being used — it’s currently the 13th most popular language on GitHub.

    As as JavaScript developer, confronting this situation — where there’s a fully compatible alternative to JavaScript, with the same performance profile — forces you to answer the question: “why haven’t you tried CoffeeScript yet?” Many of the posts that we’re seeing are developers justifying their answer to that question for themselves. If I hadn’t tried CoffeeScript yet, I’d probably be writing the same kind of posts.

    James Padolsey

    The real battle is creating clean, intuitive and maintainable APIs.

    Dart’s slightly different. One, it’s from Google! i.e. that massive monopoly that we’re supposed to be wary of. Beyond the various political issues, Dart doesn’t seem to bring anything to the table other than a more Java-esque syntax, which many developers aren’t too fond of, myself included. I prefer to stick to the most expressive API/languages I have at my disposal. When it comes to CoffeeScript, though, I am cautious because really, it’s just JavaScript, but with a completely different syntax. JavaScript’s malleable enough for me to create the APIs and functionality that I need. I don’t much care for convenience sugar unless it really enhances my ability to write good code. Some of CoffeeScript’s features, like destructuring assignment and the existential operator, are really quite awesome, but to be honest, they’re just minor sweetness, and similar functionality can be gained in JavaScript (see JS 1.7 for destructuring assignment too!), although with a little more verbosity. The real battle is creating clean, intuitive and maintainable APIs. CoffeeScript isn’t going to help you a great deal there. Like I said, it’s sugar.

    John-David Dalton

    I don’t think it’s being afraid of something new. For me at least, it’s more about not wanting to over-engineer and having more control over my JS.

    Dave Ward

    It’s difficult to speak for others, but I don’t get the impression that many JavaScript developers are avoiding CoffeeScript because they avoid new things. If anything, I think most developers who are aware of CoffeeScript at all are probably on the early adopter’s end of the curve.

    In particular, I believe that reluctance toward adding CoffeeScript’s compilation step into client-side development is objectively justified, not related to any previous investment in learning JavaScript.

    Nathan Smith

    With any potentially disruptive new technology, those who have staked their claim on the current way of doing things tend to go through the five “stages of grief.

    This was my experience, anyway…

    1. Denial — “I’ll never use CoffeeScript.” (or Dart)
    2. Anger — “I wish people would shut up about it already!”
    3. Bargaining — “Okay, I guess it has *some* good parts.”
    4. Depression — “I can’t believe I have to learn this.”
    5. Acceptance — *Shrug* ~ “Use the best tool for the job.”

    That said, there are some justifications to the criticisms of CoffeeScript (and Dart). However, whereas CoffeeScript attempts to adhere to the “spirit” of JavaScript (terse code, etc), the end-game for Dart is to get developers writing an entirely different language altogether (preferably interpreted in a browser’s VM, instead of being precompiled to JS). Dart is more akin to Java than JavaScript.

    The most valid criticism against any language that would attempt to supplant JavaScript is that JS has the world’s largest install base of any language runtime (on desktop browsers, server, and mobile devices). It might not be perfect, but as far as distribution goes, it “just works.”

    Brendan Eich has already expressed his interest in seeing aspects of CS folded back into future versions of ECMAScript. By contrast, Dart has been met with harsher criticism from not only JS developers, but from the WebKit community.

    Oscar Godson

    Yes and no. I tend to be more critical of things before I’ve tried them, but I did try CoffeeScript to see what all the hype was about. It was nice, but it’s not worth it. Why have a compiled language to *just* help you with common JS warts and to make JS more “pretty”? That’s what puts me off about it. JavaScript engineers do tend to be elitist though, I agree with that, but in this case I believe it’s for a good reason. The reason being, don’t write a totally different language to fix some warts about it.

    Ryan Florence

    [...] We’re just so tired of fragmentation.

    CoffeeScript and Dart aren’t even comparable. Dart aims to replace JavaScript, CoffeeScript is nothing more than a nice coat of paint. You can use CoffeeScript and still “always bet on JS”. I think front-end devs are happy to learn new things (our environment is always broken, you’d have to like learning stuff to survive), we’re just so tired of fragmentation. It’s completely justified to freak out if you see “ActiveX 2.0″ coming. CoffeeScript is not a threat to JavaScript.

    Marco Chomut

    I believe both reactions were equally justified (although when Google is involved, people always tend to exaggerate their opinions one way or the other for whatever reason). CoffeeScript was a re-imagining of JavaScript from the Ruby and Python communities. Dart was a re-imagining from a subset of the Java community. Language biases aside, I honestly don’t believe that Java-fying an already dynamic and (arguably) verbose language is the correct approach.

    It probably didn’t help that the JavaScript community was already allergic to the idea of Dart before it was even announced, due to the set of “leaked” correspondance surrounding it.

    Trevor Burnham

    Of course some of the criticisms of CoffeeScript are justified. I mean, “significant whitespace is evil” is a lame one, but “it divides the community” is legit. There’s something to be said for JS being a lingua franca. But you look at very common JS mistakes like forgetting a comma in a multi-line object literal (or adding an extra one at the end of the last line), and it causes your whole app to crash… for a certain kind of programmer (myself included), not having to deal with that is a big breath of fresh air.

    I think CoffeeScript and JS are going to peacefully coexist for the foreseeable future, and there are gonna be haters, and that’s fine. That’s how you know it’s a real programming language.

    Alex MacCaw

    CoffeeScript doesn’t intend to replace JavaScript, or abstract it away, but rather to enhance it.

    As others have mentioned, Dart is a completely different beast to CoffeeScript, and many of the criticisms directed at Dart were regarding implementation details and Google’s approach, rather than just the existence of another language. Frankly, CoffeeScript is an entirely different language to Dart.

    Google took rather a walled garden approach to Dart, and I get the impression they didn’t really look outside the confines of their company for inspiration. Whether this was because of some sort of Not Invented Here syndrome, or the fact that they needed a language that would appeal to their Java developers, I’m not sure. However, Dart strikes me as something that is very specific to Google’s needs, rather than something that’s applicable at large.

    CoffeeScript doesn’t intend to replace JavaScript, or abstract it away, but rather to enhance it. So, not only are the languages completely different, but the motives behind them are very different. Thus it’s difficult to compare criticism between the two.

    4 – Is it fair to assume that, if you’re against the idea of CoffeeScript, then you’re likely also against CSS preprocessors, like Sass and Less? Or, do you see a specific distinction between the two (as I do)?

    James Padolsey

    I’ve never used Sass or Less so I can’t really comment. I will say that the general idea is the same in that they’re all slightly heightening the level of abstraction, allowing you to quickly get at functionality without having to type the verbose alternative. I will say that the thing keeping me from picking up CoffeeScript is very different to what would keep me from picking up a CSS preprocessor.

    John-David Dalton

    I don’t work heavily with CSS and haven’t used a CSS preprocessor but I can understand the need to manage the cluster of vendor prefixes. I’m also not as comfortable with CSS as I am with JS.

    Nathan Smith

    I don’t think that is an entirely accurate assumption. While there might be some who are against all preprocessing of client-side code, with Sass (and Compass) you get a layer atop CSS that’s very “close to the metal” in terms of syntax. One of the benefits of Compass is the ability to write one line that is transformed into multiple lines of vendor prefixed code. One needn’t memorize different variations on the same styling that will ultimately be deprecated when a standard is agreed upon. Sass (with Compass) example:

    #foobar
      +background(linear-gradient(#fff, #ccc))
    

    That reads cleanly, and is somewhat similar to what the standard might become in CSS.

    CoffeeScript, on the other hand, adds a new syntactic layer that seeks to be a departure from JavaScript, incorporating idioms from other languages that are not native to JS.

    Sass adds variables, color math, and a slew of things that cannot be done in CSS alone. Whereas, CoffeeScript provides an alternative approach to what JavaScript is already perfectly capable of doing. I believe that’s why we’re having this discussion — Some see value in that. Others don’t.

    Oscar Godson

    I personally have nothing against CSS preprocessors because they add functionality. I don’t use them because I’m a purist you could say, but they do save time with less typing – particularly for people who do lots of CSS coding. They also don’t aim to fix “broken” things – just extend it. I don’t use it and don’t see myself ever using it for personal stuff but I’m not opposed to using it.

    Ryan Florence

    There is a distinction. SASS, Less, Stylus etc. all bring something to CSS that it doesn’t already have.

    There is a distinction. SASS, Less, Stylus etc. all bring something to CSS that it doesn’t already have: logic–it turns your CSS into an application. CoffeeScript doesn’t bring anything “new” to JavaScript in the same way, which is why it’s so debatable. Not using a CSS preprocessor isn’t really even debatable for anything non-trivial.

    Marco Chomut

    CoffeeScript provides cleaner syntax…

    I’m going to have to agree with the other answers here that the CSS “equivalents” of CoffeeScript, such as SASS or Less, are often judged quite differently. For me, SASS is always a default on any new project that I work on, while CoffeeScript continues to be debatable. CoffeeScript provides cleaner syntax, does its best to keep a developer shielded from the bad parts of JavaScript, and allows you to avoid prototype-based inheritance with its built-in class structure. SASS on the other hand offers a slew of (very-necessary) features to CSS that you would otherwise not be able to have. Variables, functions, mixins, the list goes on and on. CoffeeScript doesn’t really offer any of these meta-features to JavaScript, and really just boils down to syntactic sugar.

    Trevor Burnham

    I’m honestly amazed that people are still using Sass/SCSS.

    Sass is an interesting example because it went through a big split itself: Originally, it was a fully whitespace-significant alternative to CSS, and of course some people loved that and others hated it. Now it comes in two flavors: The whitespace-significant “Sass Classic” syntax, and the CSS superset SCSS. They’re both annoyingly strict; the “Sass Classic” compiler will yell at you if you use so much as a semicolon. Then TJ Holowaychuk came along and created Stylus, which lets you use whitespace-significant syntax and curly-brace syntax… in the same file! It’s a much more elegant solution, and I’m honestly amazed that people are still using Sass/SCSS.

    Which isn’t to say that CoffeeScript should start accepting curly braces (there would be some ambiguous cases). My point is just that CSS preprocessors aren’t really about cleaner/terser syntax the way CoffeeScript is. (The SCSS syntax is more popular than Sass Classic, probably because designers can keep using the CSS snippets they’re used to without running them through a converter.) They’re about doing things in a totally different way. CSS isn’t really a language; CSS preprocessors (with their variables and functions) are.

    Rebuttle from Nathan Smith:

    CSS *is* a language. Just not a “programming” language. I see his point though, preprocessors allow for declarative, functional programming.

    Alex MacCaw

    Well, I don’t think that’s necessarily the case. I personally enjoy Less and Stylus, as much as I enjoy CoffeeScript. However, I’m not a fan of HTML abstractions such as HAML and Jade. I evaluate each technology independently. I’m not for or against preprocessors in general.

    5 – A frequent criticism of CoffeeScript is that, if everyone uses it, we may get to a point when nobody remembers (or ever learned) how to write actual JavaScript. Is this a valid concern?

    Jeremy Ashkenas

    Nope — CoffeeScript exposes a subset of JavaScript semantics. If you learn how to write CoffeeScript, almost by definition you’ll know how to write JavaScript. Learning isn’t a zero-sum game. Learning one language or dialect doesn’t prevent you from knowing others.

    In fact, just as people who are comfortable speaking several languages find it easy to pick up more; programmers who know more than one dialect of JavaScript may be better able to learn new concepts and idioms.

    John-David Dalton

    No. As it is CoffeeScript compiles to JS so developers still have to deal with JS when debugging, for the time being, and can still use JS through the supported embedding syntax.

    - [jashkenas.github.com]
    - [https:]]
    - [https:]]

    Dave Ward

    Various tools and frameworks have been “compiling” to HTML for nearly as long as HTML has existed

    No, I don’t think that’s likely.

    Various tools and frameworks have been “compiling” to HTML for nearly as long as HTML has existed, yet knowledge of (and appreciation for) the generated HTML markup has only increased during that time. With most abstractions, you inevitably find yourself dealing with edge cases that force you to learn more deeply about the underlying technology. If anything, a simple abstraction over something more daunting often provides an appealing onramp for new developers, eventually leading them to learn more about the abstracted topic than they would otherwise have been comfortable with.

    Nathan Smith

    If CoffeeScript goes “mainstream” then more people will take an interest in the JavaScript language itself.

    I actually think (hope) maybe the opposite will be true. I think that if CoffeeScript goes “mainstream” then more people will take an interest in the JavaScript language itself. I have met quite a few designers who didn’t care about JavaScript at all, but learned how to cut and paste jQuery snippets. Before long, they’re saying “Man, I really need to learn JavaScript.”

    Just as jQuery ignited interest in JS amongst designers with its “reads like CSS” selectors, I think that perhaps CoffeeScript will be that “gateway drug” to greater JS understanding, except for Rubyists. Either way, those who already know JS have a leg-up.

    Oscar Godson

    Have you been to StackOverflow recently? Try asking a question about JavaScript. I once asked about doing some date parsing (to get the next Wed.) and someone sent me an entire jQuery plugin. It ended up being a one liner and the jQuery plugin got the most votes compared to the right one line answer. This has happened with jQuery where people just pick up jQuery and never bother to learn JavaScript. On Twitter I overheard someone asking about cookie sessions and someone suggested they use jQuery and include a $.cookie plugin. Im worried that CoffeeScript is going to end up like this where people will be including this for simple apps or when they just dont really want to understand JS.

    Ryan Florence

    You can’t write CoffeeScript without knowing JavaScript. You are debugging the JavaScript. You’re using third-party libs that are JavaScript. You can’t get away from it (the great flaw in using CoffeeScript for real world applications). So no, its not a valid argument for being against CoffeeScript.

    The fact that this argument is flawed is a solid argument to not use CoffeeScript. If you can’t break from JavaScript, what’s the point?

    Marco Chomut

    Similar arguments were made around the time that jQuery was becoming quite popular. I don’t believe that it was a valid concern then, and I don’t think it is now. Learning CoffeeScript will also require you to at some point buckle-down and learn the underlying JavaScript. This isn’t really something that you can avoid, until the day comes (if ever) that browsers parse and execute it natively. You’re going to run into the odd error or interaction that will force you to understand what it’s translating into.

    Trevor Burnham

    You shouldn’t use CoffeeScript without knowing JavaScript.

    What Ryan said.

    You shouldn’t use CoffeeScript without knowing JavaScript, although you can learn both at the same time. I mean, there must be a million people out there who are using JavaScript without really knowing JavaScript. A lot of them have other primary languages, and they’ll never really like JavaScript as much as they like Ruby, or PHP, or Java, so they only learn as much as they need to get by. That’s the sort of crowd my book is mainly aimed at. It’s like “Hey, let’s learn this hip new language, and along the way we’ll fill in the gaps in our JavaScript knowledge.”

    Alex MacCaw

    On the contrary, it’s quite the opposite. I don’t think this is a valid concern. As the others have stated, JavaScript knowledge is a requirement for writing CoffeeScript. Thus by writing CoffeeScript I think your JavaScript knowledge should, if anything, improve.

    The JavaScript generated by the CoffeeScript compiler is top notch, and by browsing through it you certainly learn a few tricks.

    However, I completely disagree that the fact you can’t break from JavaScript is an argument not to use CoffeeScript. CoffeeScript is a lightweight curated subset of the language, improving it’s syntax and only presenting the ‘good parts’. In other words, I think it’s an improvement.

    6 – One argument in favor of CoffeeScript that I rarely see put forth is that it can make you a better JavaScript developer – particularly if you’re somewhat new to the language. Similar to Rails, a huge array of best practices are baked into the compiler. Do you see benefit in that aspect? Use CoffeeScript to become a better JavaScript developer?

    Jeremy Ashkenas

    A large number of users have reported learning new tricks and patterns from reading their compiled JavaScript.

    Yes. A large number of users have reported learning new tricks and patterns from reading their compiled JavaScript.

    But having best practices built in to the compiler doesn’t mainly benefit beginners — the benefit is to long-term programmers who can take full advantage of having a concise, readable way to express their JavaScript intentions in code — without having to constantly keep best practice patterns in mind. A best practice that can be enforced and generated by a compiler is better than a best practice that has to be remembered and manually typed out every time.

    James Padolsey

    The only problem I see with taking this approach is that you’re not really learning JavaScript, and there’s so much magic going on that you won’t necessarily be appreciating the lengths that you might have to go to in order to get similar things done in JavaScript. CoffeeScript is easier for these tasks.

    It will teach you to become a better programmer, I think, but if you want to learn JavaScript, then learn it, purely.

    John-David Dalton

    I think you can take the “it makes you a better JS developer” and apply that to existing JS libs/frameworks. I learned a lot from digging into and fixing issues in libs like Dojo, jQuery, MooTools, and Prototype. The code produced by CoffeeScript is extraneously verbose and promotes micro-optimizations (which isn’t necessarily helpful and not a “best practice”).

    I would not look to CoffeeScript or its compiled JS to improve my JS skills and would rather look to mature battle hardened JS libs.

    Dave Ward

    If someone wants to become a better JavaScript developer, there are less circuitous routes. I think the main things that make JavaScript difficult for beginners are more conceptual than syntactical. CoffeeScript doesn’t change the fact that you need to understand concepts like closures, asynchronous programming, and continuation passing to write non-trivial JavaScript code.

    Nathan Smith

    I think there is some truth to this. If you are consistently checking what JavaScript is output by the CoffeeScript compiler, I think there are some insights to be gleaned. For instance, declaring all variables at the beginning of a function, to prevent variable hoisting.

    Additionally, the concept of closures is introduced automatically. This might seem frustrating at first, if just trying to create a global variable, directly inline ... (emitting something from the server-side in HTML). Due to this, CoffeeScript enforces good habits, such as explicitly attaching variables to the global object, if that is indeed what you mean to do…

    // Global variable in CoffeeScript
    window.foobar = 'something'
    
    //=====//
    
    (function() {
      // CoffeeScript output.
      window.foobar = 'something';
    }).call(this);
    
    // Versus:
    
    (function() {
      // Manual typo.
      foobar = 'something';
    })();
    

    That’s not to say such lessons cannot be learned apart from using a transpiler, but if someone new to JavaScript sought to use CoffeeScript as a way to learn about JS concepts, it might be an interesting place to start. Though, for JS beginners, reading canonical books like “JavaScript: The Good Parts” would probably be more helpful.

    Oscar Godson

    How do you learn or become better at something you’ve been shielded from? If you never have to worry about global vars leaking how do you know later when working with vanilla JS? It’s like giving someone a camera with auto-focus who’s never used a camera before and then expecting them to know how to use a film camera and adjust the focus, ISO, etc by manual means.

    Ryan Florence

    My hand-written JavaScript is pretty different from what CoffeeScript spits out.

    I think developers who aren’t very experienced in JavaScript have something to learn from the compiler’s output. Take the ?= and ||= operators, CoffeeScript shows them how to solve that problem in JavaScript.

    But they are also going to have a hard time debugging code they don’t understand. I don’t think these people can effectively use CoffeeScript.

    My hand-written JavaScript is pretty different from what CoffeeScript spits out; it’s also better looking. I think there’s more to learn by reading the source code of some of our community leaders and established JS libraries than from the compiler.

    Marco Chomut

    If, as a developer, you weren’t already exposed to the finer portions of JavaScript (either through Douglas Crockford’s JSLint or Anton Kovalyov’s JSHint), then CoffeeScript will definitely be a decent crash-course in the subject. But only if you take the chance to really understand why CS made certain decisions in the language. If you rush through it and merely try to push out a working prototype as fast as possible, you’re only harming yourself in the long run. I mentioned it before in a previous answer, but being unaware of some of the inner workings of your black boxes is very dangerous and counter-productive.

    Trevor Burnham

    Sounds like you’ve been attending my talks; I put this argument forward all the time.

    It’s interesting that you mention Rails. A lot of people learn Ruby by learning Rails. A lot of people learn JavaScript by learning jQuery. But if you learn that way, you’re not going to see the whole language. By contrast, you work through something on CoffeeScript, you’re going to see the edges. You’re going to learn all about this and prototype inheritance and typeof/instanceof and iterating through object keys and array values, and a hundred other things that JS noobs ask about on Stack Overflow every day.

    So yeah. I see learning CoffeeScript as one path to becoming a knowledgeable JavaScripter. Certainly not the only one, but one that’s fun and rewarding.

    7 – Clearly, if you’re a Ruby developer, CoffeeScript will be infinitely more appealing to you, as the syntax is fairly similar. For real world projects, where developers have deadlines, is CoffeeScript not simply a way to get the job done more quickly, with less language shuffling? What’s wrong with that, if anything?
    Jeremy Ashkenas

    Some Rubyists say that CoffeeScript looks like Ruby, Pythonistas say that CoffeeScript looks like Python, and I’ve heard Haskellers say that CoffeeScript looks like Haskell.

    I’m afraid that this is a silly question. Some Rubyists say that CoffeeScript looks like Ruby, Pythonistas say that CoffeeScript looks like Python, and I’ve heard Haskellers say that CoffeeScript looks like Haskell. The truth of the matter is that CoffeeScript semantics are just JavaScript semantics — there’s definitely no less “language shuffling” involved.

    James Padolsey

    I fear it will become acceptable to forgo the vital learning curve of JavaScript and simply rest falsely assured that the code you write in CoffeeScript works just like it would in that-other-language-you-know. For a team with a deadline I can definitely see the appeal of having a more unified development environment. Ruby and CoffeeScript are a cute match — much more so than JavaScript and Ruby. I think an understanding of JavaScript is vital, especially at this early stage (debugging can still be a nuisance).

    John-David Dalton

    Depends on their setup. CoffeeScript, like JS libs, has bugs from release to release (even some which affect cross-browser use) which can cause existing CoffeeScript code to break.

    Also, debugging still requires digging through raw JS and may not necessarily be an easy task as CoffeeScript applications become more complex.

    Unlike JS libs which can live on CDNs, the sugar around CoffeeScript has to be compiled for every JS file (unless compiled together). This can make CoffeeScript generated JS less ideal for separate third-party scripts. CoffeeScript adds yet another “something” the team will have to familiarize themselves with and become proficient in, which costs time/money and could be avoided by simply using JS (JS lib + linter).

    Dave Ward

    As someone who has spent quite a bit of time in the .NET world, I’ve seen that argument used to support drag ‘n drop development and some particularly leaky abstractions over HTML, CSS, and JavaScript. That experience has left me extremely skeptical about the long-term value of focusing on up-front productivity at the expense of understanding your development stack.

    Nathan Smith

    I wouldn’t say it’s a way to avoid “language shuffling.” Though CoffeeScript and Ruby might share some syntactic sugar, each has its own ways of dealing with things. While CS will no doubt look familiar to Ruby developers, there is still a learning curve.

    If you are under the gun on a deadline, deciding to use CoffeeScript is probably not going to help you get that work done any sooner. As with any new language, you need to set aside some time to get familiar with it, make beginner mistakes, and finally end up at a place where it becomes second nature.

    I think the danger to Ruby developers is hoping that CoffeeScript will gloss over some perceived mysterious aspects inherent to JavaScript.

    While you might end up typing less overall characters in a *.coffee file, you still need to care about what ends up in the *.js file. That comes with experience, not (only) with new syntax.

    Ryan Florence

    You write in one language, but debug in another…

    As for “less language shuffling” I assume you mean it’s like Ruby everywhere in your app–that is totally false. You write in one language, but debug in another language and neither is Ruby, so it’s actually more shuffling.

    If JavaScript’s syntax is slowing you down, then you need to learn how to use your text editor or learn how to type. There is nothing faster about CoffeeScript. Introducing CoffeeScript into your workflow actually increases “shuffling”:

    A lot of people gloss over the debugging issue but 20% of the day we write bugs, the other 80% we fix them (don’t deny it). Debugging is a big issue.

    You are debugging code you didn’t write. You have to figure out what the compiler is doing, and then figure out why the code is not doing what you wanted. Then you have to go to your CoffeeScript and figure out how to fix it in a different syntax. Usually it’s not that bad, but when using some of the fancier features of CoffeeScript it can get really “machine code” looking. One line in CoffeeScript can turn into several lines of crazy looking stuff (see here), that, again, you didn’t write, so you have to figure out why it looks that way, and then why it’s broken.

    This back-and-forth “shuffling” is a weird step that slows you down because it’s not _your_ code you’re looking at. I find I’m back to doing a lot of console.log in my code instead of using break points and watch expressions, etc., which is a total shame, and slower. But it’s the fastest way for me to “shuffle” between the JavaScript I’m debugging and the CoffeeScript I’m writing.

    Trevor Burnham

    Will CoffeeScript get the job done more quickly? Certainly some prominent JavaScript/Ruby pros have reached that conclusion for themselves.

    Rubyists are certainly easier to sell on CoffeeScript than, say, Java programmers. But the most common questions I get from Rubyists are along the lines of “Wait, why do we need a separate language? Why can’t we just compile Ruby to JS?” And I try to explain to them that, well, compiling “a = b” from Ruby into JS would require you to check whether b is a function, and if it is then run it and return its value… and compiling “x = y + 1” would require you to fire up a BigDecimal library, because all Ruby numbers are infinite-precision… and so on. Those folks have to learn that, look, when you’re in the browser, you’re on JavaScript’s turf and you’ve got to make peace with it. It could be worse. It could be statically typed.

    Will CoffeeScript get the job done more quickly? Certainly some prominent JavaScript/Ruby pros (like 37signals’ Sam Stephenson, creator of Prototype.js) have reached that conclusion for themselves. Obviously it depends on a lot of factors… sometimes what you need is a fresh perspective, and a new language can give you that.

    Alex MacCaw

    CoffeeScript isn’t inherently Rubyish.

    That’s a pretty leading question, and I don’t think that assumption is necessarily valid. CoffeeScript isn’t inherently Rubyish, just as it’s not inherently Pythonist. It borrows features from both languages but ultimately its schematics are inspired by JavaScript. The aim of CoffeeScript is not to abstract away JavaScript for developers who don’t want to learn it, such as the now defunct RJS. As such, it doesn’t help with language shuffling.

    8 – Many might argue that CoffeeScript allows for more beautiful and maintainable code. For example, creating a class in CS is considerably more intuitive and readable than what we might write with plain JavaScript.

    It’s not surprising that many will prefer the cleaner and shorter:

    class MyClass
      constructor: ->
        alert 'constructor'
    
      doSomething: ->
        alert 'doing something'
    
    c = new MyClass()
    c.doSomething()
    

    Over…

    var MyClass = (function() {
      function MyClass() {
        alert('constructor');
      }
    
      MyClass.prototype.doSomething = function() {
        alert('doing something');
      };
    
      return MyClass;
    })();
    
    c = new MyClass();
    c.doSomething();
    

    My question is: does CoffeeScript’s readability alone warrant its usage?

    Jeremy Ashkenas

    You can write undreadable code in any language.

    You can write undreadable code in any language … but yes — one of the main focuses of CoffeeScript is readability: expressing JavaScript concepts and patterns in as minimal and readable a way as we can find.

    Your “class” example is a good one. If you want to make many objects that share common methods in JavaScript — it’s not easy to accomplish. There are many ways to break the “prototype” object while you try to set up the prototype chain. You’re left either writing unreadable boilerplate every time you wish to chain two prototypes together, or using a helper library that hides basic object orientation from you. CoffeeScript’s classes are a simple way to define your constructor functions along with their prototypal properties and prototype chain. The side effect is the readability of simply writing what you mean:

        class Square extends Shape
        

    … instead of a half dozen lines of prototype manipulation code in JavaScript:

        function Square() {
          ...
        };
        var tempConstructor = function(){
          this.constructor = Square;
        };
        tempConstructor.prototype = Shape.prototype;
        Square.prototype = new tempConstructor;
    
    James Padolsey

    Naturally, because I’ve worked more with JavaScript, it’s more readable to me than CoffeeScript.

    That’s not the JavaScript I would write, but I see your point. CoffeeScript can have great readability and most of the CS code I’ve seen is both terse and expressive, but I don’t think this necessarily translates to “more intuitive”. Naturally, because I’ve worked more with JavaScript, it’s more readable to me than CoffeeScript. Again, this seems to be about taste, and is very much influenced by prior language exposure. A Ruby person would probably understand the CoffeeScript code sooner than the JavaScript, but it would be the opposite for, say, a PHP or Java developer, where keywords play a central role in class and function definition. In CoffeeScript you have very minimal and expressive operators which aren’t always as clear.

    John-David Dalton

    No. Developers have different opinions on what they consider readable. CoffeeScript is similar to JS libs in that they all add syntactic sugar and each developer/team has their own preference (MooTools, jQuery, Dojo, CoffeeScript, CoffeeScript+libs, and on and on).

    Dave Ward

    If you want syntactic sugar around structuring your code, there are JavaScript libraries to help with that without requiring the obtrusive compilation step.

    If you want syntactic sugar around structuring your code, there are JavaScript libraries to help with that without requiring the obtrusive compilation step.

    Considering this question in the overall context of the others, the developer who doesn’t yet understand JavaScript needs more than a somewhat similar analog to their server-side language’s implementation of classical inheritance. I believe putting the “class” pseudo-keyword in front of a developer coming from a typical object oriented language may even be harmful in the long run.

    Nathan Smith

    “Readability” is subjective. I think you’ve touched on something with the “class” example. For developers coming from a classical programming background (C#, Ruby, etc), CoffeeScript probably feels like a breath of fresh air. To me, having learned JavaScript as my first “real” programming language, thinking in terms of classes feels foreign.

    In my opinion, the perfect blend of CS and JS would be var added automagically, and not needing to write unnecessary parenthesis or curly braces. However, I could do without the automatic return at the end of each function.

    I am also not a fan of how CS hijacks the for in to become an i++ loop — requiring instead that you write for of to be able to iterate through objects (when *.length isn’t present).

    Oscar Godson

    This might be because JavaScript isn’t a class based language. It’s prototypal, and that scares people who aren’t used to it. PHP or Rails developers come to JS, and don’t know how to use it properly. So they come up with hacks to make it work and even look like other languages. This isn’t the answer. If you do need to use classes, you can write a mini-lib and make it clean like:

    var Ninja = Person.extend({
      init: function(){
        this._super( false );
      },
      dance: function(){
        // Call the inherited version of dance()
        return this._super();
      },
      swingSword: function(){
        return true;
      }});
    
    // via [ejohn.org]   

    The only real difference is no parenthesis. I actually like Brendan Eich’s idea of paran-free JS, but I like the idea of it being baked in and not completely changing the language.

    Ryan Florence

    I review code on gerrit from my team every day. Some JavaScript, some CoffeeScript. I have as hard a time following what they’re trying to do in one syntax vs. the other. It’s perhaps more verbally readable at times, but that has yet to make it more understandable for me. Take this line for example:

    scores = (student["assignment_#{@assignment.id}"].score for own idx, student of @gradebook.students when student["assignment_#{@assignment.id}"]?.score?)
    

    That’s 160 columns of verbally readable code straight out of our app but I have no idea what it’s doing. The fun part is that you end up debugging things like this.

    There are some aspects to CoffeeScript that are less readable.

    The fat arrow => binds the context to the function, which sounds great, but it encourages deep nesting, an anti-pattern.

    Couple that with significant whitespace over several lines of code and you’ve got a mess. Unstructured code with callbacks and lots of if else going on is extremely hard to follow: there’s no closing bracket for me to place my cursor over and see where I’m at with my text editor. Some

  • Permalink for 'Create a Scalable Widget Using YUI3: Part 1'

    Create a Scalable Widget Using YUI3: Part 1

    Posted: December 13th, 2011, 2:30pm MST by Dan Wellman

    In this tutorial, we’re going to look at how easy it is to create scalable, robust and portable widgets using the latest version of the Yahoo User Interface library. YUI3 provides a Widget class for us to extend in order to create widgets in a consistent way that leverage the power of the library.

    The widget that we’ll create today is a Twitter search client that will query Twitter’s search API and consume the JSON response in order to display tweets that contain the configured search term. We can also add additional functionality such as allowing the visitor to choose another term and do a new search, and viewing paged results. Join me after the jump!

    Getting Started

    All required YUI modules will be retrieved dynamically when the page running our widget is loade

    We’ll need the usual css, img and js folders created within a project folder for us to store our various resources in. The images our widget will use can be found in the code download. We don’t need to worry about downloading a copy of the YUI library itself as all required YUI modules will be retrieved dynamically when the page running our widget is loaded (we’ll look at this in more detail later).

    The Widget Wrapper

    Create a new script file and add to it the following code:

    YUI.add("tweet-search", function (Y) {
    
    }, "0.0.1", { requires: ["widget", "substitute", "jsonp"] });

    This is the outer wrapper for our widget; all of the code we write will reside within the function passed as the second argument to YUI’s add() method. The add() method of the YUI object allows us to add a new module to the library, which could be a simple function or class, a widget, an extension or a plugin.

    • The first argument we provide is the name of our widget. This name is used in the use() method when implementing the widget.
    • The second argument is an anonymous function that is used to define the widget’s class. The argument accepted by this function is the instance of YUI that the widget is attached to.
    • The third argument is used to specify the version number of the widget.
    • The fourth and final argument is an object that we can use to supply additional configuration for the widget.

    In this example, we use the requires property to specify an array of other YUI components that are required for our widget to function. There are other properties that can be used here, but they aren’t required for this example.

    As you can see, one of the required components is the Widget component. When creating a custom widget the Widget component of the library should be extended to make use of the powerful constructs that Widget sets up. We also use the Substitute component for doing some simple string substitution when building the required HTML elements, and the JSONP component in order to interact with Twitter’s search API.

    Top Level Variables, the Constructor and Namespacing

    Now we can begin adding some of the variables our widget will require, as well as adding the class constructor and namespace. Add the following code within the anonymous function:

    var Node = Y.Node,
        getClassName = Y.ClassNameManager.getClassName,
        i, j,
        baseClasses = ["_CLASS", "title", "loader", "viewer", "tweet", "ui", "label", "input", "button", "error"],
        templates = ["_TEMPLATE", "&lt;hgroup class={titleclass}>&lt;h1>{title}&lt;/h1>&lt;h2>{subtitle}&lt;span>{term}&lt;/span>&lt;/h2>&lt;/hgroup>", "&lt;div class={loaderclass}>loading...&lt;/div>", "&lt;div class={viewerclass}>&lt;/div>", "&lt;article>&lt;a href={userurl} title={username}>&lt;img src={avatar} alt={username} />&lt;h1>{username}&lt;/h1>&lt;/a>&lt;p>{text}&lt;/p>&lt;/article>", "&lt;div class={uiclass}>&lt;/div>", "&lt;label class={labelclass}>{labeltext}&lt;/label>", "&lt;input class={inputclass} />", "&lt;button class={buttonclass}>{buttontext}&lt;/button>", "&lt;p class={errorclass}>{message}&lt;/p>"];
    
    function TweetSearch(config) {
        TweetSearch.superclass.constructor.apply(this, arguments);
    }
    
    Y.namespace("DW").TweetSearch = TweetSearch;

    The name of our widget has the first letter of its name capitalized, as is the convention for naming constructors.

    First up, we cache references to the Y.Node component and the Y.ClassNameManager.getClassName() method as we’ll be using these frequently. We also define a couple of variables for use in the for loop, and create two new arrays; the first containing a series of strings that will form part of the class names added to the HTML elements our widget will create, and the second containing the HTML templates, also in string format, that will be used to create the elements themselves.

    Next we add the constructor function for our widget; this is the function that developers implementing our widget will call. The function can accept a single argument which will take the form of an object that sets configuration attributes exposed by our widget. The name of our widget has the first letter of its name capitalized, as is the convention for naming constructors. Within this function our widget’s class is initialised by using the apply() method of the superclass's (Widget) constructor. The value of this is set to our widget instance.

    We can also create a namespace for our widget using YUI’s namespace() method; this isn’t mandatory but it is a very good practice to run code within a namespace in order to minimize the possibility of naming collisions when code is used in the wild. The namespace() method accepts a string which represents the namespace, to which is attached the widget name as a property and the widget as the value.

    I’ve set the namespace to equal my initials but this can be anything you require; you may already have a namespace that all of your web apps reside in, or it could be the name of your company, the name of your client, or anything else that makes sense. This widget will be accessible via Y.DW.TweetSearch

    Static Properties

    Next, we can define the static constants required when extending the Widget class. Add the following code directly after the namespace() method:

    TweetSearch.NAME = "tweetsearch";
    
    for (i = 1, j = baseClasses.length; i < j; i++) {
        var current = baseClasses[i].toUpperCase(),
            prop1 = current + baseClasses[0],
            prop2 = current + templates[0];
    
        TweetSearch[prop1] = getClassName(TweetSearch.NAME, baseClasses[i]);
        TweetSearch[prop2] = templates[i];
    }

    First, we set the NAME property of our widget; the all-caps naming convention here signifies a value that will be constant throughout the life-cycle of our widget instance. The name we set is used by the widget as a prefix when firing events and creating class names for HTML elements.

    Next is the for loop we use to add the required class names and mark-up templates to our widget. We initialize the i and j variables that we declare at the top of the function; the i variable that is used as the counter is initially set to 1 instead of 0 as would usually be the case (you’ll see why in just a moment) and the j variable is set to the length of our baseClasses array (the baseClasses and templates arrays are both the same length as every element we create is given a class name. This may not always be the case).

    Within the loop we cache a reference to the current item from the baseClasses array and in upper case, and then create two new strings called prop1 and prop2. These strings consist of the variable we just created and the first item in our baseClasses array, so on the first iteration for example, this string will equal TITLE_CLASS for prop1 and TITLE_TEMPLATE for prop2.

    We then add these new properties to our widget instance; the first property is set to the result of calling the getClassName() method (remember, we’re using the cached short-cut we created earlier which points to Y.ClassNameManager.getClassName). We pass in the name of our widget as the first argument to this method, and the current item from the baseClasses array. This will result in generated class names such as yui3-tweetsearch-title, available fom the TweetSearch.TITLE_CLASS property for example.

    The second property we add is the current item from the templates array. Continuing with the title example this gives us a property name of TweetSearch.TITLE_TEMPLATE with a value of <hgroup class={titleclass}><h1>{title}</h1><h2>{subtitle} <span>{term}</span></h2></hgroup>. The purpose of the for loop is simply so that we don’t have to attach all of the classes and templates to our instance manually.

    Configurable Attributes with Sensible Defaults

    Now we can define the configurable attributes that our widget will have, which will enable developers implementing the widget to enable or disable different features. Add the following code directly after the for loop:

    TweetSearch.ATTRS = {
        term: {
            value: "yui3",
            validator: "_validateTerm"
        },
        numberOfTweets: {
            value: 5
        },
        baseURL: {
            value: " [search.twitter.com]     },
        tweets: {
            value: null
        },
        showTitle: {
            value: true
        },
        showUI: {
            value: true
        },
    
        strings: {
            value: {
                title: "Twitter Search Widget",
                subTitle: "Showing results for:",
                label: "Search Term",
                button: "Search",
    		errorMsg: "I'm sorry, that search term did not return any results. Please try a different term"
            }
        }
    };

    The YUI library adds a consistent way to add attributes to any class or module.

    The ATTRS constant is used to store the configurable attributes that the implementing developer can set when creating an instance of the widget. The YUI library adds a consistent way to add attributes to any class or module, and this mechanism is automatically available when extending Widget.

    Instead of setting the value of each attribute to a simple native value like a sting or a Boolean, an object is used. The default for each attribute is set using the value property of this object. In the first attribute, we also make use of the validator property, which allows us to specify a function that will be automatically called whenever the value is updated. This enables us to check that the value is in a particular format, or matches other custom criteria. There are also a range of other properties we can set for each attribute including; custom get and set methods, whether the attribute is read-only, and more.

    The attributes used by our widget include the search term, the number of tweets to display, the baseURL of the request sent to Twitter, whether to show a title for the widget and whether to show the search UI. There are a number of other attributes our widget will automatically get, and which we can use. We’ll look at these in more detail later on in the tutorial.

    The final attribute we define is the strings attribute, which is available to all modules that subclass Widget. The value of this attribute is also an object and within this we add all of the text strings that our widget will display. Using an attribute to define any words that the widget needs to display in this way makes our widget super easy to internationalize; implementing developers need only to override the strings attribute with their own collection of strings in whichever language they choose.

    Built-in Support for Progressive Enhancement

    The Widget superclass furnishes us with the HTML_PARSER static property that can retrieve values from any HTML elements that are present within the widget’s container and use these values as attributes, which makes it incredibly easy for us to create widgets that transform underlying mark-up into something more functional and/or pretty.

    We don’t really need to worry about this for our widget; if JavaScript is disabled, no AJAX request will be made to Twitter’s search API and there will be no data to display in any case. However, they give implementing developers more ways of instantiating the widget and configuring attributes, we can make the provision that if a text <input> is present within the widget’s container, the value of the field will be used as the search term instead of the default attribute value. In order to retrieve this value we can make use of the HTML_PARSER; add the following code directly after the ATTRS definition:

    TweetSearch.HTML_PARSER = {
        term: function (srcNode) {
            var input = srcNode.one("input");
    
            if (input) {
                var val = input.get("value");
                    input.remove();
                }
    
                return val;
            }
        };

    The HTML_PARSER property is an object literal where each property within this object maps directly to an attribute. The only attribute that we wish to add progressive-enhancement support for is the term attribute, the value of which is set to a functional that will automatically be called when our widget is initialized.

    This function receives a single argument which is a referece to the srcNode attribute. This is one of the built-in attributes that all widgets automatically get access to and refers explicitly to the element that was passed into the constructor for our widget. This element becomes the content box for the widget.

    The first thing we do is try to select an <input> element from the srcNode using YUI’s one() method, which selects a single matching element from the DOM. If an element is retrieved, we store its value in a variable called val, and then remove the element from the page (we’ll create an alternative <input> element for when the search UI is enabled later). We then return val. If val is not set, i.e. if there wasn’t an <input> in the srcNode, underfined will be returned, and the term attribute will stay set to its configured value. If val does contain a value, it will become the value for the term attribute.

    Extending the Widget Class

    Before we end this part of the tutorial, we’ll take a look at the method we use to extend the Widget class with the functionality specific to our widget. This method will form the bulk of our widget. Directly after the HTML_PARSER add the following:

    TweetSearch = Y.extend(TweetSearch, Y.Widget, {
    
    });

    The YUI extend() method takes three arguments:

    • The first is the object to extend, which in this example is our widget’s class.
    • The second argument is the object we are extending, in this case the Widget class.
    • The third argument is an object containing prototype methods to add or override to our widget. The object passed as the third argument will be the wrapper for the remainder of our code, which we’ll come to in the next part of this tutorial.

    Save this file in the js folder as tweet-search.js.

    Summary

    In this part of the tutorial we setup some of the required scaffolding for our new widget. Although the widget won’t actually do anything at this stage, it can still be initialised and we can see some of the container that is automatically added by the YUI library, and look in the DOM tab of Firebug to see the attributes it has inherited.

    After defining some top-level variables, we first saw how to define the constructor function for our widget so that the widget can be initialized by the library, as well as seeing how easy it is to namespace our widget. We then looked at the static constants that are inherited from the underlying Widget class that we are extending. These included the NAME of the widget, the _CLASS and _TEMPLATE collections and the ATTRS object, the latter of which allowed us to set the attributes that an implementing developer can override if they so wish.

    We also looked momentarily at the extend() method which is used to add the prototype methods to our widget’s class in order to implement that custom functionality it provides. This custom functionality will be the subject of the next part of this tutorial.

    Stay tuned and thank you so much for reading!


  • Permalink for 'Build an Admin Panel with the Fuel PHP Framework'

    Build an Admin Panel with the Fuel PHP Framework

    Posted: December 12th, 2011, 2:30pm MST by Philip Sturgeon

    In the first part of this series, we took a look at the basics of the FuelPHP framework. In this second-part, we’ll be stepping it up a gear and move onto some more advanced topics! We’ll be creating an admin panel for our application, cover the common uses of the ORM and use the Authentication package to restrict access.

    Join me after the break to get started!

    Introduction

    Since the first article Fuel has been renamed to FuelPHP. Also unlike the first article which was based on v1.0.1 this article requires v1.1.0 so a few little things are different. All the theory you have learnt from the first article is still accurate and not much has changed so this should be easy.

    Step 1 - Set Up Oil

    If you have not already installed the command-line utility oil and are lucky enough to be running on Linux, Mac, Solaris, etc then do so with the following command:

    $ curl get.fuelphp.com/oil | sh
    
    Step 2 - Create a New App

    The oil command will help you create new projects with a few key-strokes and alias php oil when inside your FuelPHP applications:

    $ oil create Sites/blog
    $ cd Sites/blog
    

    This will set up a blog application for us and assuming you have Apache or some other web server running on your “Sites” folder you should be able to load the following URL and see the welcome page.

    alt text

    Now that FuelPHP is alive and your web server is clearly working, we can start configuring our app.

    Step 3 - Configuring Your App

    Open up your favourite editor and we’ll start by setting up a database connection and configure the application. This is almost identical to v1.0.x, so create a database and set up your SQL users however you normally do. When it comes to database config there are two differences:

    • PDO is now the default driver
    • FuelPHP v1.1 has environment-based config folders now.

    These changes are pretty simple, but you can swap back to using the native MySQL driver if you like. PDO is more useful for developers as it means that your application will work with just about any database engine not just the few that had specific FuelPHP drivers built for them. That means this could just as easily be SQLite or PostgreSQL.

    Just open up fuel/app/config/development/db.php and modify your config, where dbname=blog is whatever your database is called and your own username and password for the database server:

    return array(
      'default' => array(
     	 'connection'  => array(
     		 'dsn'  	=> 'mysql:host=localhost;dbname=blog',
     		 'username' => 'root',
     		 'password' => 'password',
     	 ),
      ),
    );
    

    Next you will just need to open fuel/app/config/config.php and enable the auth and orm packages as suggested in the first post.

    /**************************************************************************/
    /* Always Load                    */
    /**************************************************************************/
    'always_load'  => array(
    
    	'packages'  => array(
    		'auth',
    'orm',
    	),
    

    In this config file, we need to make one small change to the whitelisted_classes array which will allow us to pass validation objects to the view:

    	'whitelisted_classes' => array(
    		'Fuel\\Core\\Response',
    		'Fuel\\Core\\View',
    		'Fuel\\Core\\ViewModel',
    		'Fuel\Core\Validation',
    		'Closure',
    	),
    
    Setting up Groups

    The auth package included with FuelPHP is driver based and by default we are using “SimpleAuth” which is the only driver included in the package. When you are more experienced with FuelPHP, you can start to create custom drivers to integrate with other users’ systems – such as third-party forums, content management systems, etc.

    To enable groups for SimpleAuth, we simply open up fuel/packages/auth/config/simpleauth.php and set groups to the following:

    return array(
      'groups' => array(
     	  -1 => array('name' => 'Banned', 'roles' => array('banned')),
     	  0	=> array('name' => 'Guests', 'roles' => array()),
     	  1	=> array('name' => 'Users', 'roles' => array('user')),
     	  50 => array('name' => 'Moderators', 'roles' => array('user', 'moderator')),
     	  100  => array('name' => 'Administrators', 'roles' => array('user', 'moderator', 'admin')),
      ),
    );
    

    These could, of course, be anything, but are pretty standard for most apps and will work for this tutorial.

    Step 4 - Creating Users

    As we are building an admin panel, we need to create the users table and then populate it with a user record who will be the first administrator. We could use something like phpMyAdmin or a GUI like Navicat, but it’s better to do things via Oil so we stay within our codebase. This means password hashing is salted correctly with whatever driver is being used – and is how we’ll be doing it:

    $ oil generate model users username:varchar[50] password:string group:int email:string last_login:int login_hash:string profile_fields:text
      Creating model: /Users/phil/Sites/blog/fuel/app/classes/model/user.php
      Creating migration: /Users/phil/Sites/blog/fuel/app/migrations/001_create_users.php
    $ oil refine migrate
    

    This creates a user model for us and creates another migration that will build our user table when the oil refine migrate task is run. Next we have to create an Administrator user, which, again, we could do via a GUI but where’s the fun in that?

    $ oil console
    Fuel 1.1-rc1 - PHP 5.3.6 (cli) (Sep  8 2011 19:31:33) [Darwin]
    >>> Auth::create_user('admin', 'password', 'phil@example.com', 100);
    1
    -- Ctrl + C to exit
    

    We’ve used the Oil Console to write code in real-time and get a response. Auth::create_user() was passed a username, password, email address and the group_id for admins, which for now we’ll just use 100 – which we set in the config. The 1 is a response from the code, which means user_id has a value of 1.

    Step 5 - Code Generation

    Generators are a great way to build a bunch of code from scratch and getting a running start.

    As explained in the first article we can use scaffolding to build large chunks of an application quickly. This is done through the oil command and is all very optional, but it is a great way to build a bunch of code from scratch. Some people look at code generation as “tools for people who don’t know how to code” or think its some kind of black magic, but if you are new to a framework and do not want to have to learn how to put everything together then having a system make code for you is not such a bad thing.

    FuelPHP v1.1 takes the code generation one small step further. Instead of just creating scaffolding (unprotected CRUD) you can now generate Admin code. This works in exactly the same way but implements a simple admin template, admin controller, etc and uses the auth package to lock down your generated code. Taking advantage of the Twitter Bootstrap, this all looks good enough to use and with only a bit of tweaking you’ll have an app that you can ship.

    This is done via the command line using the oil command. We’ll generate some code then walk through it.

    $ oil generate admin posts title:string slug:string summary:text body:text user_id:int
    	Creating controller: /Users/phil/Sites/blog/fuel/app/classes/controller/base.php
    	Creating controller: /Users/phil/Sites/blog/fuel/app/classes/controller/admin.php
    	Creating views: /Users/phil/Sites/blog/fuel/app/views/admin/template.php
    	Creating views: /Users/phil/Sites/blog/fuel/app/views/admin/dashboard.php
    	Creating views: /Users/phil/Sites/blog/fuel/app/views/admin/login.php
    	Creating migration: /Users/phil/Sites/blog/fuel/app/migrations/002_create_posts.php
    	Creating model: /Users/phil/Sites/blog/fuel/app/classes/model/post.php
    	Creating controller: /Users/phil/Sites/blog/fuel/app/classes/controller/admin/posts.php
    	Creating view: /Users/phil/Sites/blog/fuel/app/views/admin/posts/index.php
    	Creating view: /Users/phil/Sites/blog/fuel/app/views/admin/posts/view.php
    	Creating view: /Users/phil/Sites/blog/fuel/app/views/admin/posts/create.php
    	Creating view: /Users/phil/Sites/blog/fuel/app/views/admin/posts/edit.php
    	Creating view: /Users/phil/Sites/blog/fuel/app/views/admin/posts/_form.php
    	Creating view: /Users/phil/Sites/blog/fuel/app/views/template.php
    

    This is quite a bit of code because it is the first time it has been run. FuelPHP will set up a few basic templates and files, then build the MVC components for the posts section. Remember, this is just like writing the code yourself, but quicker. You can take a look at this output by going to /blog/public/admin/posts:

    Posts - Admin Generated code Understanding Controllers

    We’ve added a Controller_Base which will contain logic for your entire app, so every controller can extend from this. The file simply contains:

    abstract class Controller_Base extends Controller_Template {
    
    	public function before()
    	{
    		parent::before();
    
    		// Assign current_user to the instance so controllers can use it
    		$this->current_user = Auth::check() ? Model_User::find(Arr::get(Auth::get_user_id(), 1)) : null;
    
    		// Set a global variable so views can use it
    		View::set_global('current_user', $this->current_user);
    	}
    
    }
    

    By extending Controller_Template, all views will be wrapped by a template automatically. Then in the before() function we do a little bit of logic to get the current user and make it available as $this->current_user in controllers and $current_user in views.

    Another controller will be built called Controller_Admin which extends Controller_Base, so as well as having the current user being built we can check to see if a user is actually an admin:

    abstract class Controller_Admin extends Controller_Base {
    
    	public $template = 'admin/template';
    
    	public function before()
    	{
    		parent::before();
    
    		if ( ! Auth::member(100) and Request::active()->action != 'login')
    		{
    			Response::redirect('admin/login');
    		}
    	}
    
    	// ....
    
    }
    

    You’ll notice that this controller sets a custom template so instead of looking for fuel/app/views/template.php, it will look for fuel/app/views/admin/template.php. Then if a user does not match member(100) – the admin group ID set earlier – they will be sent off the the login page.

    Extending Controllers

    One very handy feature that FuelPHP has is to allow you to extend other controllers. Normally they are just loaded directly by the Request class after being routed to by the URL, but sometimes it is useful to extend controllers to share logic or methods. In this case, we are already checking permissions in Controller_Admin so we can extend that controller to reuse this logic.

    Controller_Admin_Posts extends Controller_Admin. This means it contains the same before() check and therefore is protected in the same way as any other controller in your admin panel.

    Now What?

    Code generation is basically just the first step in working on an application. We still need to tweak our forms and create a frontend. For example, if you go to create or edit a post it will show the user_id field as a text box.

    Step 6 - Updating the CRUD Forms

    We’re going to want to modify our action_create() method in fuel/app/classes/admin/posts.php so we have a list of users available. To do this we can replace the method with this code:

    public function action_create($id = null)
    {
    	$view = View::forge('admin/posts/create');
    
    	if (Input::method() == 'POST')
    	{
    		$post = Model_Post::forge(array(
    			'title' => Input::post('title'),
    			'slug' => Inflector::friendly_title(Input::post('title'), '-', true),
    			'summary' => Input::post('summary'),
    			'body' => Input::post('body'),
    			'user_id' => Input::post('user_id'),
    		));
    
    		if ($post and $post->save())
    		{
    			Session::set_flash('success', 'Added post #'.$post->id.'.');
    			Response::redirect('admin/posts');
    		}
    
    		else
    		{
    			Session::set_flash('error', 'Could not save post.');
    		}
    	}
    
    	// Set some data
    	$view->set_global('users', Arr::assoc_to_keyval(Model_User::find('all'), 'id', 'username'));
    
    	$this->template->title = "Create Post";
    	$this->template->content = $view;
    }
    

    This is the same as the code before with two changes:

    $view = View::forge('admin/posts/create');
    

    This creates a new View object. We can assign properties to this view by setting them as properties, so our users data can be passed easily and would normally work a little like this:

    $view->users = array(1 => "User 1", 2 => "User 2");
    

    Now we make a similar update to action_edit():

    public function action_edit($id = null)
    {
    	$view = View::forge('admin/posts/edit');
    
    	$post = Model_Post::find($id);
    
    	if (Input::method() == 'POST')
    	{
    		$post->title = Input::post('title');
    		$post->slug = Inflector::friendly_title(Input::post('title'), '-', true);
    		$post->summary = Input::post('summary');
    		$post->body = Input::post('body');
    		$post->user_id = Input::post('user_id');
    
    		if ($post->save())
    		{
    			Session::set_flash('success', 'Updated post #' . $id);
    			Response::redirect('admin/posts');
    		}
    
    		else
    		{
    			Session::set_flash('error', 'Could not update post #' . $id);
    		}
    	}
    
    	else
    	{
    		$this->template->set_global('post', $post, false);
    	}
    
    	// Set some data
    	$view->set_global('users', Arr::assoc_to_keyval(Model_User::find('all'), 'id', 'username'));
    
    	$this->template->title = "Edit Post";
    	$this->template->content = $view;
    }
    

    However, because the create.php and edit.php views share a theme partial _form.php, and properties only set variables to that one specific view we need to use the View::set_global() method:

    $view->set\_global('users', Arr::assoc_to_keyval(Model\_User::find('all'), 'id', 'username'));
    

    This uses the Model_User object to get all of our users, then flattens them to an associative array for our form.

    The HTML now needs to change, so delete the div wrapping “slug” – we’ll do that ourselves and change the user_id field from being a input box to a select box:

    <div class="clearfix">
    	<?php echo Form::label('User', 'user_id'); ?>
    
    	<div class="input">
    		<?php echo Form::select('user_id', Input::post('user_id', isset($post) ? $post->user_id : $current_user->id), $users, array('class' => 'span6')); ?>
    
    	</div>
    </div>
    
    User dropdown form

    This will set the box to show all users and default to the current logged in user if none are provided. That is the only tweak we need to make at this point, so let’s make a frontend!

    The Frontend

    Creating a basic blog frontend is really simple so won’t worry about using code generation.

    Create a new controller fuel/app/classes/controller/blog.php:

    class Controller_Blog extends Controller_Base
    {
    	public function action_index()
    	{
    		$view = View::forge('blog/index');
    
    		$view->posts = Model_Post::find('all');
    
    		$this->template->title = 'My Blog about Stuff';
    		$this->template->content = $view;
    	}
    }
    

    And the fuel/app/views/blog/index.php view file:

    <h2>Recent Posts</h2>
    
    <?php foreach ($posts as $post): ?>
    
    	<h3><?php echo Html::anchor('blog/view/'.$post->slug, $post->title) ?></h3>
    
    	<p><?php echo $post->summary ?></p>
    
    <?php endforeach; ?>
    

    This is just a simple loop through the $posts array which contains all your articles.

    Comment form

    A foreach loop, a hyperlink and a summary is all we need on this view file and we’ll make another view file to actually see the post. We’ll call this controller method action_view() and make a view file called view.php:

    <h2><?php echo $post->title ?></h2>
    
    <p><strong>Posted: </strong><?php echo date('nS F, Y', $post->created_at) ?> (<?php echo Date::time_ago($post->created_at)?>)</p>
    
    <p><?php echo nl2br($post->body) ?></p>
    

    This is the method for the blog controller:

    public function action_view($slug)
    {
    	$post = Model_Post::find_by_slug($slug);
    
    	$this->template->title = $post->title;
    	$this->template->content = View::forge('blog/view', array(
    		'post' => $post,
    	));
    }
    

    The find_by_slug() method is a “magic method” that will build WHERE slug = "foo" in your query and return a single Model_Post instance with that data.

    Comment form

    Now people can look at your – horribly unstyled – website and see a basic blog, and you have an admin interface to manage it!

    Step 7 - Using the ORM

    So far we’ve been using the ORM for our models to do basic CRUD but we’ve not yet seen anything to do with relationships. The ORM makes this incredibly easy as, well it stands for “Object Relational Mapping” for a reason. To set up relationships all we need to do is modify our models a little bit to explain how the ORM should relate the data.

    A post is created by one user, so we say it “belongs to” a user. In Model_Post we can add:

    protected static $_belongs_to = array('user');
    

    The user can post multiple blogs, so we add this line:

    protected static $_has_many = array('posts');
    

    A quick way to test this works is by firing up the oil console:

    Fuel 1.1-rc2 - PHP 5.3.6 (cli) (Sep  8 2011 19:31:33) [Darwin]
    >>> $post = Model_Post::find('first');
    >>> $post->user->username
    admin
    -- Ctrl + C to exit
    

    Nice, the relationships work!

    Now in the view we can work with $post->user and output their name, so let’s change fuel/app/views/blog/view.php:

    <h2><?php echo $post->title ?></h2>
    
    <p>
    	<strong>Posted: </strong><?php echo date('nS F, Y', $post->created_at) ?> (<?php echo Date::time_ago($post->created_at)?>)
    	by <?php echo $post->user->username ?>
    </p>
    
    <p><?php echo nl2br($post->body) ?></p>
    

    Doing things this way is called lazy loading. What basically happens is that when you ask for $post->user the ORM returns the user object based on the contents of the user_id field. This means to get the post and the first user is two queries, getting the second will be a third, etc and so it can end up being very slow with all these additional queries.

    To improve performance you can switch from lazy loading to eager loading which basically tells the ORM you are going to be joining users on so it should do it as part of the first query. This can make for one larger query but the ORM will slice it up nicely for you and you wont notice the difference.

    $post = Model_Post::find_by_slug($slug, array('related' => array('user')));
    

    If you look at the query the ORM produces, it will be something like this:

    SELECT <code>t0</code>.<code>id</code> AS <code>t0_c0</code>, <code>t0</code>.<code>title</code> AS <code>t0_c1</code>, <code>t0</code>.<code>slug</code> AS <code>t0_c2</code>, <code>t0</code>.<code>summary</code> AS <code>t0_c3</code>, <code>t0</code>.<code>body</code> AS <code>t0_c4</code>, <code>t0</code>.<code>user_id</code> AS <code>t0_c5</code>, <code>t0</code>.<code>created_at</code> AS <code>t0_c6</code>, <code>t0</code>.<code>updated_at</code> AS <code>t0_c7</code>, <code>t1</code>.<code>id</code> AS <code>t1_c0</code>, <code>t1</code>.<code>username</code> AS <code>t1_c1</code>, <code>t1</code>.<code>password</code> AS <code>t1_c2</code>, <code>t1</code>.<code>group</code> AS <code>t1_c3</code>, <code>t1</code>.<code>email</code> AS <code>t1_c4</code>, <code>t1</code>.<code>last_login</code> AS <code>t1_c5</code>, <code>t1</code>.<code>login_hash</code> AS <code>t1_c6</code>, <code>t1</code>.<code>profile_fields</code> AS <code>t1_c7</code>, <code>t1</code>.<code>created_at</code> AS <code>t1_c8</code>, <code>t1</code>.<code>updated_at</code> AS <code>t1_c9</code> FROM (SELECT <code>t0</code>.<code>id</code>, <code>t0</code>.<code>title</code>, <code>t0</code>.<code>slug</code>, <code>t0</code>.<code>summary</code>, <code>t0</code>.<code>body</code>, <code>t0</code>.<code>user_id</code>, <code>t0</code>.<code>created_at</code>, <code>t0</code>.<code>updated_at</code> FROM <code>posts</code> AS <code>t0</code> ORDER BY <code>t0</code>.<code>id</code> ASC LIMIT 1) AS <code>t0</code> LEFT JOIN <code>users</code> AS <code>t1</code> ON (<code>t0</code>.<code>user_id</code> = <code>t1</code>.<code>id</code>) WHERE (<code>t0</code>.<code>slug</code> = 'women-love-guys-who-use-fuelphp') ORDER BY <code>t0</code>.<code>id</code> ASC
    

    At first this might look insane, but the ORM knows exactly what is going on. Using this approach in the past I have reduced a application from running 300+ queries on a busy page (very slow) down to about 2 (very fast).

    Step 8 - Adding Comments

    Lots of “make a blog” tutorials stop before they get to comments which I think is a major under-sight. Every blog needs comments and we want to add them quickly so we can go and do something more fun, so we can use code generation to build the admin interface:

    $ oil generate admin comments name:string email:string website:string message:text post_id:int
    	Creating migration: /Users/phil/Sites/blog/fuel/app/migrations/003_create_comments.php
    	Creating model: /Users/phil/Sites/blog/fuel/app/classes/model/comment.php
    	Creating controller: /Users/phil/Sites/blog/fuel/app/classes/controller/admin/comments.php
    	Creating view: /Users/phil/Sites/blog/fuel/app/views/admin/comments/index.php
    	Creating view: /Users/phil/Sites/blog/fuel/app/views/admin/comments/view.php
    	Creating view: /Users/phil/Sites/blog/fuel/app/views/admin/comments/create.php
    	Creating view: /Users/phil/Sites/blog/fuel/app/views/admin/comments/edit.php
    	Creating view: /Users/phil/Sites/blog/fuel/app/views/admin/comments/_form.php
    
    $ oil refine migrate
    Migrated app:default to latest version: 3.
    

    Comments will need some similar tweaks as Post did so make those then we set up the relationships.

    Model_User

    protected static $_has_many = array('posts', 'comments');
    protected static $_belongs_to = array('user');
    

    Model_Post

    protected static $_belongs_to = array('user');
    protected static $_has_many = array('comments');
    

    Model_Comment

    protected static $_belongs_to = array('post', 'user');
    

    Add a comment through the interface the cheating way, by going to http://localhost/blog/public/admin/comments/create and entering one

    Comment admin

    Now we can test the relationship in the console again:

    Fuel 1.1-rc2 - PHP 5.3.6 (cli) (Sep  8 2011 19:31:33) [Darwin]
    >>> Model_Post::find(1)->comments
    array (
      1 =>
      Model_Comment::__set_state(array(
       '_is_new' => false,
       '_frozen' => false,
       '_data' =>
      array (
      'id' => '1',
      'name' => 'Phil Sturgeon',
      'email' => 'email@philsturgeon.co.uk',
      'website' => 'http://philsturgeon.co.uk/',
      'message' => 'This is an epic article.',
      'post_id' => '1',
      'created_at' => '1322931744',
      'updated_at' => '1322931744',
      ),
       '_original' =>
      array (
      'id' => '1',
      'name' => 'Phil Sturgeon',
      'email' => 'email@philsturgeon.co.uk',
      'website' => 'http://philsturgeon.co.uk/',
      'message' => 'This is an epic article.',
      'post_id' => '1',
      'created_at' => '1322931744',
      'updated_at' => '1322931744',
      ),
       '_data_relations' =>
      array (
      ),
       '_original_relations' =>
      array (
      ),
       '_view' => NULL,
       '_iterable' =>
      array (
      ),
      )),
    )
    

    Output of an array of ORM objects is a little verbose, but at least we can see the data. This means the relationship is working nicely, so let’s modify the ORM query in the blog controllers action_view() method to include comments:

    $post = Model_Post::find_by_slug($slug, array('related' => array('user', 'comments')));
    

    Now update the blog view to output the comments and have a form to add more:

    <h2><?php echo $post->title ?></h2>
    
    <p>
    	<strong>Posted: </strong><?php echo date('nS F, Y', $post->created_at) ?> (<?php echo Date::time_ago($post->created_at)?>)
    	by <?php echo $post->user->username ?>
    </p>
    
    <p><?php echo nl2br($post->body) ?></p>
    
    <hr />
    
    <h3 id="comments">Comments</h3>
    
    <?php foreach ($post->comments as $comment): ?>
    
    	<p><?php echo Html::anchor($comment->website, $comment->name) ?> said "<?php echo $comment->message?>"</p>
    
    <?php endforeach; ?>
    
    <h3>Write a comment</h3>
    
    <?php echo Form::open('blog/comment/'.$post->slug) ?>
    
    <div class="row">
    	<label for="name">Name:</label>
    	<div class="input"><?php echo Form::input('name'); ?></div>
    </div>
    
    <div class="row">
    	<label for="website">Website:</label>
    	<div class="input"><?php echo Form::input('website'); ?></div>
    </div>
    
    <div class="row">
    	<label for="email">Email:</label>
    	<div class="input"><?php echo Form::input('email'); ?></div>
    </div>
    
    <div class="row">
    	<label for="message">Comment:</label>
    	<div class="input"><?php echo Form::textarea('message'); ?></div>
    </div>
    
    <div class="row">
    	<div class="input"><?php echo Form::submit('submit'); ?></div>
    </div>
    
    <?php echo Form::close() ?>
    

    This code will output all comments in a very basic style followed by a really simple form using Twitter Bootstrap markup. I’m sure you can whip up some styling for the comments section.

    Comment form

    We can see the comment is being output and any that are added will also be put in. So the next and final stage in the process is to get comments saved.

    The line with Form::open('blog/comment/'.$post->slug) will set the action to blog/comment/women-love-guys-who-use-fuelphp which means Controller_Blog needs a new method action_comment($slug) which should look something like this:

    public function action_comment($slug)
    {
    	$post = Model_Post::find_by_slug($slug);
    
    	// Lazy validation
    	if (Input::post('name') AND Input::post('email') AND Input::post('message'))
    	{
    		// Create a new comment
    		$post->comments[] = new Model_Comment(array(
    			'name' => Input::post('name'),
    			'website' => Input::post('website'),
    			'email' => Input::post('email'),
    			'message' => Input::post('message'),
    			'user_id' => $this->current_user->id,
    		));
    
    		// Save the post and the comment will save too
    		if ($post->save())
    		{
    			$comment = end($post->comments);
    			Session::set_flash('success', 'Added comment #'.$comment->id.'.');
    		}
    		else
    		{
    			Session::set_flash('error', 'Could not save comment.');
    		}
    
    		Response::redirect('blog/view/'.$slug);
    	}
    
    	// Did not have all the fields
    	else
    	{
    		// Just show the view again until they get it right
    		$this->action_view($slug);
    	}
    }
    
    Summary

    This article skipped a few things like how to set up a pretty URL instead of localhost/blog/public and how to use form validation in the model or the controller, but all of this can be found in the FuelPHP Documentation. I planned to touch on things like File Uploads and Migrations a little more but again this is all documented already.

    You should have enough code now to pick apart and play with, and whatever project you choose to work on with FuelPHP already has a blog now – so throw up a splash page, design it and you are ready to make the next SquareFaceTwitBook.


  • Permalink for 'Quick Tip: Create a Makeshift JavaScript Templating Solution'

    Quick Tip: Create a Makeshift JavaScript Templating Solution

    Posted: December 9th, 2011, 11:02am MST by Jeffrey Way

    Sometimes, you don’t require a high-quality templating solution, but still need to keep from mixing lots of nasty HTML into your JavaScript. In these cases, a simple, makeshift templating system can go a long way.

    Choose 720p for the best clarity.
    Subscribe to our YouTube channel for more training. Final Source HTML
    <!doctype html public 'ahh hell yeah'>
    <html>
    <head>
    	<meta charset=utf-8>
    	<title>Simple Templating</title>
    </head>
    <body>
    
      <div class="result"></div>
    
      <script type="template" id="template">
        <h2>
          <a href="{{href}}">
            {{title}}
          </a>
        </h2>
        <img src="{{imgSrc}}" alt="{{title}}">
      </script>
    
    </body>
    </html>
    
    JavaScript
    ;(function() {
      // simulates AJAX request
      var data = [
        {
          title: "Create a Sticky Note Effect in 5 Easy Steps with CSS3 and HTML5",
          href: " [net.tutsplus.com]       imgSrc: " [d2o0t5hpnwv4c1.cloudfront.net]     },
        {
          title: "Nettuts+ Quiz #8",
          href: " [net.tutsplus.com]       imgSrc: " [d2o0t5hpnwv4c1.cloudfront.net]     },
        {
          title: "WordPress Plugin Development Essentials",
          href: " [net.tutsplus.com]       imgSrc: " [d2o0t5hpnwv4c1.cloudfront.net]     }
      ],
          template = document.querySelector('#template').innerHTML,
          result = document.querySelector('.result'),
          i = 0, len = data.length,
          fragment = '';
    
      for ( ; i < len; i++ ) {
        fragment += template
          .replace( /\{\{title\}\}/, data[i].title )
          .replace( /\{\{href\}\}/, data[i].href )
          .replace( /\{\{imgSrc\}\}/, data[i].imgSrc );
      }
    
      result.innerHTML = fragment;
    })();
    
    Alternative

    The method outlined in the screencast is the most readable, however, if you’d prefer a more automated approach, we can apply the values and regular expressions dynamically, like so:

    ;(function () {
        // simulates AJAX request
        var data = [{
            title: "Create a Sticky Note Effect in 5 Easy Steps with CSS3 and HTML5",
            href: " [net.tutsplus.com]         imgSrc: " [d2o0t5hpnwv4c1.cloudfront.net]     }, {
            title: "Nettuts+ Quiz #8",
            href: " [net.tutsplus.com]         imgSrc: " [d2o0t5hpnwv4c1.cloudfront.net]     }, {
            title: "WordPress Plugin Development Essentials",
            href: " [net.tutsplus.com]         imgSrc: " [d2o0t5hpnwv4c1.cloudfront.net]     }],
            template = document.querySelector('#template').innerHTML,
            result = document.querySelector('.result'),
            attachTemplateToData;
    
        // Accepts a template and data. Searches through the
        // data, and replaces each key in the template, accordingly.
        attachTemplateToData = function(template, data) {
            var i = 0,
                len = data.length,
                fragment = '';
    
            // For each item in the object, make the necessary replacement
            function replace(obj) {
                var t, key, reg;
    
                for (key in obj) {
                    reg = new RegExp('{{' + key + '}}', 'ig');
                    t = (t || template).replace(reg, obj[key]);
                }
    
                return t;
            }
    
            for (; i < len; i++) {
                fragment += replace(data[i]);
            }
    
            return fragment;
        };
    
        result.innerHTML = attachTemplateToData(template, data);
    
    })();
    

    This is the method that I’m most likely to use.

    Additional Tools

    If you’d prefer a more flexible solution, any of the following should do the trick!


  • Permalink for 'Create a Sticky Note Effect in 5 Easy Steps with CSS3 and HTML5'

    Create a Sticky Note Effect in 5 Easy Steps with CSS3 and HTML5

    Posted: December 8th, 2011, 8:20am MST by Christian Heilmann

    Twice a month, we revisit some of our readers’ favorite posts from through out the history of Nettuts+. This tutorial was first published in August, 2010.

    In this tutorial, you’ll learn how to transform an HTML list into a wall of “sticky notes” that look and work like the following…

    The effect is built up gradually and works on the latest Webkit browsers (Safari, Chrome), Firefox and Opera. Other browsers simply get some yellow squares.

    Step 1: The HTML and Basic Squares

    Let’s start with the simplest version that works across all browsers. As we are using HTML5 for the effect, the basic HTML of our sticky notes is an unordered list with a link containing all the other elements in each list item:

    <ul>
      <li>
        <a href="#">
          <h2>Title #1</h2>
          <p>Text Content #1</p>
        </a>
      </li>
      <li>
        <a href="#">
          <h2>Title #2</h2>
          <p>Text Content #2</p>
        </a>
      </li>
      […]
    </ul>

    Notice that each note is surrounded by a link which is always a good element to use as it automatically means that our notes become keyboard accessible. If we used the list item for the effect we’d need to set a tabindex property to get the same access.

    The CSS to turn this into the yellow squares is simple:

    *{
      margin:0;
      padding:0;
    }
    body{
      font-family:arial,sans-serif;
      font-size:100%;
      margin:3em;
      background:#666;
      color:#fff;
    }
    h2,p{
      font-size:100%;
      font-weight:normal;
    }
    ul,li{
      list-style:none;
    }
    ul{
      overflow:hidden;
      padding:3em;
    }
    ul li a{
      text-decoration:none;
      color:#000;
      background:#ffc;
      display:block;
      height:10em;
      width:10em;
      padding:1em;
    }
    ul li{
      margin:1em;
      float:left;
    }

    We reset things the browser normally gives us like margins and paddings and the list style to get rid of the bullets of the list.

    We then give the UL element some padding and set its overflow property to hidden – this makes sure that when we float the list items later on they are contained in the list and the following elements in the document automatically clear the float.

    We style the link as a yellow rectangle and float all of the list items to the left. The result is a series of yellow boxes for our list:

    a series of yellow boxes

    This works for every browser out there – including IE6. This is also where we end supporting this browser as we should not shoe-horn visual effects supported by modern technology into outdated one.

    Step 2: Drop Shadows and Scribbly Font

    Now it is time to add a drop shadow to the notes to make them stand out and to use a scribbly, hand-written font as the note font. For this we use the Google Fonts API and the font they provide us with, called “Reenie Beanie”. The easiest way to use this API is to play with the Google font previewer:

    The Google font previewer allows you to play with the fonts API and get copy+paste CSS code

    Using this, we get a simple line of HTML to include this new font into the page. This is supported by all modern browsers.

    <link  href=" [fonts.googleapis.com] family=Reenie+Beanie:regular"
    rel="stylesheet"
    type="text/css">

    We then can set some padding to the headings in the sticky notes, and set the font of the paragraphs to the new font we included. Notice that Reenie Beanie needs to be big to be readable:

    ul li h2{
      font-size:140%;
      font-weight:bold;
      padding-bottom:10px;
    }
    ul li p{
      font-family:"Reenie Beanie",arial,sans-serif;
      font-size:180%;
    }

    In order to give the sticky notes a shadow to make them stand out from the page, we need to apply a box-shadow. For this, we must add a line for each of the different browsers we want to support to the style of the links:

    ul li a{
      text-decoration:none;
      color:#000;
      background:#ffc;
      display:block;
      height:10em;
      width:10em;
      padding:1em;
      /* Firefox */
      -moz-box-shadow:5px 5px 7px rgba(33,33,33,1);
      /* Safari+Chrome */
      -webkit-box-shadow: 5px 5px 7px rgba(33,33,33,.7);
      /* Opera */
      box-shadow: 5px 5px 7px rgba(33,33,33,.7);
    }

    The syntax is luckily the same for each: offset, spread and colour – in this case a dark grey with an opacity of 70%. Together with the new font our sticky notes now look like this:

    adding new fonts and drop shadows Step 3: Tilting the Notes

    Disclaimer: Both the tilting of the notes and the zooming we’ll add in the next step were already explained in the past, in this article by Zurb, but lacked the support for other browsers, as they weren’t out at the time of writing. So big thanks to them for publishing this trick.

    In order to tilt an element you use the transform:rotate property of CSS3, again adding the prefix for each of the browsers:

    ul li a{
      -webkit-transform:rotate(-6deg);
      -o-transform:rotate(-6deg);
      -moz-transform:rotate(-6deg);
    }

    This tilts all the links by six degrees to the left. Now to make the sticky notes appear to be randomly tilted, we can use the nth-child property of CSS3:

    ul li:nth-child(even) a{
      -o-transform:rotate(4deg);
      -webkit-transform:rotate(4deg);
      -moz-transform:rotate(4deg);
      position:relative;
      top:5px;
    }
    ul li:nth-child(3n) a{
      -o-transform:rotate(-3deg);
      -webkit-transform:rotate(-3deg);
      -moz-transform:rotate(-3deg);
      position:relative;
      top:-5px;
    }
    ul li:nth-child(5n) a{
      -o-transform:rotate(5deg);
      -webkit-transform:rotate(5deg);
      -moz-transform:rotate(5deg);
      position:relative;
      top:-10px;
    }

    This tilts every second link four degrees to the right, and offsets it a bit by five pixels from the top. Every third link gets tilted by three degrees to the left and pushed up five pixels. And every fifth link gets rotated five degrees to the right and offset ten pixels from the bottom. All in all this gives the impression of random sticky notes:

    seemingly random sticky notes Step 4: Zooming the Sticky Notes on Hover and Focus

    To make a sticky note stand out we use a larger drop shadow and the scale transformation of CSS3. Again, we need to define these for each of the browsers:

    ul li a:hover,ul li a:focus{
      -moz-box-shadow:10px 10px 7px rgba(0,0,0,.7);
      -webkit-box-shadow: 10px 10px 7px rgba(0,0,0,.7);
      box-shadow:10px 10px 7px rgba(0,0,0,.7);
      -webkit-transform: scale(1.25);
      -moz-transform: scale(1.25);
      -o-transform: scale(1.25);
      position:relative;
      z-index:5;
    }

    We also add a higher z-index to ensure that the enlarged sticky note covers the others. As we apply this on hover and focus,it means that moving the mouse over or tabbing to a link now makes it stand out:

    Zooming the current sticky note Step 5: Adding Smooth Transitions and Colors

    The last step is to make the change from tilted to zoomed smooth and appealing rather than sudden. For this we use the CSS3 transition module in its different browser vendor implementations:

    ul li a{
      text-decoration:none;
      color:#000;
      background:#ffc;
      display:block;
      height:10em;
      width:10em;
      padding:1em;
      -moz-box-shadow:5px 5px 7px rgba(33,33,33,1);
      -webkit-box-shadow: 5px 5px 7px rgba(33,33,33,.7);
      box-shadow: 5px 5px 7px rgba(33,33,33,.7);
      -moz-transition:-moz-transform .15s linear;
      -o-transition:-o-transform .15s linear;
      -webkit-transition:-webkit-transform .15s linear;
    }

    In essence this says: if something is to change to this element, do not just switch to that other definition but do it gradually during a quarter of a second. As another extra, let’s add some colour into the mix by making every second sticky note green and every third light blue:

    ul li:nth-child(even) a{
      -o-transform:rotate(4deg);
      -webkit-transform:rotate(4deg);
      -moz-transform:rotate(4deg);
      position:relative;
      top:5px;
      background:#cfc;
    }
    ul li:nth-child(3n) a{
      -o-transform:rotate(-3deg);
      -webkit-transform:rotate(-3deg);
      -moz-transform:rotate(-3deg);
      position:relative;
      top:-5px;
      background:#ccf;
    }

    In order to see the difference to the last step, you’d need to try the last demo out in a browser.

    Coloured and smoothly zooming sticky notes Summary and Download

    There you have it – smoothly animating and tilted sticky notes without any use of images or JavaScript – supported by Firefox, Opera, Safari and Chrome and falling back to a set of yellow boxes in older browsers. By clever use of the nth-child selector and CSS transformations and transitions, we saved ourselves some scripting. Further, Google’s Web Font API made it easy to use a custom font. Using both hover and focus for the effect also means that keyboard users can observe the results as well.

    Download the sticky notes example as a zip.

    About the Author

    Christian Heilmann is an international Developer Evangelist who works for the Yahoo Developer Network in the lovely town of London, England. He’s written two books: “Beginning JavaScript with DOM Scripting and AJAX“, and “Web Development Solutions.”


  • Permalink for 'Nettuts+ Quiz #8: Abbreviations – Darth Sidious Edition'

    Nettuts+ Quiz #8: Abbreviations – Darth Sidious Edition

    Posted: December 7th, 2011, 2:00pm MST by Siddharth

    Abbreviations are an inevitable part of being a web developer. HTML, CSS, [HTTP,] XML… the list goes on and on.

    This Darth Sidious edition should be a fairly advanced test of your web development force-fu. Keep in mind that this covers the entire spectrum of the web, not merely code — so be warned!



    $(document).ready(function(){ $('#quiz-container').jquizzy({ questions: init.questions, resultComments: init.resultComments, twitterStatus: 'Woo! I scored {score} on the Nettuts Abbreviations quiz. Give it a shot!', twitterImage: 'http://d2o0t5hpnwv4c1.cloudfront.net/jquizzy-1.0/img/share.png', twitterUsername: 'envatowebdev', splashImage: 'http://d2o0t5hpnwv4c1.cloudfront.net/1102_quiz8/nettuts.png', }); });


  • Permalink for 'WordPress Plugin Development Essentials: New Premium Course'

    WordPress Plugin Development Essentials: New Premium Course

    Posted: December 6th, 2011, 12:24pm MST by Jeffrey Way

    So you’ve wrapped your mind around the process of creating WordPress themes, and now you want to take things to the next level? In that case, it’s time to begin learning how to create plugins for WordPress. In this Tuts+ Premium course, we start from the absolute basics, and work our way up to more advanced topics and techniques.

    With hours of training, and nearly fifty videos, I’ll teach you, step by step, how to work with shortcodes, widgets, custom post types, WP Cron, and much more. If you’re unfamiliar with Tuts+ Premium, for $19 a month, you gain access to hundreds upon hundreds of tutorials, an entire catalog of ebooks from Rockable Press and Smashing Magazine, and our new courses section (to be updated a few times every month).

    If you’re on the fence, try signing up for a single month, and see how it goes! We have a 30-day, no questions asked, money back promise.

    Tuts Plus Questions?

    If you have any questions about the Tuts+ Premium service, just leave a comment; I’d be glad to help out any way that I can.


  • Permalink for 'A Brief History of HTML5'

    A Brief History of HTML5

    Posted: December 6th, 2011, 10:28am MST by Jeffrey Way

    This is that article you generally skip over. It’s the one where I don’t detail an ounce of code, but instead describe the important events that lead to what you now recognize as HTML5. Some of us find this stuff interesting, but, certainly, a history lesson may not be your idea of a good time.

    …Wait – you’re still here? Let’s get on with it then.

    We won’t travel as far back as the beginning. That’s an entire book on its own. Instead, we’ll rewind the clock to to the release of HTML 4.01, at the tail-end of the nineties.

    What’s the Difference Between the W3C, WHAT WG, and HTML WG?
    • W3C – A community with the sole purpose of working to develop web standards.
    • WHATWG – Formed after various members of the W3C became agitated by the direction being taken with XHTML 2.0. They preferred a different, less drastic approach, where the existing HTML was extended.
    • HTML WG – Once the W3C finally recognized that XHTML 2.0 was not the future, they indicated that they wished to work with the WHAT WG on development of what would eventually become HTML5. They chartered the HTML WG for this purpose.

    If that still sounds confusing, don’t worry; continue reading for the full story.

    HTML vs XHTML

    Right around the period that HTML advanced to version 4.01 (around 1998), the ground began to shift a bit. Developers started to talk about this next new thing the W3C was working on: XHTML, which stood for “Extensible Hypertext Markup Language.” This first 1.0 specification was more or less identical to HTML 4.01, other than the inclusion of a new MIME type, application/xhtml+xml.

    Believe it or not, we’ve always been able to get away with omitting quotations around attribute values (mostly), and not self-closing tags. However, up until recently, it was widely considered to be a bad practice. For the youngsters among you readers, the reason why we viewed it as a bad practice is largely due to the popularity of XHTML.

    Think of XHTML as your grandmother. When she comes to visit, she forces you to brush your teeth, stand up straight, and eat your peas. Now replace teeth, posture, and peas, with quotation marks, self-closing tags, and lowercase tag names.

    Though I kid, mostly, we viewed XHTML 1.0 as a good thing – the next step. It required designers and developers to follow a set of standards when creating markup. How could that be bad? The irony is that, though we followed these new rules, the majority of us continued serving pages with the text/html MIME type, which meant that the browser didn’t really care how we created our markup. This way, XHTML could be opt-in.

    So we were writing markup in a certain, strict fashion to pass XHTML validation that had zero effect or influence on the browser’s rendering. A bit odd, huh?

    XHTML 1.1

    This all changed with the introduction of XHTML 1.1 – a significant shift toward pure XML. With this release, the application/xhtml+xml MIME type was required. Sure, this may sound like the natural next step, in theory, but there were a couple glaring issues.

    1. “Save to Disk”

    First, Internet Explorer could not render documents with this MIME type. Instead, it would prompt a save to disk dialog. Yikes!

    “I’ve also been reading comments for some time in the IEBlog asking for support for the “application/xml+xhtml” MIME type in IE. I should say that IE7 will not add support for this MIME type – we will, of course, continue to read XHTML when served as “text/html”, presuming it follows the HTML compatibility recommendations.” – Chris Wilson

    2. Take No Prisoners

    XHTML 1.1 was sort of like Professor Umbridge, from Harry Potter.

    Secondly, XHTML 1.1 was sort of like Professor Umbridge, from Harry Potter: extremely harsh. Have you ever noticed how, if you leave off a closing </li> tag, the browser doesn’t flinch? Browsers are smart, and compensate for your broken markup (more on this shortly). While, these days, the community is beginning to embrace and take advantage of this truth, with XHTML, the W3C wanted to enforce XHTML’s stricter syntax. Though, up to this point, developers could get away with leaving off, say, the closing <head> or <body> tag, the W3C implemented a new fail on the first error system, known as draconian error handling. If an error was detected, the browser was expected to cease rendering the page, and display an error message, accordingly. Like I said: incredibly harsh for markup.

    As a result, few of us ever used XHTML 1.1; it was too risky. Instead, we adopted general XML best practices, and continued to serve our pages as text/html.

    XHTML 2

    In their minds, the W3C was finished with HTML 4. They even shut down and rechartered the HTML Working Group, and transferred their focus to XHTML – or, at this point, XHTML 2.0.

    XHTML2 was an effort to draw a line, fix the web, and right the wrongs of HTML. Though, again, this sounds fabulous, in truth, it angered much of the community, due to the fact that it was never intended to be backward compatible with HTML 4. In fact, it was entirely different from XHTML 1.1 as well!

    Get where I’m going here? The W3C was essentially ignoring the current web, and the demands of its developers, in favor of a strict, potentially page-breaking XML approach. It simply wasn’t practical to expect such a huge transition.

    XHTML2 was never finalized.

    Fight, Fight, Fight!

    (Okay, not as Fight Club as that.) Right around this time, the idea that, “Hey – maybe we should return to HTML and work off that” began to come up again. Work had begun on Web Forms 2.0, which managed to spark renewed interest in HTML, rather than scrapping it entirely for XHTML2. This notion was put to the test in 2004, during a W3C workshop, where the advocates for HTML presented their case, and the work they had already done with Web Forms 2.0.

    Unfortunately, the proposal was rejected on the grounds that it didn’t fall in line with the original goal of working toward XHTML2. Needless to say, this rejection angered some in the group, including representatives from Mozilla and Opera.

    The group consequently branched out, and formed the WHAT Working Group (or, “Web Hypertext Application Technology Working Group.”), after, for lack of better words, becoming pissed off at the way XHTML 2 seemed to be heading. Their goal was to keep from throwing the baby out with the bath water. Continue and extend development of HTML, via three specifications: Web Forms 2.0, Web Apps 1.0, and Web Controls 1.0.

    The Two Golden Rules

    This new group would embrace two core principles:

    1. Backward compatibility is paramount. Don’t ignore the existing web.
    2. Specifications and implementations must match one another. This means that the spec should be incredibly detailed (hence, the 900 pages).

    “The Web Hypertext Applications Technology working group therefore intends to address the need for one coherent development environment for Web Applications. To this end, the working group will create technical specifications that are intended for implementation in mass-market Web browsers, in particular Safari, Mozilla, and Opera.” – WHATWG.org

    Parser

    Don’t underestimate how significant an achievement this was.

    While XHTML 2.0 intended to enforce perfect XML, the WHAT Working Group instead took it upon themselves to document exactly how HTML is, and should be parsed. – a five year task!

    Remember when we discussed how browsers do a great job of compensating for your broken markup? The interesting thing is that, before the creation of the WHAT Working Group, there wasn’t any specification that provided instructions to the browser vendors for how to deal with errors. This naturally leads up to the question: how did the browsers match one another’s error handling? The answer is through tireless (though essential) reverse engineering. Firefox, Safari, and Opera copied Internet Explorer’s implementation, and Internet Explorer reverse engineered Netscape handling.

    Over the course of five years, the WHAT WG charted out what’s now referred to as the HTML5 parser. Don’t underestimate how significant an achievement this was. Today, all modern browsers parse HTML according to the guidelines of this specification. Though perhaps not as sexy as, say, canvas, the HTML5 parser is a massive achievement.

    A Line in the Sand

    As you might expect, an imaginary line was drawn in the sand. You’re either for XHTML2, or (what would eventually become) HTML5.

    Rather than a consensus-based approach, where members debated and voted on what they felt was best, the WHAT WG took a bit more of a dictator-like stance, with Ian Hickson at the helm.

    Wait – Dictator!?

    Don’t we usually try to over throw these power mongers?

    Don’t we usually try to over throw these power mongers? What’s the deal? I must admit, on paper, it sounds awful, doesn’t it? Does one guy determines the future of the web? We prefer this system? Politically speaking, yes, a dictatorship may be a bad idea. But, when you think about it in terms of the web, imagine how much more quickly things can get done. When a community is as passionate as ours, things tend to move very slowly, as debates continue on and on…and on.

    “The Web is, and should be, driven by technical merit, not consensus. The W3C pretends otherwise, and wastes a lot of time for it. The WHATWG does not.” – Ian Hickson

    While discussion certainly (and rightfully) takes place at the WHAT WG, ultimately, Ian Hickson has his finger on the button (unless the group and community strongly disagrees with a particular decision. At this point, he can either be impeached (not as Bill Clinton as that), or, more often than not, he’ll re-evaluate and reverse his decision).

    That said, it’s certainly not ideal. The W3C has its slow and steady consensus-based approach, which many still prefer. On the other hand, while the WHAT WG moves at a quicker pace, there certainly are hiccups. Then, when you combine the two groups, things can sometimes get a bit muddy!

    The time Debacle

    In October, 2011, Ian Hickson removed the <time> tag, and replaced it with a more general-purpose solution: <data>. In his own words:

    There are several use cases for <time>:

    1. Easier styling of dates and times from CSS.
    2. A way to mark up the publication date/time for an article (e.g. for
      conversion to Atom).
    3. A way to mark up machine-readable times and dates for use in Microformats or
      microdata.

    Use cases A and B do not seem to have much traction. Use case C applies to more than just dates, and the lack of solution for stuff outside dates and times is being problematic to many communities.

    Proposal: we dump use cases A and B, and pivot <time> on use case C, changing it to and making it like the <abbr> for machine-readable data, primarily for use by Microformats and HTML’s microdata feature. – Ian Hickson

    Remember: you have much more control over the shape of the web than you likely give yourself credit for!

    What he possibly didn’t realize was that much of the community did, in fact, use the <time> tag. Further, they (myself included) felt that, though more flexible, the proposed <data> tag was too ambiguous; <data> has as much meaning as a <span>, when it comes to semantics.

    After a significant level of uproar from the community, the HTML WG announced that the <time> change must be reverted. They gave Ian a short deadline to make the reversal. Though not without additional layers of drama, the following month, <time> was reinstated.

    This chain of events simply proves that, even though Ian has the right to propose these sorts of changes, the web community, as a whole – and, of course, the browser vendors – have quite a bit of control over the specification. There’s a difference between the spec creators, and the authors who integrate these new elements and APIs into their projects. If the authors don’t use them, they might as well be removed from the spec. Remember: you have much more control over the shape of the web than you likely give yourself credit for!

    Sign up for the various mailing lists and be loud! Otherwise, folks like Ian won’t know if or how you use these new features.

    “Is there any data showing how people actually use <time> in practice? i.e. is it actually giving anyone any of its hypothetical benefits?” – Comment by Ian Hickson

    The Shape of a Specification

    While some may think that a small group of people determine the future of the web, that’s far from the case. Three factions receive equal weight, when it comes to specifications.

    1. Spec Creators – Obviously…
    2. Authors – People like us; if we reject (i.e. don’t use) a particular element or API, it might as well be dead in the water.
    3. Vendors – Browsers have a huge amount of input into these specifications, many times leading the way.

    If you’d like to learn more about the <time> debacle, review the bug thread, and Ian’s Google+ post. They’re interesting reads, and aren’t nearly as black or white as you might think.

    Back at the W3C…

    Back to the W3C vs. WHAT WG feud. Well, it was less a feud, and more like two groups ignoring one another for a couple years.

    As time progressed, it became clearer and clearer that XHTML 2.0 was not the solution.

    While work at the WHAT WG progressed relatively quickly, work on XHTML 2.0 at the W3C was – how should I put this… – not going well (almost non-existent). As time progressed, it became clearer and clearer that XHTML 2.0 was not the solution (though it wouldn’t be fully dropped until 2009). In 2006, the W3C relented, and signaled that they were interested in collaborating with the WHAT WG on (what would be) HTML5. They chartered yet another group for this purpose: HTML WG, or the Hypertext Markup Language Working Group.

    They intended to use the work of the WHAT WG as a basis for continued development of HTML. Weird, huh? Now we have two different groups: the W3C HTML WG and the WHAT WG. Technically, the W3C hadn’t yet given up on XHTML. Nonetheless, as part of the newly formed HTML WG, they renamed Web Apps 1.0 to HTML5.

    “Apple, Mozilla, and Opera allowed the W3C to publish the specification under the W3C copyright, while keeping a version with the less restrictive license on the WHAT WG site.” – WHATWG.org

    Today

    These days, the WHAT WG and W3C collaborate with one another on HTML5. It’s a bit of an odd relationship, but somehow manages to function, thanks to an endless supply of incredibly passionate activists.

    This article is an excerpt from my upcoming book on HTML5 and its friends. Stay tuned to Nettuts+ for more information on the release date!


  • Permalink for 'Create a Windows-like Interface with jQuery UI'

    Create a Windows-like Interface with jQuery UI

    Posted: December 5th, 2011, 8:10am MST by Nikko Bautista

    Have you ever wanted to create an interactive user interface for your application, but didn’t know how to? In this tutorial, we’ll create a Windows-like interface quickly and easily, by getting down and dirty with jQuery UI, a user interface library built on top of jQuery.

    What Exactly is jQuery UI? jQuery UI

    jQuery UI provides abstractions for low-level interaction and animation, advanced effects and high-level, themeable widgets.

    jQuery UI has always been a great tool in any front-end developer’s kit. It has a lot of different widgets and effects that have been beautifully made to work with most browsers. Want a fast way to create a tabbed interface? jQuery UI has got ‘em! Want to create a modal dialog box? It has them too!

    In this tutorial, we’ll be learning how to utilize jQuery UI to create a highly-functional user interface without using anything else. By the end, you should be familiar with jQuery UI, some of its components, and basic understanding of jQuery UI customization. Ultimately, we’ll be building a user interface akin to windows, with dialog boxes that are draggable, resizable, minimizable and maximizable.

    Note: If you really want to customize every nook-and-cranny of the jQuery UI’s theme, you should check out this tutorial entitled “A Massive Guide to Custom Theming jQuery UI Widgets”. It’s a Premium-only tutorial, but I guarantee it’s well-worth the purchase.!

    Our Goal: To create draggable, resizable, minimizable and maximizable windows-like dialog boxes that we can implement for different kinds of applications

    windows-like interface example from Aralista!
    Windows-like interface example from Aralista!

    Image courtesy of [aralista.com] Step 1: Setting Up

    To begin, download the jQuery UI library from their site, [jqueryui.com] . Once you visit the site, you’ll see multiple options to “customize” your jQuery UI download.

    The jQuery UI Download Page
    The jQuery UI Download Page

    For the purposes of our tutorial, make sure that all the components are selected. For the theme, select the Flick theme. Double check that you also select the 1.8.16 version, as jQuery UI’s download page provides a legacy version for older jQuery releases.

    The jQuery UI download should come with the 1.6.2 version of the jQuery library as well. If you’re using a more current version of jQuery, you should use that instead. This is just the minimum version of jQuery that’s needed by jQuery UI.

    Extract the download into your project’s public folder. The download suggests a structure for your site resources:

    Suggested file-structure for your site resources
    Suggested file-structure for your site resources
    • a js folder for your JavaScript files (jQuery UI and jQuery)
    • a css fodler for your CSS files (jQuery UI theme CSS)

    Feel free to change this to suit your needs, though in my experience, this is a great way to organize your site’s resources.

    After extracting your files, create an index.html file which will contain our page’s HTML. The content of the HTML file should be as follows:

    <!DOCTYPE html>
    <html>
    	<head>
                   <meta charset="utf-8">
    		<title>Creating a windows-like interface with jQuery UI</title>
    		<!-- Load the jQuery UI CSS -->
    		<link rel="stylesheet" href="css/flick/jquery-ui-1.8.16.custom.css" type="text/css" />
    
    		<!-- Load jQuery first before jQuery UI! -->
    		<script src="js/jquery-1.6.2.min.js"></script>
    		<script src="js/jquery-ui-1.8.16.custom.min.js"></script>
    	</head>
    	<body>
    	</body>
    </html>
    
    Step 2: Create the HTML for Our Dialog Windows

    Now, let’s begin by creating the HTML for our Dialog windows. According to the Dialog documentation page on jQuery UI’s site, a Dialog box’s HTML is simply a <div>. Any other HTML inside the <div> becomes the content of the dialog box. Knowing that, create a simple Dialog box window and open it using jQuery UI.

    Copy the following code over to the <body> of the HTML file:

    <div id="dialog_window_1" class="dialog_window" title="This is our first dialog window">
    	<p>Hello World!</p>
    </div>
    

    Then, initiate the Dialog box by executing this JavaScript. Copy the following code inside the <head> of the HTML file:

    <script>
    	$(document).ready(function() {
    		$('#dialog_window_1').dialog();
    	});
    </script>
    

    Once you refresh the page, you should see something like this:

    Hello World!

    Hello World!

    Initializing a Dialog box can be done by simply calling the $(element_id).dialog() function! And as you can see, our content inside the <div> will be converted into content for the dialog box.

    Now, create a simple form to create new Dialog boxes inside the Dialog Box. Replace the Hello World! code inside our initial Dialog box with the following:

    <h3>Create a new <code>Dialog</code> Window</h3>
    <table class="dialog_form">
    	<tr>
    		<th>window Title</th>
    	</tr>
    	<tr>
    		<td><input type="text" id="new_window_title" /></td>
    	</tr>
    	<tr>
    		<th>
    			window Content
    		</th>
    	</tr>
    	<tr>
    		<td>
    			<textarea id="new_window_content"></textarea>
    		</td>
    	</tr>
    	<tr>
    		<th>
    			window Buttons
    		</th>
    	</tr>
    	<tr>
    		<td id="buttonlist">
    			<input type="checkbox" id="alertbutton" /><label for="alertbutton">ALERT</label>
    			<input type="checkbox" id="closebutton" /><label for="closebutton">CLOSE</label>
    			<input type="checkbox" id="clonebutton" /><label for="clonebutton">CLONE</label>
    		</td>
    	</tr>
    </table>
    

    When you refresh the page, it should look something like this:

    (

    It looks a tad ugly right now, but don’t worry, we’ll be adding some customizations to the Dialog window to make it look better

    Step 3: Customizing our Dialog Windows via Dialog Options and CSS

    Our Dialog box currently doesn’t look very good, but we’ll be able to customize it by providing some initialization options to our Dialog initialization code, and of course, some CSS.

    Let’s replace our initialization code with the following:

    $('#dialog_window_1').dialog({
    	width: 'auto',
    	height: 'auto'
    });
    

    Let’s also add some CSS in the <head> of our HTML:

    <style>
    .dialog_form th {
    	text-align: left;
    }
    
    .dialog_form textarea, .dialog_form input[type=text] {
    	width: 320px;
    }
    </style>
    
    Much better!

    Much better!

    Let’s break down some of the options that we used on our initialization code:

    • width – this option lets you set a specific width for your Dialog box. You can also set it to 'auto' to let jQuery UI set the width dyanmically
    • height – does virtually the same thing as the width option, but does it for the height of the Dialog box instead of width

    There are a lot more options for the Dialog box, but most of them deal with the behaviour of the Dialog box. We’ll go into some of these in the later steps of the tutorial.

    Now that we have a nice-looking Dialog box with a form inside, let’s add some Buttons to our Dialog box to make it do something!

    Step 4: Adding a Button to Open our Dialog Window

    One of the great things about jQuery UI is its modularity. For example, the Dialog box also uses other jQuery UI components, like Draggable, Resizable, and most importantly, the Button component.

    Button example from jQuery UI's documentation

    Button example from jQuery UI’s documentation

    The Button component allows us to create buttons with customized functions upon clicking. And at the same time, it corresponds with the theme we installed with jQuery UI, so changing the theme will also change the look of the button, therefore keeping the design uniform throughout the site.

    For starters, create a Button to open and close our Dialog box. Add this to the <body> of the HTML:

    <button id="create_button">Create a new window</button>
    

    And initialize it by adding this to the $(document).ready() function:

    $('#create_button').button();
    
    Cool button bro

    Cool button bro

    Since we’re doing stuff with buttons, let’s convert our checkboxes to buttons as well so they’ll look better. jQuery UI’s Button component also lets you recreate a set of checkboxes or radio buttons into a Buttonset. To do so, just copy the following code code in the JavaScript block:

    $('#buttonlist').buttonset();
    

    Now, refresh the page to see the new pretty-fied checkboxes:

    Cool checkboxes bro

    Now that the Dialog box and Button are rendering well, we can change their behaviour so that the Button opens and closes the Dialog. To do so, update the JavaScript block so it’ll look like this:

    $(document).ready(function() {
    	//initialize the button and add a click function to our button so that it"ll open the window
    	$("#create_button").button().click(function() {
    		var create_dialog = $("#dialog_window_1");
    		var create_button = $(this);
    
    		//if the window is already open, then close it and replace the label of the button
    		if( create_dialog.dialog("isOpen") ) {
    			create_button.button("option", "label", "Create a new window");
    			create_dialog.dialog("close");
    		} else {
    			//otherwise, open the window and replace the label again
    			create_button.button("option", "label", "Close window");
    			create_dialog.dialog("open");
    		}
    	});
    
    	//open our dialog window, but set autoOpen to false so it doesn"t automatically open when initialized
    	$("#dialog_window_1").dialog({
    		width: "auto",
    		height: "auto",
    		autoOpen : false
    	});
    
    	//initialize our buttonset so our checkboxes are changed
    	$("#buttonlist").buttonset();
    });
    

    Let’s go through the code line-by-line:

    • We’ve added a click function to our Button that opens the Dialog box whenever we click on it.
    • Additionally, we use the $(dialog_id).dialog('isOpen') method, which returns true if our Dialog is already open, and false if not.
    • If the Dialog is closed, we open the Dialog window by calling the $(dialog_id).dialog('open') method, and change the label of the Button to “Close window” using the $(button_id).button('option') method.
    • If it’s already open, we do the reverse using the same option method on Button and the $(dialog_id).dialog('close') method to close the Dialog box.
    • We’ve also taken advantage of another Dialog option, which is called autoOpen. When set to true, it allows the Dialog window to open automatically when initialized. If not, then the Dialog window can only be opened by calling the $(dialog_id).dialog('open') method, which is what the button does.
    Functional buttons and checkboxes bro

    Functional buttons and checkboxes bro Step 5: Adding Functionality to our Dialog Window

    Now that the Dialog window is up and running, let’s add the functionality to it to create new Dialog windows. First off, add some buttons to our Dialog. Thankfully, jQuery UI has the functionality to add buttons to any Dialog box and customize what they do when clicked. To do so, modify the initialization code by adding a buttons parameter to it:

    $('#dialog_window_1').dialog({
    	width: 'auto',
    	height: 'auto',
    	autoOpen : false,
    	buttons: [
    		{
    			text: 'Create',
    			click: function() {
    				alert('Yay, clicked the button!');
    			}
    		}
    	]
    });
    

    As you can see from the sample code, we added the “Create” button by simply adding a buttons option to the initialization code. The button option is an array of JSON objects in the following format:

    {
    	text: 'Name of your button',
    	click: function () {
    		//Add stuff here to do when the button is clicked
    	}
    }
    

    To add more buttons, you can merely add more JSON objects in the same format to the buttons array. When you refresh the page, it should look something like so:

    Yay, clicked the button!

    Yay, clicked the button!

    Now we’ll add some functionality to our button. Remove the alert('Yay, clicked the button!'); line and replace it with the following:

    //get the total number of existing dialog windows plus one (1)
    var div_count = $('.dialog_window').length + 1;
    
    //generate a unique id based on the total number
    var div_id = 'dialog_window_' + div_count;
    
    //get the title of the new window from our form, as well as the content
    var div_title = $('#new_window_title').val();
    var div_content = $('#new_window_content').val();
    
    //generate a buttons array based on which ones of our checkboxes are checked
    var buttons = new Array();
    if( $('#alertbutton').is(':checked') ) {
    	buttons.push({
    		text: 'ALERT',
    		click: function() {
    			alert('ALERTING from Dialog Widnow: ' + div_title);
    		}
    	});
    }
    
    if( $('#closebutton').is(':checked') ) {
    	buttons.push({
    		text: 'CLOSE',
    		click: function() {
    			$('#' + div_id).dialog('close');
    		}
    	});
    }
    
    //append the dialog window HTML to the body
    $('body').append('<div class="dialog_window" id="' + div_id + '">' + div_content + '</div>');
    
    //initialize our new dialog
    var dialog = $('#' + div_id).dialog({
    	width: 'auto',
    	height: 'auto',
    	title : div_title,
    	autoOpen : true,
    	buttons: buttons
    });
    

    Here’s a step-by-step of the code we just added above:

    • First, get the total number of Dialog windows on the site.
    • From this, generate a new unique id that will be used for the new Dialog window.
    • Get the window Title and window Content values from the “Create a new Dialog window” form.
    • Check whether the ALERT and CLOSE checkboxes are checked. If they are, create a JSON object, following the button format from above, and push it into a buttons array.
    • Generate and append the Dialog window’s HTML inside the page’s <body> tag
    • Lastly, initialize the new Dialog window using the initialization code like the one used on the original Dialog window.

    Play around with it and try different combinations for the buttons. Here’s a screenshot with all the possible combinations:

    Lorem ipsum dolor sit amet

    Lorem ipsum dolor sit amet

    Now that we’re able to create mutiple windows, let’s add some minimize-maximize functionality!

    Step 6: Making the Dialog Windows “Minimizable” and “Maximizable”

    Unfortunately, jQuery UI doesn’t have built-in minimize and maximize methods, but we can easily add it by overriding some stuff on the initialization process of the jQuery UI Dialog prototype. Essentially, we’re going to add some post-initialization code which will automatically create a “minimized state”, add a minimize icon for the Dialog windows, as well as add a function that “maximizes” the minimized window when the minimized state is clicked.

    Let’s start off by adding the CSS to style the buttons and the minimized state:

    #dialog_window_minimized_container {
    	position: fixed;
    	bottom: 0px;
    	left: 0px;
    }
    
    .dialog_window_minimized {
    	float: left;
    	padding: 5px 10px;
    	font-size: 12px;
    	cursor: pointer;
    	margin-right: 2px;
    	display: none;
    }
    
    .dialog_window_minimized .ui-icon {
    	display: inline-block !important;
    	position: relative;
    	top: 3px;
    	cursor: pointer;
    }
    
    .ui-dialog .ui-dialog-titlebar-minimize {
    	height: 18px;
    	width: 19px;
    	padding: 1px;
    	position: absolute;
    	right: 23px;
    	top: 9px;
    }
    
    .ui-dialog .ui-dialog-titlebar-minimize .ui-icon {
    	display: block;
    	margin: 1px;
    }
    
    .ui-dialog .ui-dialog-titlebar-minimize:hover, .ui-dialog .ui-dialog-titlebar-minimize:focus {
    	padding: 0;
    }
    

    We’ll also need to add a “minimized state” container, where we’ll append all the minimized windows. Add this inside the <body> tag:

    <div id="dialog_window_minimized_container"></div>
    

    Now, add this JavaScript codeblock after the place where the jQuery UI library is loaded. This is important as it won’t work if it’s before the library is loaded.

    <script>
    var _init = $.ui.dialog.prototype._init;
    $.ui.dialog.prototype._init = function() {
    	//Run the original initialization code
    	_init.apply(this, arguments);
    
    	//set some variables for use later
    	var dialog_element = this;
    	var dialog_id = this.uiDialogTitlebar.next().attr('id');
    
    	//append our minimize icon
    	this.uiDialogTitlebar.append('<a href="#" id="' + dialog_id +
    	'-minbutton" class="ui-dialog-titlebar-minimize ui-corner-all">'+
    	'<span class="ui-icon ui-icon-minusthick"></span></a>');
    
    	//append our minimized state
    	$('#dialog_window_minimized_container').append(
    		'<div class="dialog_window_minimized ui-widget ui-state-default ui-corner-all" id="' +
    		dialog_id + '_minimized">' + this.uiDialogTitlebar.find('.ui-dialog-title').text() +
    		'<span class="ui-icon ui-icon-newwin"></div>');
    
    	//create a hover event for the minimize button so that it looks good
    	$('#' + dialog_id + '-minbutton').hover(function() {
    		$(this).addClass('ui-state-hover');
    	}, function() {
    		$(this).removeClass('ui-state-hover');
    	}).click(function() {
    		//add a click event as well to do our "minimalization" of the window
    		dialog_element.close();
    		$('#' + dialog_id + '_minimized').show();
    	});
    
    	//create another click event that maximizes our minimized window
    	$('#' + dialog_id + '_minimized').click(function() {
    		$(this).hide();
    		dialog_element.open();
    	});
    };
    </script>
    

    Here’s what this code does:

    • Let the original jQuery UI Dialog initialization code run via _init.apply(this, arguments);
    • Append the minimize icon to the Dialog Box’s Title Bar
    • Append the minimized state HTML inside the #dialog_window_minimized_container <div>
    • Add a hover event to the minimize icon so that it’ll get the ui-state-hover class when the mouse is hovered over it, which will add the “background-color changing” effect that we see.
    • Create a click event for it that closes the Dialog window and shows the minimized state
    • Finally, create another click event for the minimized state that hides itself and re-opens the Dialog window

    And now, our windows-like interface is complete!

    windows-like interface, hurrah!

    windows-like interface, hurrah! Conclusion

    In this article, we’ve demonstrated how easy it is to create a beautiful and highly-functional user interface using nothing but jQuery and jQuery UI. By now, you should already know how to:

    • Download and setup the jQuery UI library for your project
    • Use jQuery UI’s Dialog, Button and Buttonset component.
    • Create Dialog boxes both statically and dynamically using information from any source
    • Dynamically create different Dialog Buttons with each new Dialog box.
    • Adding custom functionality to jQuery UI’s Dialog e.g. minimize and maximize functionality.
    • Customize jQuery UI’s initialization process

    It’s worth taking note that there are a whole lot more components that you can leverage through jQuery UI. It’s definitely a great way to build incredible user interfaces quickly and easily. Hopefully this article has proven to you that jQuery UI is an essential tool in any developer’s toolkit.

    Have you used jQuery UI in the past or planning to use it for a future project? Let us know in the comments below and thank you so much for reading!


  • Permalink for 'Best of Tuts+ in November'

    Best of Tuts+ in November

    Posted: December 3rd, 2011, 8:37am MST by David Appleyard

    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!

    Huge Improvements to Tuts+ Premium

    As many of you know, Tuts+ is accompanied by an online educational membership called Tuts+ Premium. We’re very excited to announce that the membership has received a huge upgrade, including a new library of courses, 27 top-selling educational eBooks, member forums, and a completely redesigned UI.

    You can check out all the changes here, and find out about all the fantastic new content available!

    Our new premium website is a drastic improvement over the old system. It includes a slick and polished user interface and presents all of our tutorials the way that you would expect, from within your browser. We are now providing courses and ebooks from within Tuts+ Premium to make it even more valuable. So what are you waiting for? Head over to the new Tuts+ Premium site and let us know what you think.

    Take a Tour of Tuts+ Premium

      Psdtuts+ — Photoshop Tutorials
      • Create Detailed Vintage Typography with Illustrator and Photoshop Create Detailed Vintage Typography with Illustrator and Photoshop

        In this tutorial we will demonstrate how to customize a typeface in Illustrator and then use Photoshop to create a stunning vintage detailed typographic design. Let’s get started!

        Visit Article

      • Realistic Portrait Retouching With Photoshop Realistic Portrait Retouching With Photoshop

        Today’s designers and photographers need to have a varied skill set that sets them apart from the pack. One common skill that both can use is portrait photography retouching. This tutorial will make you a more effective retoucher and help keep your portraits looking clean and realistic. Subtlety is – going too far will only make the results noticeable. The best comment you can get after presenting a final image is "I didn’t even notice you did that". Let’s get started!

        Visit Article

      • How to Paint Clouds With Photoshop How to Paint Clouds With Photoshop

        Photoshop is an excellent tool for manipulating photographs but it can also be used as a means to create stunning digital art. This tutorial is part of a 25-part video tutorial series demonstrating everything you will need to know to start producing digital art in Photoshop. Digital Art for Beginners, by Adobe Certified Expert and Instructor, Martin Perhiniak will begin by teaching you how to draw in Photoshop. At the conclusion of this series you will know all you need to produce your own concept art and matte paintings in Photoshop.

        Visit Article

      • Nettuts+ — Web Development Tutorials
      • How to Create a Sublime Text 2 Plugin How to Create a Sublime Text 2 Plugin

        Sublime Text 2 is a highly customizable text editor that has been increasingly capturing the attention of coders looking for a tool that is powerful, fast and modern. Today, we’re going to recreate my popular Sublime plugin that sends CSS through the Nettuts+ Prefixr API for easy cross-browser CSS.

        Visit Article

      • a Free Tuts+ Premium Course Days to Learn HTML and CSS: a Free Tuts+ Premium Course

        If you’ve ever wanted to learn how to build websites and web apps, HTML and CSS are the first skills you should learn. They are so fundamental that we believe everyone has the right to learn these skills for free.

        Visit Article

      • Dig into Dojo Dig into Dojo

        Maybe you saw that tweet: “jQuery is a gateway drug. It leads to full-on JavaScript usage.” Part of that addiction, I contend, is learning other JavaScript frameworks. And that’s what this four-part series on the incredible Dojo Toolkit is all about: taking you to the next level of your JavaScript addiction.

        Visit Article

      • Vectortuts+ — Illustrator Tutorials
      • How to Create a Vector Stamp Set in Illustrator How to Create a Vector Stamp Set in Illustrator

        In the following tutorial you will learn how to create a vintage, vector stamp set in Adobe Illustrator. Learn how to build a stamp illustration, shape by shape. We’ll construct the stamp border vector shape, highlight the edges, create the branding, and give the vector postage stamp a vintage texture, and final illustrator stamp effect. Let’s get started with making this vector stamp in Illustrator and then transform this into a vector stamp set.

        Visit Article

      • Create a Vector Bamboo Forest with Blends, Brushes and Profiles Create a Vector Bamboo Forest with Blends, Brushes and Profiles

        In today’s tutorial you’ll learn how to create a bamboo vector illustration with the help of custom art and pattern brushes, blends and profiles on strokes in Adobe Illustrator CS5. Vector bamboo is an excellent element to use in your work to give a classic Japanese fine art print feel, for use as bamboo forest art background in a larger illustration, and to make your vector pictures stand out with stylish bamboo art. So let’s jump straight into it!

        Visit Article

      • Floral Borders, Corners, and Frames Massive Collection of Vintage Vector Graphics: Floral Borders, Corners, and Frames

        Welcome design rockstar, today you’re in for a real treat. We have a massive collection of vector graphics compiled for free download today. We’ve assembled vintage vector floral graphics that have antique floral borders, classic ornate corners, and decorative frames.

        Visit Article

      • Webdesigntuts+ — Web Design Tutorials
      • Bring Your Forms Up to Date With CSS3 and HTML5 Validation Bring Your Forms Up to Date With CSS3 and HTML5 Validation

        Let’s look at how to create a functional form which validates users’ data, client-side. With that done, we’ll cover prettying it up using CSS, including some CSS3!

        Visit Article

      • Design a Clean Launch Email for a Mobile App Design a Clean Launch Email for a Mobile App

        During this tutorial we’ll be using Adobe Photoshop to create a unique and clean email, announcing the launch of a new mobile app. We’ll look at using smart objects, clipping masks, warping text, and even examine the psychology of our users.

        Visit Article

      • Financial Best Practices for Web Design Freelancers Financial Best Practices for Web Design Freelancers

        A lot of web designers start their careers as employees for larger design firms. However, it seems inevitable that most designers will at least consider going out on their own as freelancers, either for side jobs or full time. One major key to any successful freelancing career, though, is to stay on top of your finances.

        Visit Article

      • Phototuts+ — Photography Tutorials
      • 50 Amazing Animal Photos Amazing Animal Photos

        Animals are, without a shadow of a doubt, a fascinating photography subject. They’re at their most intriguing when they’re unpredictable and wild, allowing you to capture something of their very nature. This collection is a look at some outstanding shots of animals, of every kind, in the hope that it inspires and encourages you in your endeavors to immortalize something of the creatures with which we share our existence.

        Visit Article

      • The Best Way To Learn Sports Photography The Best Way To Learn Sports Photography

        Whether you’re a sports fan or not, it’s hard to deny the huge popularity of sports in modern culture. In today’s tutorial, instead of giving you tips about directly shooting sports, we’re focusing on giving you tips on learning how to shoot it. We hope you enjoy this new approach.

        Visit Article

      • The Camera Swap Survival Guide The Camera Swap Survival Guide

        In photography circles, you run into two types of people. Those who love their gear and those who would just as soon forget about. I love making photographs, but I also love cameras and the other gear used in the process. Therefore, I love camera swaps and flea markets. The variety of tools available for our craft is astounding and frankly overwhelming. But I’m here to help. I’ve been going to swaps for 12 years. I’ve been ripped off more times than I care to admit, but after all this time, I’m finding more treasure than fool’s gold. So today, I’ll guide you through the jungle that is the camera swap.

        Visit Article

      • Cgtuts+ — Computer Graphics Tutorials
      • Facial Animation With Morph Targets In Cinema 4D, Part 1 – Cg Premium Content Facial Animation With Morph Targets In Cinema 4D, Part 1 – Cg Premium Content

        In this new two part Premium tutorial, Aleksey Voznesenski will give you an introduction to mesh animation in Cinema 4D, in this case a face with the use of the pose morph tag. We’ll also actually model the character, add materials, do some lighting, Faking GI is always fun, and then animate the little bugger.

        Visit Article

      • The Abandoned Lobby in Maya and Mentalray, A Lighting & Rendering Overview Making Of: The Abandoned Lobby in Maya and Mentalray, A Lighting & Rendering Overview

        In this overview tutorial, author Pratik Gulati will give you valuable insight into Lighting and Rendering a scene in Maya using Mentalray. Using his “Abandoned Backyard Lobby” image as a basis, Pratik will discuss how he approached the Lighting setup and walk you through the render settings for achieving a very realistically lit interior scene with Mentalray.

        Visit Article

      • Creating A Simple 3D Puzzle In Maya Quick Tip: Creating A Simple 3D Puzzle In Maya

        In this quick tip, author Abed Ibrahim will show you a great way to create a simple 3D puzzle in Maya. Although simple in approach, this valuable technique can be used in a variety of projects, ranging from very simple puzzles to extremely complex scenes, or even animations.

        Visit Article

      • Aetuts+ — After Effects Tutorials
      • Design A Fantastic Floating Card Logo Reveal – AE Premium Design A Fantastic Floating Card Logo Reveal – AE Premium

        In this tutorial we’ll break down a project I created called Motion Cards. We’ll create 3 scene’s in which we’ll animate some falling customizable placeholders that will be re purposed using Trapcode Particular for a dynamic logo reveal.

        Visit Article

      • Regenerate Like A “Time Lord” From Dr. Who Regenerate Like A “Time Lord” From Dr. Who

        In this tutorial, we’ll be creating a regeneration effect, inspired by the Doctor Who TV show. I say inspired by, because it’s not screen-accurate, but we’ll be using AE’s built-in tools, alongside some stock footage, VCP’s Optical Flares and Trapcode Particular to pull off a pretty convincing regeneration.

        Visit Article

      • An Apple Box At Its Core An Apple Box At Its Core

        In today’s video, I’ll talk about the Apple Box… a rectangular multi-purpose block used on production sets dating back to practically the beginning of film. This video is for exposure more than anything. A year ago, I didn’t even realize those boxes had a name, and now I end up pretty much using them at least once on every shoot I do. Hope you enjoy it. )

        Visit Article

      • Audiotuts+ — Audio & Production Tutorials
      • Why You Should Use Metering Tools while Mixing and Mastering Why You Should Use Metering Tools while Mixing and Mastering

        Last AES convention I met a manufacturing rep for a very prestigious equipment company. He was demoing a piece of equipment for me, showing me all the great knobs and buttons that it had to offer. Then he said something along the lines of, ’We don’t include a screen for these things since you’re supposed to mix with your ears.” That’s when I took my exit stage left. I think imposing a viewpoint like that is just plain wrong.

        Obviously, you’re supposed to mix with your ears, but I don’t think looking at meters is going to destroy your mix.

        Visit Article

      • Adding Flavor to Chords - Adding Flavor to Chords -” Sixth Chords -” Basix

        Today we are going to cover how to add some flavor to your chords and compositions using sixths in both major and minor. Just like the 7ths chord tutorial, we will approach this chord concept from the ground up and look it from all possible angles. If you have heard of these types of chords but never knew exactly how they were constructed then this tutorial is for you. We will cover everything from basic structure to different voicings of the chords and try to apply them in a creative context. The sixth chords are waiting, you ready?

        Visit Article

      • 20 Podcasts that Musicians Should Subscribe To (And Why!) Podcasts that Musicians Should Subscribe To (And Why!)

        Rather than listening to music as I drive, shave and garden, I regularly listen to podcasts. That way Im not just being entertained, but educated as well. In this post we introduce you to the Top 20 podcasts musicians should subscribe to.

        A podcast is like a radio show, only distributed via RSS over the internet. Some are professionally produced, but many are done by amateurs. Most are about a particular interest or topic. And there are a ton of them on music and recording -” some featuring indie music, others exploring music technology, and many explaining techniques for playing and recording music. In this article we’ll focus on the podcasts that teach you about producing music, and not the ones that help you discover new music. Maybe we’ll cover those in a future post.

        Visit Article

      • Activetuts+ — Flash, Flex & ActionScript Tutorials
      • Introduction TimelineLite Ultimate Starter Guide: Introduction

        TimelineLite is the ultimate tool for creating elaborate and precise sequences of scripted animation. It is an integral part of the GreenSock Tweening Platform that allows you to make the most of TweenLite and TweenMax. This series of screencasts will walk you step by step through everything you need to know to take your AS3 tweening skills to the next level.

        Visit Article

      • Getting Started With Scoreoid Getting Started With Scoreoid

        Games are becoming ever more popular, especially casual games on mobile devices and tablets. In these games, the importance of leaderboards is multiplied – and game developers need a simple cross-platform solution for this. In this tutorial we will cover Scoreoid and how it can help you with game development.

        Visit Article

      • Effectively Organize Your Game’s Development With a Game Design Document Effectively Organize Your Game’s Development With a Game Design Document

        Have you ever dived right in to developing a game, but found yourself having to constantly change aspects of the design or the gameplay due to a lack of planning? You should consider using a game design document: a guiding vision of the game as a whole, pulling together ideas and plans for the design, development, and business sides of your game.

        Visit Article

      • Wptuts+ — WordPress Tutorials
      • 5 Cardinal Sins of WordPress Theme Development Cardinal Sins of WordPress Theme Development

        We talk alot on this site about tips and tricks for getting what you want out of WordPress… but today we’re going to take a step back from the technical stuff to look at some practices, bad habits, and coding faux pas that would be better left in our past. So, forgive the heavy-handed post title (haha!), we’re about talk bring up 5 surprisingly common practices that are blemishes on the platform.

        Visit Article

      • Using the Framework as a Boiler Plate DIY WordPress Framework Part 4: Using the Framework as a Boiler Plate

        Last time we used our framework as a child theme, creating a totally new theme that depends on the framework. Today we’re going to use our framework as a boilerplate, copying the folder and making edits right to it.

        Visit Article

      • November 2011 WordPress Monthly News: November 2011

        For some, WordPress is a livelihood whereas, for others, it’s just for fun. Nonetheless, anyone involved with WordPress needs to stay on track with the latest developments in the blogging world. This is our monthly article covering the latest developments in the WordPress world from news to the latest new kick-ass themes on our marketplaces.

        Visit Article

      • Mobiletuts+ — Mobile Development Tutorials
      • jQuery Mobile 1.0 jQuery Mobile 1.0

        The official release of jQuery Mobile 1.0 was recently announced, and this tutorial will provide you with an overview of how this popular framework can assist you in your cross-platform and web based app development!

        Visit Article

      • Building a Caterpillar Game with Cocos2D Building a Caterpillar Game with Cocos2D

        In this series, we will be recreating the popular Atari game Centipede using the Cocos2D game engine for iOS. Centipede was originally developed for Atari and released on the Arcade in 1980. Since then, it has been ported to just about every platform imaginable. For our purposes, we will be calling the game Caterpillar.

        Visit Article

      • Using the Text to Speech Engine Android SDK: Using the Text to Speech Engine

        This tutorial will teach you to give your applications a voice with the Android SDK text to speech engine!

        Visit Article

      • FreelanceSwitch — Articles and Resources for Freelancers
      • 10 Free Apps for Working with Video 10 Free Apps for Working with Video

        Video has become a must-have for every website or blog aiming to enhance its presence online. It’s a common practice that video-related orders are often assigned to freelancers, and these are not only simple video editing tasks, but the preparation of how-to’s, demos, screencasts, video embedding and distribution as well.

        Here is a roundup of the most popular video software and services recommended for freelancers’ everyday use.

        Visit Article

      • 30 Top Facebook Apps for Business 30 Top Facebook Apps for Business

        Facebook is a good place to communicate with friends and get new job offers. Freelancers should not miss an employment opportunity on Facebook. The social network app section is a real treasure box with multiple handy applications.

        These are some of the best Facebook applications that help freelances boost their productivity, enhance their business pages, show off their portfolio and attract new contacts. Since many freelancers work with social media as experts, account managers and analysts, the list below has both apps for personal profiles and Facebook pages.

        Visit Article

      • The Latest Google Update is Fantastic News for Freelance Writers The Latest Google Update is Fantastic News for Freelance Writers

        On November 3, 2011 Google published a new article on their blog informing readers that fresh new content is now being seen as highly valuable on their blog or website. This “freshness update” is a new addition to Google’s “Caffeine web indexing system”.

        Now blog owners who update their sites regularly will be rewarded with a higher search engine ranking. Let’s look at how freelance writers can put this new update to use in their business.

        Visit Article


  • Permalink for 'Dig into Dojo: NodeList Modules and Ajax'

    Dig into Dojo: NodeList Modules and Ajax

    Posted: December 2nd, 2011, 11:00am MST by Andrew Burgess

    Maybe you saw that tweet: ”jQuery is a gateway drug. It leads to full-on JavaScript usage.” Part of that addiction, I contend, is learning other JavaScript frameworks. And that’s what this four-part series on the incredible Dojo Toolkit is all about: taking you to the next level of your JavaScript addiction.

    In this second episode, we’ll be discussing loading modules and using some of the DOM-enhancing modules.

    Prefer a Video?

    Remember, for premium members, there’s a screencast available. Besides covering everything in this tutorial, I also cover Dojo’s AJAX and cross-domain AJAX methods. So, sign in to get these screencasts and all the other incredible Tuts+ Premium screencasts, tutorials, and resources.

    You’ll recall that there’s a lot more to Dojo than comes in the Dojo Base file that we loaded from the Google CDN in episode 1. There’s a whole lot more, in fact. So, how do we harness this whole lot more?

    Well, the rest of Dojo is available in modules. We can load in a module to get its functionality. Behind the scenes, every module is a JavaScript file of its own. Basically, The string you use you refer to the module is its path name (minus the “.js”).

    To get a better idea of how this works, download the Dojo Toolkit release. After you unzip this rather hefty file, you’ll see this:

    The Dojo folder structure

    To load able/baker/charlie.js, we use 'able.baker.charlie'. Couldn’t be easier, right?

    Notice, there’s a folder for each of the three members of the Dojo trinity. By default, this folder (here, called “dojo-release-1.6.1”) is the root for all our module paths.

    Take a look inside the “dojo” folder. You’ll see the file dojo.js, which is the minified Dojo base file that we’ve been loading from Google. Notice further down, there’s a file called NodeList-traverse.js. If we wanted to use the functionality that file provides (and we will, in this tutorial), we would get it using the module path 'dojo.NodeList-traverse' (yes, I know you don’t know where we’ll use this string yet, but stick with me). Now, see that folder called io? If we wanted to load the script.js file in there, we’d use 'dojo.script.io'. Getting the hang of this? Basically, to load able/baker/charlie.js, we use 'able.baker.charlie'. Couldn’t be easier, right?

    So, where are we using these strings, exactly? We can pass these module path strings to the dojo.require function. This will load that file in, via an XHR request. Once that file loads, you’ll be able to use whatever it brought to the table.

    I should note that you don’t want to try to use the pieces you’re loading before they’re actually loaded. To avoid this, you should use dojo.ready, which is just an alias for dojo.addOnLoad. Any function you pass to it will run once the code is loaded. It’s a lot like jQuery’s $(document).ready() function. In this tutorial, you can use your browser’s JavaScript console to try out all these snippets, so we won’t actually have a dojo.ready call here.

    So, let’s start looking at some modules. I’ll note here that we won’t necessarily be looking at all the methods each of these modules has to offer; we’ll look at ones you’ll find most useful as you’re learning Dojo.

    Oh, one more thing: if you’re following along, you can use this HTML to get the same results as I show:

    <html>
    <head>
      <title> Dig into Dojo, part 2 </title>
      <style>
        body {
          font: 16px/1.5 helvetica;
          color: #474747;
        }
    
        #test {
          border: 1px solid #ccc;
          background: #ececec;
          width: 250;
          padding: 20px;
          text-align: center;
        }
        .active {
          background: maroon;
        }
      </style>
    </head>
    <body>
      <div id='content'>
        <h1> Dig into Dojo Episode 2</h1>
    
        <p id='test'> Dojo Tutorial </p>
    
        <div> An Unsemantic Div </div>
    
        <ul>
          <li> A Child! 1 </li>
          <li> A Child! 2 </li>
          <li> A Child! 3 </li>
          <li> A Child! 4 </li>
        </ul>
    
        <p> Another Paragraph </p>
      </div>
    
      <script src='http://ajax.googleapis.com/ajax/libs/dojo/1.6.1/dojo/dojo.xd.js.uncompressed.js'></script>
      <script>
      </script>
    </body>
    </html>
    dojo.require('dojo.NodeList-data');

    Let’s start with a relatively simple one: the NodeList data methods. To load them:

    dojo.require('dojo.NodeList-data');

    To cement the idea of these paths, go look for the file you just loaded. You should find it in [dojo-download]/dojo/NodeList-data.js. Once you’re a little more familiar with Dojo, I’d recommend looking through a few modules to see how they’re built.

    Note: Even though we downloaded Dojo, we’re still using the Google CDN version, which means any files we require are being loaded from there. If you want to use your local copy, you’ll have to fire up Apache (or otherwise), because the files are loaded via XHR.

    So, dojo.NodeList-data adds two NodeList methods: data, and removeData. Let’s see how this works:

    var ps = dojo.query('p');
    
    ps.data('key', 'value');
    ps.data('key'); // ['value', 'value']

    Setting and getting data is a pretty straightforward process: pass a key (always a string) and a value (any JavaScript type) to set the data, and just pass the key to get it back. You’ll notice that when getting, data returns an array. This is because NodeLists are arrays, and may have more than one node. Therefore, we’re returning the value for every node. data will always return an array, even if there is only one item in the NodeList.

    If you pass data no parameters, it will return an array with an object for each node in the NodeList: each object will have the appropriate keys and values. See here:

    dojo.query('#test').data('handle', function () { /* action! */ });
    
    dojo.query('p').at(0).data('name', 'Dojo Toolkit');
    dojo.query('p').at(1).data('age', 1.6);
    
    dojo.query('p').data; // returns: [ { handle: function () { /* action! */}, name: 'Dojo Toolkit' }, { age: 1.6 }]

    Now, about removeData: pass it a key and it will remove that key and value from every node. Pass it no parameters, and it removes everything:

    // assuming the above:
    var ps = dojo.query('p');
    
    ps.removeData();
    ps.data(); // [ {}, {} ]

    Of course, data does not persist across page refreshes.

    dojo.require('NodeList-fx');

    If you’re familiar with jQuery’s fadeIn and fadeOut methods, you’ll think you know these … and you’ll be wrong.

    Next up is a collection of animation methods. Animation with JavaScript functions can be somewhat challenging, so we won’t be covering animation very much at all in this series, but we’ll look at a couple basic methods here.

    I should note that this module primarily provides NodeList methods to many of the dojo.* methods in the dojo.fx module. We won’t be discussing those specifically, but much of this applies to those methods as well.

    First, there are the mandatory fadeIn and fadeOut. If you’re familiar with jQuery’s fadeIn and fadeOut methods, you’ll think you know these … and you’ll be wrong. There are some interesting differences we should cover.

    These methods—and the others in this module—are actually wrapper methods for some of Dojo’s incredibly complex animation functionality. The first difference is that calling one of these methods doesn’t automatically run the animation; it returns a dojo.Animation object. Then, to run the animation, you call the dojo.Animation object’s play method. Alternately, you can pass auto: true as a key/value in the options object you might pass to the animation method.

    Other options you can pass to an animation method include delay, duration, and easing, among others. You can also include functions that run before or after certain events: beforeBegin, onBegin, onEnd, onPlay, and onAnimate.

    A good example of all this behaviour is making the Dojo fadeOut function work like the jQuery version. Here’s what we’d do to make our first paragraph fade out over 2 seconds, with each library:

    jQuery('#test').fadeOut(2000);
    
    dojo.query('#test').fadeOut({ auto: true, duration: 2000, onEnd: function (node) { dojo.style(node, 'display', 'none'); } });
    
    // alternately:
    
    dojo.query('#test').fadeOut({ duration: 2000, onEnd: function (node) { dojo.style(node, 'display', 'none'); } }).play();

    All this goes for the fadeIn, wipeOut, and wipeIn effects as well.

    Then, there’s the animateProperty method. This is a really handy way to change the CSS properties of an object, animating them while doing it. You’ll pass an options object to that method. Besides taking all the properties that fadeOut and friends take (delay, duration, onEnd, etc.), this method takes a properties property (how meta!), with your CSS values. Of course, this returns a dojo.Animation object, so you pretty much call the play method, or use the auto: true property.

    Here are a couple of examples:

    This line will fade the background colour of our element to red over 2 seconds:

    dojo.query('#test').animateProperty({ duration: 2000, properties: { backgroundColor: 'red' } }).play();

    This line will wait 4 seconds, and then widen our element to 1200px, and alert “done” when finished. Notice that first we load the dojo.fx.easing module first. This is just a set of easing functions that you can use as I have below wherever easing is accepted.

    dojo.require('dojo.fx.easing');
    dojo.query('#test').animateProperty({ delay: 4000, properties: { width: 1200  }, easing: dojo.fx.easing.bounceOut, onEnd: function () { alert('done'); }, auto: true });

    One more. This shows a more advanced use of the CSS properties: instead of just putting where it should end, you can also define where the property should start. Of course, if that’s not the current value of the property, it won’t be animated to the starting point.

    dojo.query('#test').animateProperty({
    	properties: {
    		fontSize:        { start: 20,    end: 120 },
    		backgroundColor: { start: 'red', end: 'blue' },
    		width:           { start: 100,   end: 1200 }
    	},
    	easing: dojo.fx.easing.quintIn,
    	duration: 10000
    }).play();

    Of course, animation is a hydra that we could spend a long time slaying, so we’ll leave it at that.

    dojo.require('dojo.NodeList-manipulate');

    We discussed several methods for manipulating DOM elements in episode 1 of this series, but loading the dojo.NodeList-manipulate module gives us a few more methods to work with. Let’s check ‘em out.

    First up, there’s the innerHTML and text methods. They do very much what you’d expect: set the HTML or text within the element to whatever you pass in.

    // <p id='test'> Dojo Tutorial </p>
    dojo.query('#test').innerHTML('<strong> Unicorns! </strong>');
    // <p id='test'><strong> Unicorns! </strong></p>
    
    // <p id='test'> Dojo Tutorial </p>
    dojo.query('#test').text('<strong> Unicorns! </strong>');
    // <p id='test'>&amp;lt;strong> Unicorns! &amp;lt;/strong></p>

    You can also pass actual DOM nodes to innerHTML.

    Next, a warm round of applause for append and prepend, and their cousins appendTo and prependTo. These are very similar to innerHTML, except they don’t get rid of what is currently in the node(s) in question.

    // <p id='test'> Dojo Tutorial </p>
    dojo.query('#test').append('<strong> Unicorns! </strong>');
    // <p id='test'> Dojo Tutorial <strong> Unicorns! </strong></p>
    
    // <p id='test'> Dojo Tutorial </p>
    dojo.query('#test').prepend(dojo.query('p').at(1));
    // <p id='test'><p>Another Paragraph</p> Dojo Tutorial </p>

    When you’re moving DOM nodes, as in that last example, it might be easier to start with the node you want to move. Then, you can use appendTo or prependTo, passing in a selector, to tell Dojo where to put the node:

    dojo.query('h1').appendTo('p');

    This will append the <h1> on our example page to the two paragraphs on the page. Notice that the &h1> will be removed from its original location, and cloned for each paragraph.

    Our next act is after, before, insertAfter, and insertBefore. You’ll find these quite similar to the append, et al methods; it’s just that they put the content before or after the element in question. A code snippet is worth a thousand words, here:

    // <p id='test'> Dojo Tutorial </p>
    dojo.query('#test').after('<em> NETTUTS+ </em>');
    // <p id='test'> Dojo Tutorial </p><em> NETTUTS+ </em>
    
    // <p> Another Paragraph </p>
    dojo.query('h1').insertBefore(dojo.query('p:last-of-type'));
    // <h1> Intro to Dojo Episode 2</h1> <p> Another Paragraph </p> 

    I think you’re starting to get it.

    Now, the NodeList methods wrap, wrapAll, and wrapInner. These are pretty straightforward:

    wrap will wrap the items in the NodeList with the HTML string you pass in:

    dojo.query('p').wrap('<strong>'); // all paragraphs will be wrapped in <strong>, as unsemantic as that is

    wrapAll will move all the nodes in your NodeList to where the first one is, and wrap them all in the HTML string you pass in:

    dojo.query('p').wrapApp('<div class='active'></div>'); // if you add the closing tag, Dojo will figure out what you mean

    wrapInner will wrap everything inside the nodes in your NodeList, essentially making it the only child node of each node:

    dojo.query('body').wrapInner('<div id='main'>');
    dojo.require('dojo.NodeList-traverse');

    We saw a very few select methods for moving around in episode 1, but—wait for it‐there’s more if you dojo.require('dojo.NodeList-traverse').

    I know you’re excited to see these methods, but a note first: all these NodeList methods change the NodeList in some way. To get back to the original NodeList, use the end method, just like jQuery.

    children: Captures the child nodes of the nodes in your NodeList; optionally, takes a selector to filter those kids:

    	dojo.query('ul').children(); // four <li>s

    parent: Captures the parent node of the nodes in your NodeList. There’s also a parents (plural) method that returns the parent, grandparent, etc. Both take filtering selectors.

    	dojo.query('li').parent(); // [<ul>]
    	dojo.query('li').parents(); // [<ul>, <div id='content'>, <body>, <html>]

    siblings: Gets the siblings of each node. Can be filtered.

    	dojo.query('#test').siblings(); // [<h1>, <div>, <ul>, <p>]

    next, prev, nextAll, and prevail: These methods are sub-methods, if you will, of siblings: they all return a certain group of siblings. next returns the sibling node after each node in the NodeList; prev returns the one before each node. nextAll and prevAll return all the next or previous siblings of each node in the NodeList.

    dojo.query('#test').next(); // [<div>]
    dojo.query('p').prev(); // [ <h1>, <ul> ]
    dojo.query('li').prevAll(); [<li> A Child! 1 </li>, <li> A Child! 2 </li>, <li> A Child! 3 </li>]

    first / last: Very simply, these methods return the first and last methods of the NodeList:

    dojo.query('li').first(); //[<li> A Child! 1 </li>]
    dojo.query('li').last(); //[<li> A Child! 4 </li>]

    even / odd: Get your odd or even nodes from the NodeList here:

    dojo.query('li').even(); // [<li> A Child! 2 </li>, <li> A Child! 4 </li> ]
    dojo.query('li').odd(); // [<li> A Child! 1 </li>, <li> A Child! 3 </li> ]

    And there you have it: four helpful modules for working with the DOM. Of course, there are dozens of dozens of other modules available, many more than I could cover in an introductory series. I encourage you to dig around in that dojo directory in the toolkit download and see what you can find.

    Conclusion

    Now that you’re familiar with a couple of Dojo modules, I’d recommend you poke around inside the modules themselves to see how they add their functionality. While I won’t be able to explain exactly how modules are created in this series, what you see in there might be a good jumping-off point for some of your own research.

    Thanks for sticking around, and keep your eyes out for Episode 3, where we’ll take a look at Dijit.


  • Permalink for 'Wrangling with the Facebook Graph API'

    Wrangling with the Facebook Graph API

    Posted: December 1st, 2011, 11:00am MST by Nikko Bautista

    Have you ever wanted to learn how to make your applications more social with Facebook? It’s much easier than you think!

    In this tutorial, we’ll be building an application that reads and publishes data to and from Facebook using Facebook’s Graph API. Interested? Join me after the jump!

    A Short Introduction to the Open Graph Protocol Facebook Open Graph

    Open Graph Protocol

    Image courtesy of [ogp.me]

    The Open Graph protocol enables any web page to become a rich object in a social graph. For instance, this is used on Facebook to allow any web page to have the same functionality as any other object on Facebook.

    While many different technologies and schemas exist and could be combined together, there isn’t a single technology which provides enough information to richly represent any web page within the social graph. The Open Graph protocol builds on these existing technologies and gives developers one thing to implement. Developer simplicity is a key goal of the Open Graph protocol which has informed many of the technical design decisions.

    In a nutshell, the Open Graph Protocol turns any web page into an object in a huge graph. Each object, at least in Facebook’s graph objects, can have many other objects linked to it. For example, a Facebook Page can have multiple Post objects, which are posts made by that page. In turn, each Post object can have multiple Comment objects attached to it, referring to comments written by people on the post. This relationship between graph objects is the basis for Facebook’s Graph API, which in turn allows us to do CRUD operations on these objects.

    In this tutorial, we’ll be learning how to use and integrate the Facebook Graph API into an application. We’ll also learn how to use data from the Graph API to do operations like logging in a user via their Facebook account. Ultimately, we’ll be creating a small application than allows people to create and read posts from a Facebook Page they’re managing, similar to HootSuite or TweetDeck.

    Step 1: Create a Facebook Application

    The first thing you should do when you’re planning to use the Facebook Graph API is to create a Facebook application. This doesn’t necessarily mean that we’ll be putting the application on Facebook (although we can); we just need a Facebook application (specifically an APP ID and APP SECRET) to access the API.

    Open [developers.facebook.com] and click on the Apps link in the navigation bar.

    Facebook's Developer Site

    Facebook’s Developer Site

    You’ll be prompted to log in (if you’re not) and allow the Developer application to access your account. Just click on Allow and you’ll be redirected to the Developer App homepage.

    Allow the Developer application access

    Allow the Developer application access

    On the Developer App homepage, click on Create New App in the upper right corner of the page.

    Developer App homepage

    Developer App homepage

    You’ll be greeted with a modal window asking for an App Display Name and App Namespace. Provide anything you want here, but for the purposes of this tutorial, I’ll be using Nettuts+ Page Manager and nettuts-page-manager respectively. Click on Continue.

    Birth of the Nettuts+ Page Manager

    Birth of the Nettuts+ Page Manager

    After some obligatory captcha checking, you’ll be redirected to your newly-minted application’s page. Here you’ll see the APP ID and APP SECRET that we need. Copy and paste these values somewhere for later use.

    The APP ID and APP SECRET

    The APP ID and APP SECRET

    When that’s done, go to the lower part of the page and click on the “Website” box, and below it should appear a form that asks for a Site URL. Since I’m just using my local machine to build the application, I’ll use http://localhost/nettuts/pagemanager. When you’re done, click on the Save Changes button below.

    Nettuts+ Page Manager Settings

    Nettuts+ Page Manager Settings Step 2: Download and Set Up Facebook’s PHP SDK Facebook's GitHub page

    Facebook’s GitHub page

    Our next task is to download and set up Facebook’s PHP SDK. The best location to get it would be on Facebook’s GitHub page, since this is where the latest and greatest version of the PHP SDK will be.

    Downloading Facebook's PHP SDK

    Downloading Facebook’s PHP SDK

    Point your browser to [https:]] and click on the “ZIP” button. This should prompt a download for the latest version of the SDK. Save it anywhere you like.

    Now, extract this into PHP’s include_path to make it accessible by any application. Alternatively, if you’re just using this for one application, extract it inside the application’s folder — just make sure to take note where, since we’ll have to include facebook.php in our code later.

    Step 3: Read from Facebook via the Graph API

    Let’s start creating our project and using the Facebook Graph API to read information from Facebook. For starters, create an index.php file where a user can log in via Facebook. The index.php file should contain the following code:

    <!DOCTYPE html>
    <html>
    <head>
    	<title>Nettuts+ Page Manager</title>
    	<link rel="stylesheet" href="css/reset.css" type="text/css" />
    	<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
    	<script src="js/jquery.min.js"></script>
    
    	<style>
    	body {
    		padding-top: 40px;
    	}
    	#main {
    		margin-top: 80px;
    		text-align: center;
    	}
    	</style>
    </head>
    <body>
    	<div class="topbar">
    		<div class="fill">
    		<div class="container">
    			<a class="brand" href="/">Nettuts+ Page Manager</a>
    		</div>
    	</div>
    	<div id="main" class="container">
    		<a href="connect.php" class="btn primary large">Login via Facebook</a>
    	</div>
    </body>
    </html>
    

    If you’re wondering, reset.css is just your standard stylesheet reset, and bootstrap.min.css is Twitter Bootstrap. I’ve also added jQuery into the mix to make it easier to do client-side stuff. Now, if you refresh the page, it should look something like this:

    Nettuts+ Page Manager First Run
    Nettuts+ Page Manager First Run

    Now let’s create our connect.php file, which will enable us to connect a user’s Facebook account and the pages that he or she manages. Let’s start by including the Facebook library we downloaded earlier. Instantiate it using the APP ID and APP SECRET:

    
    //include the Facebook PHP SDK
    include_once 'facebook.php';
    
    //instantiate the Facebook library with the APP ID and APP SECRET
    $facebook = new Facebook(array(
    	'appId' => 'REPLACE WITH YOUR APP ID',
    	'secret' => 'REPLACE WITH YOUR APP SECRET',
    	'cookie' => true
    ));
    

    The $facebook variable can now be used to make API calls to Facebook on behalf of the application.

    • The appID setting tells Facebook which application we’re using.
    • The secret setting “authenticates” our API calls, telling Facebook that they came from someone who owns the application. This should never be shown to the public, which is why it’s named the “Application Secret.”
    • The cookie setting tells the library to store the user’s session using cookies. Without it, we won’t be able to know whether the user is logged in via Facebook or not.

    Now, we check if the current user has already allowed access to the application. If not, the application has to redirect them to Facebook’s “Allow Permissions” page.

    
    //Get the FB UID of the currently logged in user
    $user = $facebook->getUser();
    
    //if the user has already allowed the application, you'll be able to get his/her FB UID
    if($user) {
    	//do stuff when already logged in
    } else {
    	//if not, let's redirect to the ALLOW page so we can get access
    	//Create a login URL using the Facebook library's getLoginUrl() method
    	$login_url_params = array(
    		'scope' => 'publish_stream,read_stream,offline_access,manage_pages',
    		'fbconnect' =>  1,
    		'redirect_uri' => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
    	);
    	$login_url = $facebook->getLoginUrl($login_url_params);
    
    	//redirect to the login URL on facebook
    	header("Location: {$login_url}");
    	exit();
    }
    

    Essentially, this is all that happens here:

    • The application makes a simple API call to get the user’s Facebook User ID (also known as FB UID) via the $facebook->getUser() method.
    • If the $user variable has a value, it means that the user has already allowed basic permissions for the application.
    • If not, then it means the user hasn’t allowed the application permissions yet, and the application needs to redirect to Facebook’s permissions page to get the necessary permissions.
    • It then generates a Login URL, which is where the application should redirect the user to show Facebook’s permissions page for the application. The getLoginUrl() method takes in the following parameters:

      • scope – this is a comma-delimited list of permissions the application needs
      • fbconnect – this should be 1 to tell Facebook that the application will be using Facebook to authenticate the user
      • redirect_uri – this is the page Facebook redirects to after the user has gone through the Facebook permissions page

      You can read more about the getLoginUrl() method here: [https:]]

    • Afterwards, the application redirects the user to the Login URL and the user sees Facebook’s permissions page.
    Facebook's Permissions Page

    Facebook’s Permissions Page Facebook Permissions

    Let’s take a minute to talk about Facebook permissions. Similar to when you install an application on your Android phone, Facebook permissions are various levels of access a Facebook application can do on behalf of a user. For example, if we wanted access to user’s email address, we can add the email permission to the scope setting we use to generate the login URL.

    Remember, with great power comes great responsibility, so make sure to only use your permissions for good, not for evil.

    It’s important that your application only asks a user for permissions that it actually needs. If you only need to authenticate a user via Facebook, you don’t even need to ask any permissions at all! Remember, with great power comes great responsibility, so make sure to only use your permissions for good, not for evil.

    In the app, we use the following permissions:

    • publish_stream – allows the application to publish updates to Facebook on the user’s behalf
    • read_stream – allows the application to read from the user’s News Feed
    • offline_access – converts the access_token to one that doesn’t expire, thus letting the application make API calls anytime. Without this, the application’s access_token will expire after a few minutes, which isn’t ideal in this case
    • manage_pages – lets the application access the user’s Facebook Pages. Since the application we’re building deals with Facebook Pages, we’ll need this as well.

    There are a lot more permissions Facebook requires for different things. You can read all about them in Facebook’s documentation for permissions.

  • Going back to the application, now that the user has allowed the permissions required by the application, we can do some API calls to Facebook! Place this inside the if-else block from the code above:

    <pre>
    //start the session if needed
    if( session_id() ) {
    
    } else {
    	session_start();
    }
    
    //get the user's access token
    $access_token = $facebook->getAccessToken();
    
    //check permissions list
    $permissions_list = $facebook->api(
    	'/me/permissions',
    	'GET',
    	array(
    		'access_token' => $access_token
    	)
    );
    </pre>
    

    The first thing we do is get the $access_token for the user that the application just authenticated. This is crucial, as the application will need this access token for almost everything we do. To get it, we use the getAccessToken() method. The $access_token acts as a ‘password’ for the user. It’s always unique for every user on every application, so make sure to store this when needed.

    Afterwards, we can see how to make API calls to Facebook using the api() method. This method takes in the following parameters:

    Alternatively, we can also use the api() method to execute FQL (Facebook Query Language) queries, which lets us get data via SQL-style language. This is great for retrieving information not available in the Graph API, as well as running multiple queries in one call. For example, we can get a user’s name and other details through this FQL API call:

    $fql = 'SELECT name from user where uid = ' . $fb_uid;
    $ret_obj = $facebook->api(array(
       'method' => 'fql.query',
       'query' => $fql,
     ));
    

    We won’t need this for this tutorial, but it’s good to keep this in mind when you come across something the Graph API can’t get.

    Now that we have the list of permissions the user has allowed for the application, we need to check if the user gave the application all the necessary ones. Since Facebook’s permissions page allows users to revoke certain permissions, we need to make sure that all of them have been allowed to make sure the application works. If the user has revoked one of the permissions, we’ll redirect them back to the permissions page.

    //check if the permissions we need have been allowed by the user
    //if not then redirect them again to facebook's permissions page
    $permissions_needed = array('publish_stream', 'read_stream', 'offline_access', 'manage_pages');
    foreach($permissions_needed as $perm) {
    	if( !isset($permissions_list['data'][0][$perm]) || $permissions_list['data'][0][$perm] != 1 ) {
    		$login_url_params = array(
    			'scope' => 'publish_stream,read_stream,offline_access,manage_pages',
    			'fbconnect' =>  1,
    			'display'   =>  "page",
    			'next' => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
    		);
    		$login_url = $facebook->getLoginUrl($login_url_params);
    		header("Location: {$login_url}");
    		exit();
    	}
    }
    
    var_dump() of the $permissions_list variable

    var_dump() of the $permissions_list variable

    When that’s done, it means we’re all set and we’ll be able to run the application without any problems. Let’s start by doing another API call, this time to retrieve the list of Facebook Pages the user has administrative rights to, and saving these into a session variable. Afterwards, we’ll redirect the user to the manage.php page, where the page management code will be.

    //if the user has allowed all the permissions we need,
    //get the information about the pages that he or she managers
    $accounts = $facebook->api(
    	'/me/accounts',
    	'GET',
    	array(
    		'access_token' => $access_token
    	)
    );
    
    //save the information inside the session
    $_SESSION['access_token'] = $access_token;
    $_SESSION['accounts'] = $accounts['data'];
    //save the first page as the default active page
    $_SESSION['active'] = $accounts['data'][0];
    
    //redirect to manage.php
    header('Location: manage.php');
    
    var_dump() of the $accounts variable

    var_dump() of the $accounts variable

    The /me/accounts graph path gives us a list of the pages that a user has administrative rights to. This returns an array of all of the pages, plus specific $access_tokens for each of these pages. With those $access_tokens, we’ll be able to do API calls on behalf of the Facebook Page as well!

    Save these in the $_SESSION array and redirect to the manage.php page.

    Let’s start working on our manage.php file. Remember that we’ve saved the user’s $accounts list into the $_SESSION array, as well as set the first account on the list as the default active page. Let’s GET that account’s news feed and display it:

    //include the Facebook PHP SDK
    include_once 'facebook.php';
    
    //start the session if necessary
    if( session_id() ) {
    
    } else {
    	session_start();
    }
    
    //instantiate the Facebook library with the APP ID and APP SECRET
    $facebook = new Facebook(array(
    	'appId' => 'APP ID',
    	'secret' => 'APP SECRET',
    	'cookie' => true
    ));
    
    //get the news feed of the active page using the page's access token
    $page_feed = $facebook->api(
    	'/me/feed',
    	'GET',
    	array(
    		'access_token' => $_SESSION['active']['access_token']
    	)
    );
    

    Again, the application does the intialization of the Facebook library, and then another api() call, this time to /me/feed. Take note that instead of using the user's access token, we use the active page's access token (via $_SESSION['active']['access_token']). This tells Facebook that we want to access information as the Facebook Page and not as the user.

    var_dump() of the $page_feed variable

    var_dump() of the $page_feed variable

    Wow, that’s a lot of information about a Facebook Post. Let’s dissect a single Facebook Post object and see what it’s made of.

    The Facebook Post Object Facebook Post Cheat Sheet

    Facebook Post Cheat Sheet

    It would be wise to keep a copy of the cheat sheet above, since we’ll be using that again when we publish Post objects to Facebook.

    Moving on, let’s display the news feed in a more pleasing way. Add the following HTML below the PHP code:

    <!DOCTYPE html>
    <html>
    <head>
    	<title>Nettuts+ Page Manager</title>
    	<link rel="stylesheet" href="css/reset.css" type="text/css" />
    	<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
    	<script src="js/jquery.min.js"></script>
    
    	<style>
    	body {
    		padding-top: 40px;
    		background-color: #EEEEEE;
    	}
    	img {
    		vertical-align: middle;
    	}
    	#main {
    		text-align: center;
    	}
    
    	.content {
    		background-color: #FFFFFF;
    		border-radius: 0 0 6px 6px;
    		box-shadow: 0 1px 2px rgba(0, 0, 0, 0.15);
    		margin: 0 -20px;
    		padding: 20px;
    	}
    	.content .span6 {
    		border-left: 1px solid #EEEEEE;
    		margin-left: 0;
    		padding-left: 19px;
    		text-align: left;
    	}
    	.page-header {
    		background-color: #F5F5F5;
    		margin: -20px -20px 20px;
    		padding: 20px 20px 10px;
    		text-align: left;
    	}
    	</style>
    
    </head>
    <body>
    <div id="main" class="container">
    	<div class="content">
    		<div class="page-header">
    			<h1>
    				<img width="50" src=" [graph.facebook.com] echo $_SESSION['active']['id']; ?>/picture" alt="<?php echo $_SESSION['active']['name']; ?>" />
    				<?php echo $_SESSION['active']['name']; ?>
    				<small><a href=" [facebook.com] echo $_SESSION['active']['id']; ?>" target="_blank">go to page</a></small>
    			</h1>
    		</div>
    		<div class="row">
    			<div class="span10">
    				<ul id="feed_list">
    					<?php foreach($page_feed['data'] as $post): ?>
    					<?php if( ($post['type'] == 'status' || $post['type'] == 'link') && !isset($post['story'])): ?>
    					<?php //do some stuff to display the post object ?>
    					<?php endif; ?>
    					<?php endforeach; ?>
    				</ul>
    			</div>
    			<div class="span6">
    				<h3>Post a new update</h3>
    			</div>
    		</div>
    	</div>
    </div>
    </body>
    </html>
    

    We make use of a simple Graph API trick here: the Picture Graph API object. Basically, you can take the Graph path of any User or Page object (e.g. http://graph.facebook.com/293518907333589), add /picture in the end and you’ll get a 50×50 photo of that object. For example:

    http://graph.facebook.com/293518907333589/picture

    Becomes…



    Demo Picture Graph API Object

    Going back, when we refresh the manage.php page now, it should look something like this:

    Add this inside the <?php foreach($page_feed['data'] as $post): ?> to display the feed from the page:

    <?php if( ($post['type'] == 'status' || $post['type'] == 'link') && !isset($post['story'])): ?>
    <li>
    	<div class="post_photo">
    		<img src=" [graph.facebook.com] echo $post['from']['id']; ?>/picture" alt="<?php echo $post['from']['name']; ?>"/>
    	</div>
    
    	<div class="post_data">
    		<p><a href=" [facebook.com] echo $post['from']['id']; ?>" target="_blank"><?php echo $post['from']['name']; ?></a></p>
    		<p><?php echo $post['message']; ?></p>
    		<?php if( $post['type'] == 'link' ): ?>
    		<div>
    			<div class="post_picture">
    				<?php if( isset($post['picture']) ): ?>
    				<a target="_blank" href="<?php echo $post['link']; ?>">
    					<img src="<?php echo $post['picture']; ?>" width="90" />
    				</a>
    				<?php else: ?>
    				&nbsp;
    				<?php endif; ?>
    			</div>
    			<div class="post_data_again">
    				<p><a target="_blank" href="<?php echo $post['link']; ?>"><?php echo $post['name']; ?></a></p>
    				<p><small><?php echo $post['caption']; ?></small></p>
    				<p><?php echo $post['description']; ?></small></p>
    			</div>
    			<div class="clearfix"></div>
    		</div>
    		<?php endif; ?>
    	</div>
    	<div class="clearfix"></div>
    </li>
    <?php endif; ?>
    

    When you refresh the page again, it should look something like this:

    Looks good, right? We’ll have to thank the Twitter Bootstrap CSS for that!

    Now, let’s add a top navigation bar to help us switch from one page to another. Add the following HTML after the <body> tag and before the <div id="main" class="container"> tag:

    <div class="topbar">
    	<div class="fill">
    	<div class="container">
    		<a class="brand" href="/">Nettuts+ Page Manager</a>
    		<ul class="nav secondary-nav">
    			<li class="dropdown" data-dropdown="dropdown">
    				<a class="dropdown-toggle" href="#">Switch Page</a>
    				<ul class="dropdown-menu">
    					<?php foreach($_SESSION['accounts'] as $page): ?>
    					<li>
    						<a href="switch.php?page_id=<?php echo $page['id']; ?>">
    							<img width="25" src=" [graph.facebook.com] echo $page['id']; ?>/picture" alt="<?php echo $page['name']; ?>" />
    							<?php echo $page['name']; ?>
    						</a>
    					</li>
    					<?php endforeach; ?>
    				</ul>
    			</li>
    		</ul>
    	</div>
    	</div>
    </div>
    

    Don’t forget to load the dropdown JavaScript library from Twitter Bootstrap’s JavaScript page. You can download it here.

    <script src="js/bootstrap-dropdown.js"></script>
    <script>
    $('.topbar').dropdown()
    </script>
    

    Lastly, let’s create the switch.php file, where we’ll set another page as the active page:

    <?php
    session_start();
    $page_id = $_GET['page_id'];
    
    foreach($_SESSION['accounts'] as $page) {
    	if( $page['id'] == $page_id ) {
    		$_SESSION['active'] = $page;
    		header('Location: manage.php');
    		exit();
    	}
    }
    exit();
    ?>
    

    Refresh the manage.php page again and you should see something like this:

    And now, by using our dropdown switcher, we’re able to switch pages.

    Step 4: Publish to Facebook via the Graph API

    Now we’re ready to publish new updates to our page! First of all, let’s create the HTML form where we can set what we’ll publish. Add this below the <h3>Post a new update</h3> HTML:

    <img src="post_breakdown.png" alt="Facebook Post Cheat Sheet" width="340" /><br />
    <form method="POST" action="newpost.php" class="form-stacked">
    	<label for="message">Message:</label>
    	<input class="span5" type="text" id="message" name="message" placeholder="Message of post" />
    	<label for="picture">Picture:</label>
    	<input class="span5" type="text" id="picture" name="picture" placeholder="Picture of post" />
    	<label for="link">Link:</label>
    	<input class="span5" type="text" id="link" name="link" placeholder="Link of post" />
    	<label for="name">Name:</label>
    	<input class="span5" type="text" id="name" name="name" placeholder="Name of post" />
    	<label for="caption">Caption:</label>
    	<input class="span5" type="text" id="caption" name="caption" placeholder="Caption of post" />
    	<label for="description">Description:</label>
    	<input class="span5" type="text" id="description" name="description" placeholder="Description of post" />
    
    	<div class="actions">
    		<input type="submit" class="btn primary" value="Post" />
    		<input type="reset" class="btn" value="Reset" />
    	</div>
    </form>
    

    Refresh to see how it looks:



    Loving Twitter Bootstrap’s default form styles

    The Post cheat sheet should come in handy when we’re figuring out what to put in the fields. Now, let’s create the newpost.php file where we’ll actually use the Facebook Graph API to publish to the page’s feed.

    Start by creating the file and initializing the Facebook library like we did for the other pages:

    <?php
    //include the Facebook PHP SDK
    include_once 'facebook.php';
    
    //start the session if necessary
    if( session_id() ) {
    
    } else {
    	session_start();
    }
    
    //instantiate the Facebook library with the APP ID and APP SECRET
    $facebook = new Facebook(array(
    	'appId' => 'APP ID',
    	'secret' => 'APP SECRET',
    	'cookie' => true
    ));
    ?>
    

    Afterwards, let’s get all of the content we received from the POST request:

    //get the info from the form
    $parameters = array(
    	'message' => $_POST['message'],
    	'picture' => $_POST['picture'],
    	'link' => $_POST['link'],
    	'name' => $_POST['name'],
    	'caption' => $_POST['caption'],
    	'description' => $_POST['description']
    );
    

    Let’s not forget to add the $access_token for the page to the parameters:

    //add the access token to it
    $parameters['access_token'] = $_SESSION['active']['access_token'];
    

    Now that we have our $parameters array, let’s build and send our Graph API request!

    //build and call our Graph API request
    $newpost = $facebook->api(
    	'/me/feed',
    	'POST',
    	$parameters
    );
    

    Take note of what difference the $method can make. A GET API call to /me/feed will return the news feed of that particular object, but a POST API call to /me/feed will post a new status update to the object.

    To publish a new Post object to Facebook, the application needs to make a call to the /<page_id or /me>/feed graph path, and it needs to supply the following in the $parameters array:

    You can see that the only parameters that are required are the access_token and the message parameters. By providing only these two, we can publish a simple status message, like so:



    Status Update Example

    Everything else is optional. However, if you provide a name, link, caption, or decription, you have to provide all four. As for picture, if a parameter value is not provided or not accessible, the post’s picture will be blank.

    Finally, let’s try publishing to Facebook using the application! Go back to the manage.php page and fill up the form, then press Post:

    Afterwards, you should be redirected back to the manage.php page, but there should be a new post on the feed!



    Publishing to Facebook successful!

    You can also check the Facebook Page itself. You should see the new post there:



    Publishing to Facebook Page Conclusion

    By now, you should already have a clear grasp on how to use the Facebook Graph API to both read and publish to Facebook. In this tutorial, we only cover the basics — there’s a whole lot more you can do using the Graph API. Stuff like real-time updates, which lets you subscribe to events that happen to your application’s users (e.g. when a user changes his/her profile photo) or the Insights Graph object, which lets you get the statistics of an application, page, or domain the user has access to.

    Of course, the best resource for learning more about the Graph API is undoubtedly Facebook’s Graph API documentation, but I also suggest taking a look at FBDevWiki, which is a third-party hosted wiki for Facebook Development documentation.



    FBDevWiki.com

    Additionally, there’s also a special Facebook version of StackOverflow you can visit at [facebook.stackoverflow.com] . The questions here are all about Facebook and Facebook Development, so it’s well worth visiting if you need any help or have any questions on the subject.



    Facebook StackOverflow

    Hopefully, you’ve learned from this tutorial how easy it is to use the Facebook Graph API to make your applications more social.

    Have you used the Facebook Graph API in a previous project, or are you planning to use it now? Tell me all about it in the comments below and thank you so much for reading!


  • Permalink for 'Recently in Web Development (November Edition)'

    Recently in Web Development (November Edition)

    Posted: November 30th, 2011, 4:25pm MST by Siddharth

    Web development is an industry that’s in a state of constant flux with technologies and jargon changing and mutating in an endless cycle. Not to mention the sheer deluge of information one has to process everyday.

    In this series, published monthly, we’ll seek to rectify this by bringing you all the important news, announcements, releases and interesting discussions within the web development industry in a concise package. Join me after the jump!

    News and Releases

    All of the important news in a single place: releases, announcements, companies bickering, security issues and all related hoopla.

    Nettuts image Mozilla Releases Popcorn

    Mozilla, in their quest to make video on the web a better experience, released their Popcorn platform. Popcorn consists of a JavaScript framework as well as a creation environment.

    I’m sure you have lots of questions so make sure to read more below.

    Read more

    Nettuts image Adobe to Drop Flash for Mobile Devices

    This maybe a bit tangential but it’s still important news. Adobe, after a lot of attritional warfare with Apple, has decided to drop development of the Flash players for mobile devices.

    Adobe plans to instead leverage HTML5 technologoy to provide more features to developers. Read on more about the topic at the link below.

    Read more

    Nettuts image jQuery 1.7 Released

    A new version of our favorite JavaScript library got released this month. This bumps up the version number to 1.7.

    The new features on tap in this versions include a new event API, support for the AMD API, extensions to the deferred object and many more.

    Read more

    Nettuts image Mozilla Version Version 8 of Firefox

    Mozilla did promise quicker release cycles but this is quite unprecedented. We’ve gone from version 4 to version 8 in a matter of months and most of the changes have been under the hood.

    Anyway, if you’re a cutting edge, curious dev, you can find more about this release at the link below.

    Read more

    Nettuts image Nimbus.IO Launches

    If you’re a developer who makes use of Amazon S3 but would like more options, here is something for you.

    In the footsteps of S3 comes Rackspace Cloud comes Nimbus.io, the latest entrant in this field. Even though it’s still in beta, it’s fairly stable, competitively priced and has an API that’s quite similar to S3.

    Read more

    Nettuts image jQuery Mobile 1.0 is Out

    In the midst of jQuery releases, it’s easy to forget that jQuery mobile exists. The mobile framework has been slowly creeping towards the version 1.0 release and it’s finally here.

    If you’re a mobile dev, or even just someone who wants to dabble around with mobile development, you really need to go browse around at the link below.

    Read more

    Nettuts image Twitter Bootstrap Gets Updated

    The wildly popular toolkit from Twitter got upgraded with a substantial number of fixes and performance improvements over the last few weeks.

    If you’re a bit curious about what Bootstrap is, we do have a little tutorial that makes use of Bootstrap.

    Read more

    Nettuts image Node v0.6.0 Released

    NodeJS, the JavaScript userbase’s recent darling, has been getting a steady stream of updates recently. Earlier this month, Ryan brought Node upto version 6 with a number of improvements including better Windows support.

    Read more

    New Kids on the Block

    As web developers, the sheer amount of resources we can tap into increases exponentially with time. Here is just a quick look at some recently created resources that deserve your attention — everything from new books to scripts and frameworks.

    Nettuts image Lungojs

    Meet the first Mobile Framework that uses the actual features of #HTML5, #CSS3 and #JavaScript.

    Read more

    Nettuts image Slider.js

    Slider.js is an easy-to-use customizable Javascript library to create image slideshows. It relies on latest web technologies: the power of CSS Transitions to perform awesome and efficient effects and the HTML5 Canvas to perform some non trivial transitions.

    Read more

    Nettuts image Face detection jQuery Plugin

    A neat little jQuery plugin which detects faces in pictures and returns theirs coords.

    Read more

    Nettuts image Flatiron

    An unobtrusive framework initiative for node.js. Flatiron promotes code organization and sustainability by clearly separating development concerns.

    Read more

    Nettuts image backbone-on-rails

    A simple gem for using Backbone.js with Rails (>= 3.1), based on thoughtbot’s Backbone.js on Rails

    Read more

    Nettuts image kibi

    An easy-to-use single-page app framework in 1,024 bytes of JavaScript. kibi currently weighs in about 200 bytes less, so there’s still room for improvement.

    Read more

    Nettuts image Derby

    MVC framework making it easy to write realtime, collaborative applications that run in both Node.js and browsers.

    Read more

    Nettuts image BicaVM

    This project is an implementation of a JVM in JavaScript. At the moment it runs Java code, but is more like a proof of concept than a real JVM.

    Read more

    Nettuts image RightJS

    Even though RightJS has been around for a while, this new version brings a lot of new features since there are a ton of new features and fixes with this version.

    Read more

    Best of the Internet

    Often, you’re not really looking for a tutorial as much as you’re looking for a rant, an opinion or the musings of a tired developer or just something cool with absolutely zero real world use. This sections contains links to precisely those — interesting and cool stuff from the developer community.

    Nettuts image Why Parsing XHTML with RegEx is a Bad Idea

    A cry for help or an artistic masterpiece? You decide. A user asks for assistance with regex for parsing XHTML leading to this linked piece.

    Read more

    Nettuts image HTML5 2D Gaming Performance Analysis

    With HTML5 showing great growth, lots of developers have started using canvas and WebGL for developing games and such. If you’re thinking of making the move, this is a must read article that explores the performance facet of these technologies.

    Read more

    Nettuts image The Last PHP PDO Library You Will Ever Need

    A developer’s thoughts on ORMs, SQL generation tools and how he came to write his own mini PDO library.

    Read more

    Nettuts image CoffeeScript Means Giving Up on JavaScript

    Michael Woloszynowicz explains why he’s alarmed at the recent move towards languages that compile to JavaScript instead of merely using JavaScript itself.

    Read more

    Nettuts image Response to “CoffeeScript Means Giving Up on JavaScript”

    As is the case with strongly opinioned prose, the above article ignited a heated discussion among the web and here’s a rebuttal that I found the most prgamatic and, well, terse. Good read!

    Read more

    Nettuts image MongoGate — or Let’s Have a Serious NoSQL Discussion

    Need the down low on the current NoSQL situation? I’ve got something for you. This piece by Martin Scholl is a great read if you’re interested in the topic.

    Read more

    Wrapping Up

    Well, that’s about all the major changes that happened in our industry lately.

    Do you want us to cover more standard news? A focus on upcoming scripts maybe? Or just more interesting posts and discussions from the community? Let us know in the comments and thank you so much for reading!


  • Permalink for 'Why I’m So Excited About the New Tuts+ Premium'

    Why I’m So Excited About the New Tuts+ Premium

    Posted: November 29th, 2011, 5:42pm MST by Jeffrey Way

    Hey, guys! For the last several months, I’ve had the pleasure of helping out, top-secret, on the relaunch of Tuts+ Premium. After months of work, it’s out in the wild! If you have a second, let me know show you what’s new.

    Massive Redesign

    We’ll be the first to admit that the old layout was in huge need of revision. That’s why we hired the incredibly talented Orman Clark to work on a new, updated layout. I think it turned out wonderfully.

    Courses!

    I’m a huge fan of taking a skill, and breaking it down as much as possible into bits and pieces that can easily be consumed. Ten minutes a day, and, at the end of the month, you’ve learned a new technology. That’s what our new courses are for!

    We’ve launched with five massively in depth courses, and will continue adding more at a rate of around three per month. Here’s a few that will appeal specifically to you guys:

    Also in the queue are courses on HTML5, WordPress Plugin Development, Professional Screencasting, and much more!

    …And, if you have a question about a lesson in a particular course, just head over to the Tuts+ Premium forums to discuss it with your fellow members and the course instructor.

    eBooks

    We’ve worked with Rockable Press and Smashing Magazine to provide their respective catalogs of eBooks free to all Premium members. That’s hundreds upon hundreds of dollars worth of eBooks for $19 a month. Here’s a handful that you might enjoy:

    Getting Good with JavaScript  Getting Good with JavaScript Professional Web Design Professional Web Design How to be a Rockstar WordPress Designer How to be a Rockstar WordPress Designer Theme Tumblr Like a Pro Theme Tumblr Like a Pro Over 700 Exclusive Tutorials

    In addition to the newly added courses and eBooks, we still have our insanely huge library of exclusive Premium tutorials. At the time of this writing, Tuts+ Premium contains over 700, including these:

  • Next Generation JavaScript with AMD and RequireJS – I don’t know about you, but I’m always looking for better ways to organize my JavaScript. Recently (only a week or so ago), I’ve discovered what seems to be the best pattern yet. In this tutorial, I’ll introduce you to AMD: Asynchronous Module Definition and RequireJS. Hang on tight; it’ll be a wild ride!
  • The Magic of WordPress Custom Post Types – In this in depth video tutorial, I’ll teach you how to use custom post types, taxonomies, and meta boxes to extend your WordPress application into CMS-like territory.
  • A Massive Guide to Custom Theming jQuery UI Widgets – jQuery UI is an open source library of interface components that features interactions, animation effects and ready-to-use widgets. jQuery UI is based on the jQuery JavaScript library and is themeable, which makes integrating jQuery UI easy for developers of any skill level to integrate into their web pages and applications.
  • Build your Own JavaScript Library – Over the course of the past few years, the JavaScript community has exploded exponentially. It it’s safe to assume that libraries are the primary reason we’ve seen such astonishing growth. Thanks to these libraries, the differences between the popular browsers are minimized, making cross-browser development much easier than it used to be.
  • How to Build a Custom S3 Uploader – Ever wondered how to create a form that can upload multiple files directly to your desired S3 bucket? While tools like S3Fox and Transmit certainly get the job done quite well, sometimes we need a simpler, one-click interface for our clients. We’ll build one today!
    For $19 – It’s Worth It

    After listening to all of the input from our users, we think we’ve produced an exceptional Version Two of Tuts+ Premium. I hope you agree! If you sign up, come say hi in our forums!


  • Permalink for 'Why Many Developers Hate ASP.NET… and Why They’re Wrong'

    Why Many Developers Hate ASP.NET… and Why They’re Wrong

    Posted: November 29th, 2011, 8:49am MST by Jeremy McPeak

    Few platforms draw the same amount of ire as ASP.NET (or .NET in general) from the development community. While there are certainly valid criticisms of the platform (what platform doesn’t?), the majority of negativity comes from those who haven’t spent any time with .NET. Those developers typically rely on misconceptions or flat out hatred to base their opinion, and they do a disservice to others looking to learn a new technology and to the platform itself. So, let’s examine these excuses and add a dose of reality on why you shouldn’t listen to the rabble and give ASP.NET a try.

    It’s Made by Microsoft

    This is probably the #1 reason for all ASP.NET hate.

    Microsoft is a massive software corporation, and like all other corporations, they’re in business to make money. Duh, right? Unfortunately, this is probably the #1 reason for all the ASP.NET hate: it’s a Microsoft technology, and the “evil” taint still lingers over the giant in many people’s minds. I’ve always found this interesting because the other major technology companies, such as Google and Apple, are just as “evil” as Microsoft, but the zealots fans of those other companies typically turn a blind eye (or are in denial) to those “evils.” I personally think the majority of people are normal minded people. They don’t really care who makes a product as long as that product works well.

    But I’m not talking about normal people, right? Normal people don’t see a headline containing "ASP.NET" and have an automatic urge to make an inane comment. Instead, I’m talking about the developers (and geeks) that treat technology, and/or the company that creates it, as a religion. I’m not kidding—find any article or tutorial on X platform, and chances are good you’ll find comments stating “X Sucks! Y Rules!”

    It’s as if these people are on some weird crusade to defend their chosen tech/company to the hilt and bash the competition in an attempt to bring the unwashed masses into their fold.

    It’s sad that the technology = religion mindset exists. Technology is a just tool, and a real developer is going to try multiple tools in order to find the right one for the job. That’s not to say that someone cannot dislike a technology, but to echo our parents, "you don’t know you don’t like it until you try it." In order for someone to truly dislike something, that person has to try it. So don’t listen to the rabble—they haven’t tried it and haven’t formed an informed opinion. If you decide you want to try it, they’ll attempt to dissuade you by saying it costs too much.

    Misconception: It’s Expensive

    Find any article comparing ASP.NET with any other platform, and you’ll read, either in the article or in the comments, “ASP.NET costs more than [insert any other server-side tech other than ColdFusion here].” Before discussing the actual cost of something, it’s important to put the term “expensive” in context, as what is expensive for personal use can be considered cheap in a business environment. In business, there are many factors that make up the “cost” of a product. The initial price obviously needs to be considered, but the benefit of the product is also factored into the overall cost.

    If a product is $10,000, but it saves the company $1,000 a month, the purchase decision is a no brainer. But on a personal level, it would more than likely be difficult to justify the initial $10,000 cost.

    So when talking about cost, it’s important to keep things in perspective according to the context in which it will be incurred.  To keep things simple, I’m going to assume that if you’re reading this, you’re more concerned with the personal cost than the business cost (if I’m wrong with that assumption, I’ll make this very easy for you: if you have a Windows environment, ASP.NET is cheap).

    You don’t actually need Windows to develop ASP.NET apps, thanks to the Mono project.

    Let’s get the biggest cost out of the way: the Windows operating system. You don’t actually need Windows to develop ASP.NET apps, thanks to the Mono project (more on this later), but Mono typically lags behind the official .NET Framework coming out of Microsoft’s ovens. So, if you want all of the latest features and .NET-goodness, you’ll need Windows. Most OEMs (companies like Dell, HP, Acer, etc) ship their computers with Windows already installed; so, if you buy your computer from an electronics chain store like Best Buy, chances are pretty darn good that the computer will have Windows. If you’re more of a power user and build your own computers or plan on run Windows in a virtual machine, you will have to purchase a copy of Windows. An OEM version of Windows will run you anywhere from $99 to $189, depending on which version of Windows you buy. You don’t need to have Professional ($139 OEM) or Ultimate ($189 OEM), but if you’re a power user, you’ll more than likely want to opt for one of those two versions (OEM versions are cheaper than retail versions, but they are tied to the hardware you activate them on).

    Development Costs

    With that out of the way, let’s review development costs. ASP.NET development is thought to be expensive for two reasons.

    1. It’s Microsoft. They supposedly don’t give anything away for free, but that’s exactly what they do. Everything you need to develop ASP.NET applications (or .NET apps in general) can be obtained without spending a dime.

      Beginners: First, Microsoft gives away WebMatrix, a development environment targeted at beginners. It combines an integrated development environment (IDE) with a built-in web server (IIS Express) and a database engine (SQL Compact Edition). It also has tools to help users deploy their websites to a remote host.

      Advanced Users: For more advanced developers, Microsoft makes available the Express editions of Visual Studio. Like WebMatrix, these trimmed down versions of Visual Studio are free, but they offer some of the features and abilities found in the full versions of Visual Studio. The web-focused Express product is Visual Web Developer Express (VWD), and it, too, has a built-in web server. It doesn’t have a built-in database engine, but Microsoft gives away SQL Server Express, a trimmed down version of SQL Server, that you can use for development (and even some deployment situations). If you later decide you like Visual Studio and want to purchase the full version, the projects you developed with VWD can be opened with Visual Studio.

      Students: And if you’re a student, you can get lots of Microsoft software (Visual Studio Pro, Windows Server OSs, and Expression Studio to name just a few) for free through the DreamSpark program.

    2. Secondly, Windows-based hosting is thought to be mucho expensive-o. Ten years ago, that argument held some weight. Today however, you can find no shortage of reasonably priced hosting for ASP.NET. DailyRazor (the company I use) starts plans at $2/month, and you can find other hosting providers that sell their services at low prices.

    So cost isn’t really a problem, but naysayers will then say ASP.NET is only suitable for enterprise-class websites as opposed to your personal site(s).

    Misconception: It’s Horrible for Small, Personal Websites

    One only has to look at the .NET Framework’s class library to get the “this is for enterprise” feeling.

    It’s actually easy to get into the mindset that ASP.NET isn’t suited for anything but large-scale sites. Microsoft is a platform company, after all, and their products are primarily focused towards business solutions. .NET isn’t really different in that respect; it’s huge in business environments, and its foothold continues to grow as Microsoft expands new and revitalized products like Azure (Microsoft’s Cloud platform) and Windows Phone, respectively. One only has to look at the .NET Framework’s class library to get the “this is for enterprise” feeling. It’s almost as if the framework guides developers to a mindset that (ASP).NET applications needs to be highly structured masterpieces of object oriented design. A lot of .NET is complex, and doing simple things isn’t always as simple as it should be. It sounds like I’m making the naysayer’s case, doesn’t it? I kind of am, but there two things to consider.

    Simplicity

    First, Microsoft wants you developing on their platform, and they’ve recognized that it needs some (perhaps a lot of) simplification in order to grow. After all, PHP is as popular as it is specifically because of its simplicity, and that’s the primary reason Microsoft released WebMatrix: to offer new developers (either to .NET development or web development in general) a simplified approach to writing sites with ASP.NET.

    Not only is the all-in-one IDE easy to use, but Microsoft created a simplified API to make ASP.NET development easier and less complex.

    Multiple Approaches

    You can also build sites with the same kind of “scripting” mentality that thrives in PHP.

    Second, you don’t have to fall into the “highly structured or die” mentality. There are many approaches to ASP.NET development. If you want to create highly structured masterpieces of object oriented design, you can. But you can also build sites with the same kind of “scripting” mentality that thrives in PHP. The point is, ASP.NET development is flexible enough to fit your needs, and you can choose the development approach that best fits you.

    Oddly enough, there’s a somewhat prevalent idea that ASP.NET isn’t suitable for enterprise-class websites. o.0

    Misconception: It’s Horrible for Large, Enterprise-class Websites

    I honestly have no idea where this comes from because, as mentioned earlier, ASP.NET excels in the enterprise space. But don’t just take my word for it; let’s examine a real-world website (well, a network of websites) that run on ASP.NET.

    Have you ever heard of StackOverflow.com? You probably have, and if you haven’t, it’s a Q&A website for developers (regardless of technology). Its an invaluable resource, and one I find myself visiting quite often.

    StackOverflow is a member of the Stack Exchange Network, a network of Q&A websites for a variety of topics: servers, databases, legos, sci-fi, cars, and so on, and so on. There are currently 71 sites in the network, and it continues to grow.

    The folks at the Stack Exchange Network are pretty open about their network. Much of the code running on the site is open sourced, and they often provide information regarding the network in general. In a March 2011 blog post, Kyle Brandt provided an overview of the technology powering the Stack Exchange Network, as well as the traffic the network gets. Keep in mind this information is regarding the entire Stack Exchange Network. It gets 95 million page views a month and handles 800 HTTP requests a second, and those requests are handled by twelve (yes only twelve) Windows web servers, two MS SQL Server servers, two Linux load balancers, and two Linux caching servers (fail-over hardware is not included in that count).

    Reread those stats—I’ll wait. Phenomenal, right? It’s amazing that only twelve servers, serving many different websites, handle that amount of traffic. It’s a testament to just how good Microsoft’s server and application architecture is.

    It’s Statically Typed

    Dynamic languages rule the web. Be it on the server side, where languages like PHP, Ruby, Python, and Perl live, or in the browser with JavaScript, dynamic languages are the backbone of the web. It’s not that these languages are better, but they are quickly adopted because dynamic languages are typically easier to learn and understand than statically typed languages.

    So what we essentially end up with is a massive community of developers who have only used dynamic languages, and that community almost has an aversion to static languages.

    I fully understand the mindset. I used to be one of those people, and I understand the desire to stay within one’s comfort zone. After all, dynamic languages are lenient, and there is some comfort found in that leniency.

    Static languages have a strict type system.

    But there’s a bad side to that leniency; it is extremely easy to introduce bugs into your app if you’re not careful. You’ll typically not find that bug until runtime, and a common cause of bugs is the assignment of a different and unintended type of value to a critical variable. This is where the primary benefit of static languages comes in: type safety. Static languages have a strict type system, in that a variable can only contain one type of value (eg: a variable declared as an integer can only contain integer values; it cannot contain a string or floating point numbers). If you mistakenly assign a string to a number variable, you will immediately know of the error when you compile the code because the compiler with halt and alert you to the error.

    Type safety can also alleviate the type checking you need to perform in dynamic languages. For example, how many times have you written code like the following to ensure the data a function accepts is of the expected type:

    function add($a, $b) {
        if (is_int($a) && is_int($b)) {
            return $a + $b;
        }
    
        // throw error
    }

    This is a simple PHP function that adds two numbers together. In order to ensure predictable results, checking if the supplied values are of the appropriate type is imperative (admittedly, the type checking here isn’t complete; there are numeric types other than integer); otherwise, your app could break at unexpected times. In contrast, let’s look at the C# equivalent code:

    int add(int a, int b) {
        return a + b;
    }

    This code defines an add() method. C# is the most popular .NET language, and it is purely object oriented. There are no functions; only methods of a class. This method accepts two integer values (denoted by the int keyword before the a and b identifiers), and it returns an integer value as denoted by the int before add. Because C# is a static language, the type checking is performed by the compiler—not by you. So, if you were to call this method, pass a string as one of the arguments, like add("hello", 123), and attempt to compile the code, the compiler will stop the build process and alert you to the error. Chances are, however, you wouldn’t even try to compile the code because Visual Studio performs its own type and syntax checking; the IDE will warn you of errors before you even try to compile (see the below screenshot of Visual Studio 2010).

    Also consider that Microsoft continually updates and improves the C# language. In the first two versions of the language, you had to identify a variable’s type when declaring it like this:

    XmlDocument document = new XmlDocument();

    This code creates an instance of the XmlDocument class by declaring its type prior to the variable’s name. Admittedly, this syntax is rather cumbersome and adds far more typing, but as of C# 3.0, however, you can simply use the var keyword to define a variable, like this:

    var document = new XmlDocument();

    There are .NET-enabled versions of PHP, Ruby, Python, and PERL.

    The compiler is smart enough to infer that the document variable is an XmlDocument. This syntax sort of blurs the line between dynamic and static languages. You get simple, typeless variable declarations with the benefits of type safety… a win-win in my book.

    But if I still can’t persuade you to give C# a try, ASP.NET sites do not have to be written in C# (or even VB.NET… but who would want to do that?). There are .NET-enabled versions of PHP, Ruby, Python, and PERL (and others) that you can use to write ASP.NET sites with, and they are just as dynamic as usual thanks to the Dynamic Language Runtime, a feature of .NET 4. So while I recommend anyone picking up ASP.NET to learn C#, you don’t have to leave your comfort zone if you don’t want to (but if you do the benefits are worth it).

    It’s Compiled

    The same dynamic languages that rule the web are also interpreted, and there is a certain benefit that comes with interpreted languages. Unlike compiled environments like ASP.NET where you typically write your code, compile it, and upload it, interpreted environments let you simply write your code and upload it. The common idea being that compiled environments require an extra step in development, and that wastes time. But it really doesn’t. The compiler gives us many benefits that you just cannot get in an interpreted-language environment.

    First, the compiler checks the code and can give you warnings. Warnings are just that: a warning. It’s something you’ve done that may be a bug, but it won’t stop the compiler from compiling your code. Let’s look at the following code that would cause a warning:

    string DoSomething()
    {
        var foo = "Hello";
        var bar = "World!";
    
        return foo;
    }

    This code defines a method called DoSomething(). Its body creates two string objects, foo and bar, and foo is returned to the caller. The bar variable is not used, so the compiler would issue a warning stating that bar is assigned but its value is never used. It may be that I created bar and forgot about it, or that I ended up not needing it. But it could be the source of a bug if I forgot bar already existed and used it elsewhere in the method. The compiler brings it to my attention so that I may address it and avoid future bugs. Here’s a screenshot of what Visual Studio tells me:

    Do you want another example? Sure you do:

    void DoSomethingElse()
    {
        var foo = true;
    
        if (foo = false)
        {
            // this code will never execute
        }
    }

    In this method definition, a boolean variable, foo, and defined as true. It is then used in an if statement, where it is assigned a value of false. That may be exactly what I intended (although I would argue that I should never do that), but chances are I meant foo == false (yes, the logical not ! operator would be better here… but it doesn’t work for my example). It’s not an error, however, so the compiler will compile the code. However, it will issue a warning asking if I meant == instead of =. These are issues that I would have found an in interpreted environment, but I would have needed to run the app and test it in order to find those mistakes.

    Second, the compiler checks the code for errors. Naturally, a compiler cannot catch logic errors, but it can type check and check the code’s syntax. Although, a decent IDE will do these things for you without needing a compiler, and Visual Studio does.

    Last, you get a performance boost. Compiled code runs faster than interpreted. Admittedly, .NET isn’t a truly compiled environment. Our code is compiled into an intermediate language (IL), which is then just-in-time compiled by the .NET runtime. The IL, however, is optimized, and the .NET runtime executes it. But it’s still very fast.

    In fact, ASP.NET’s raw performance is faster than PHP’s.

    Misconception: It’s Closed

    Microsoft makes the source code for the .NET Framework available for free.

    Microsoft is a company that sells software, and they are naturally very protective of their products’ source code. So, one might think that ASP.NET (and .NET in general) is closed source, but that is not the case. Microsoft makes the source code for the .NET Framework available for free, and you can step into the code while debugging your own apps. You can even build your own personal version of the .NET Framework.

    Microsoft also gives you access to the source code of ASP.NET releases, like WebForms and MVC, via CodePlex; giving you the ability to test new features and provide feedback to the ASP.NET team. I encourage every developer using .NET to download these free resources and study them. You’ll gain a greater understanding of how it works under the hood, and you can apply that same knowledge when writing your own code.

    It’s Windows Only

    Microsoft’s openness with the .NET Framework is what helped birth the Mono project, a cross-platform version of the .NET Framework. While Mono isn’t officially supported by Microsoft, the project has been publicly acknowledged by Microsoft. Mono isn’t going away; in fact, it’s growing in popularity  Regardless of what your favorite platform, you can probably use the .NET Framework and C# to write apps for it (you can even write iOS apps with Mono!).

    It’s Not in Demand

    Lastly, it’s often espoused that ASP.NET is not in demand, and that simply is not true. Demand is somewhat subjective because different areas of the world and in the country you live have different job markets. For all intents and purposes, .NET has been the development platform for Microsoft Windows environments (both for the desktop and the web) over the past ten years.

    Most software developed for Windows uses the .NET Framework, and so there is a huge opportunity for new .NET developers to find work.

    The Mono project also factors into demand. Mono is huge, and the community is just getting bigger. With its wide breadth of OS support, you can write apps for any of the big OSs, including mobile devices. There is opportunity galore, regardless of OS!

    Conclusion

    So where does all this leave us? Well, the haters and naysayers are wrong, and ASP.NET is a technology that you should try and get to know. After all, successful developers are polyglots—able to write applications in different languages for different platforms. So give ASP.NET a try. What do you say?


  • Permalink for 'Are jQuery Users Fools?'

    Are jQuery Users Fools?

    Posted: November 27th, 2011, 3:00pm MST by Jeffrey Way

    We should get this out into the open. There seems to be a commonly held belief that jQuery users are ignorant, and, more often than not, designers. Where did this come from, and is it true?

    Roots

    The JavaScript community wasn’t nearly as vibrant and passionate as it is today.

    Let’s take a trip down memory lane; we’ll rewind the clock several years – pre jQuery days. The JavaScript world was a very different scene back then. The community wasn’t nearly as vibrant and passionate as it is today. Sure, back then, there were a few libraries, like Prototype; but they never managed to grab the regular user spotlight the way that jQuery soon would. At that time, JavaScript was a widely hated language. Sometimes, it’s easy to forget that there were times when developers refused to take the necessary time to …ya know… learn JavaScript! Instead, they’d simply copy and paste their way, hoping to keep from getting that nasty JavaScript stain on their pants.

    The DOM

    What you mean is, “I hate the DOM API.”

    What these copy and paste addicts (I was one of them) didn’t realize is that, when you say, “I hate JavaScript,” what you really mean (whether you realize it or not) is, “I hate the DOM API.” No one can be blamed for feeling that way. Especially back in those days, when even IE5 support was in effect, things could get a bit nasty. Browser implementations of the DOM were the culprit; not the JavaScript language. This is due to the fact that there really wasn’t any DOM specification. As a result, browsers sort of winged it as best as they could! We have innerHTML not because of a specification, but because the Internet Explorer team decided to just throw it in there (at which point the other browser vendors reverse engineered it, and implemented it into their own browsers). But the JavaScript language, as a whole, is solid.

    In fact, many folks, including myself, would go as far to say that, as a language, JavaScript is really quite beautiful.

    jQuery

    Around that time, jQuery entered the atmosphere, and began taking the development community by storm. While other libraries like Prototype still retained a certain level of complexity and confusion for newcomers, jQuery was ridiculously easy to grasp, thanks to the fact that everything is accessible, via the jQuery object (something that it’s, ironically, often criticized for).

    Need to apply a class? Easy; doing so is tailor made for designers. jQuery allows you to use the CSS selectors you already know to query the DOM.

    $('#container').addClass('ahh-yeah');
    

    Fun Fact: Technically, though jQuery popularized the idea of a CSS selector engine, it was largely based on work by Dean Edwards.

    And then, at some point, the timeline skewed into this alternate reality…

    It literally couldn’t be simpler. By abstracting away complex code and browser quirks, developers could get back to doing what was important: creating websites and applications.

    While jQuery’s community grew in leaps and bounds, the library, itself, also continued to mature and take shape. The world was peachy.

    And then, at some point, the timeline skewed into this alternate reality (okay, not as Doc Brown as that), where, suddenly, if you labeled yourself as a proud jQuery user, certain members of the JavaScript community would consequently feel the need to stereotype you as an ignorant “designer” (regardless of whether you were or not) – certainly not a “JavaScript Developer.” How did this happen? JavaScript developers don’t use jQuery?

    The Burden of Popularity

    Everyone has an opinion about the spotlight.

    It’s only natural that, once you reach a certain – for lack of better words – popularity, you open yourself to incredible amounts of scrutiny. Everyone has an opinion about the spotlight, it seems. For example, you’ve no doubt heard endless criticism of Catholicism. “They worship statues.” Is that the only religious body with questionable history? Surely not; but it’s the largest. The United States is one of the most powerful countries in the world. Naturally, everyone has an opinion. “Americans are ignorant and fat.” Ignore the good, and spotlight the bad.

    jQuery is the most popular JavaScript library, by a landslide. Again, everyone has an opinion. I’ve read countless criticisms – everything from what it doesn’t do, to the structure of the code base. However, perhaps the biggest criticism of jQuery comes from a simple truth: its users, as an average, are less experienced with vanilla JavaScript, when compared to, say, Mootools. While some consider this to be a downside, I honestly view it as a strength – in an odd way.

    The fact that jQuery has many less-experienced users is not its downfall; it’s a testament to its appeal.

    jQuery Users Don’t Know JavaScript!

    This is the argument you’ll hear more than any other. Again, a testament to jQuery, many people learn jQuery before vanilla JavaScript. There have been countless debates on whether this is a good thing or not. In fact, these sorts of discussions extend to all abstractions.

    Personally, I feel that those who demand that newcomers first learn JavaScript before moving on to jQuery are missing one thing: JavaScript and the DOM are scary! If you throw the ES5 specification at them, they’re going to have a heart attack, unless they have a real interest in becoming a JavaScript developer. Many people simply need to add a few effects to their websites. We can’t always master everything. Are they bad people for choosing their priorities? Of course not.

    JavaScript and the DOM are scary!

    Compare this to simple Math. When you first learned how to add 2 + 2, did you do it the official way? I sure didn’t; I used my fingers. I bet you did too. Though it’s a huge simplification of the issue, is jQuery not the same way? It provides new JavaScript users with a simple and exciting entry point. Do you honestly expect them to learn about closures and objects and global variables before they even learn how to do something fun? Come, come, now.

    The strict, “Learn it the right way, or you’re a fool” viewpoint is naive, and doesn’t take into account the various learning styles that we all have.

    I view jQuery as bait. Hold it over the user’s head, get them really excited by it, and then, when they feel ready, they almost always move on to learning more vanilla JavaScript.

    jQuery Users Write Poor Code

    Once again, this is a massive generalization. Some of the biggest and most influential companies in the world use jQuery. But yes, there are lots of beginners who are still in the process of learning. Oh well; it happens. Poor code exists in every language. I’ve written a good bit of it myself, I’m proud to say! The best we can do is, rather than scorn them publicly, offer advice and tips when we can. We’re all learning. Do we really need to attack some, because they have different priorities and skill-sets?

    With popularity, comes the potential for bad advice.

    jQuery managed to generate this incredibly passionate community – from the hardcore JavaScript developers down to the designers who were amazed by how easy it was to get the job done. This passion subsequently lead to countless jQuery tutorials by community members – both good and bad. While still learning jQuery (something I’m still doing), I can guarantee that I offered some terrible advice at one point or another. It’s not too dissimilar to the PHP community. With popularity, comes the potential for bad advice.

    The Ruby Community

    This sort of pointless teaching almost hurts the community.

    In the Ruby community, there’s an interesting dynamic. Tutorials are, to generalize things, written by the veterans. In other words, if you’re going to write a Ruby on Rails article or book, you should fully expect extreme scrutiny. If you don’t have a massive level of experience, don’t you dare write about it. In some ways, this is a strength. As a student, you can more easily rest assured that what you’re learning is correct. On the other hand, PHP tutorials are all over the place. Writers sometimes focus on the insignificant, and ignore the important. You’ll often find best practice PHP tutorials, which describe whether or not it’s faster to use single quotes or double quotes. Of course, this sort of pointless teaching almost hurts the community.

    What Do You Prefer?

    It’s an interesting thing, I must say. What do you prefer? A smaller, passionate base, or an incredibly popular one, consisting of all skill levels? There’s certainly pros and cons to each.

    It’s undeniable that many of us feel a need to be trail blazers. Remember when parents began signing up for Facebook? Critics widely declared that the end of Facebook was near. Once you sacrifice exclusivity for wide appeal, people instinctively begin searching for the next thing. But that didn’t happen. The same is true for jQuery. Sure, some users have moved on to more comprehensive frameworks, like Dojo. But that’s to be expected, and should be a badge of honor for jQuery. For many, the learning cycle goes like this:

    Is that so bad?

    Real Deadlines

    It’s not like we’re coding in binary here, folks.

    There will always be the advocates who suggest that you shouldn’t use a library – period. Given the current state of JavaScript and the DOM, though, I honestly feel that this is bad advice – particularly for newcomers. They shouldn’t be expected to wrestle with frustrating browsers inconsistencies so early in the learning process. And, many times, abstractions are a very good thing! It’s not like we’re coding in binary here, folks. When you use jQuery, or any other popular library, you’re benefiting from countless tests, bug fixes, and the best minds in the industry.

    Now, certainly, you’re not required to use somebody else’s framework. Create your own library, if you have the ability; that works too! The goal is to:

    jQuery is not “a designer’s library,” but it appeals to designers. It’s not as class-based as other libraries, but this makes the entry point for newcomers far more painless. So what we end up with is a library that helped reignite the JavaScript community. It’s simple enough to appeal to first-timers, and powerful enough to be used by the largest companies in the world. Why exactly is it being criticized again?


  • Permalink for 'Latest Web Development Jobs at FreelanceSwitch'

    Latest Web Development Jobs at FreelanceSwitch

    Posted: November 25th, 2011, 11:15am MST by David Appleyard

    Looking for a new web development job? The FreelanceSwitch Job Board is a great resource of freelance gigs and opportunities. New opportunities are posted every day for web developers, and come from a wide range of potential clients. Today we’re showcasing a few of the latest positions that might be perfect for Nettuts+ readers!

    Developer for Online Journal Platform

    Budget: $10,000 + — Location: Anywhere, Australia Preferred

    Calling all talented developers! We are in need of a confident website developer(s) who have experience in NLM XML to PDF/HTML conversion to build an online journals platform which can be managed by the client.

    The website, along with any potential sub-sites, are to be efficiently managed by a single CMS. For a quick overview, the platform needs to be developed with the below features in mind:

    Applicants will be required to sign a NDA before receiving additional information about the platform. Successful applicants will be notified before December 20th as to whether they have received the job.

    Find Out More

    Application Developer & HTML5 Specialist

    Budget: $1,000 to $2,500 — Location: Anywhere

    Since we are starting to get a lot of requests from our clients to develop mobile and desktop applications, I really need someone with whom I can create long term trustworthy relationship.

    You need to know your way with Flex and AS3 if possible (I know it is dying but still…) and any other iOS programming you are good at. Please send your skill set and links to completed projects. And of course your hourly fee – please have in mind I need a sub-contractor which means it will not be one time deal.

    We are also looking for HTML5 specialist — please send examples of work in that area as well. I look forward for your responses.

    Find Out More

    Startup Looking for Rails Enthusiasts

    Budget: $500 to $1,000 — Location: Anywhere

    Exvo is a young informal startup running several projects. We’re working on an innovative distributed web based operating system, a distributed platform to manage and run your company from and several other side projects.

    To support these very ambitious plans, we need several additional experienced Rails developers. You can work from anywhere, just as long as you love what you do and enjoy making beautiful code. You will join a team made up of people around the world, who will challenge you to be the best you can be and most of all, have a lot of fun in the process. We currently have three teams of varying sizes.

    We’re looking for junior, intermediate and senior developers with a willingness to learn, good communication skills, a passion for Ruby, a love for Rails, and generally good development skills.

    Find Out More

    Freelance Developer for Web-Chat App

    Budget: $1,000 to $2,500 — Location: United States

    Ever heard of Omegle or Iddin.com? Well I currently have a site that uses a similar model with a much more useful cause that is in need of a complete revamp. I need someone who can re-create a very simple chat script with newly added features. It also needs to be optimized for volume. I also need some membership features, but nothing too extensive.

    Programmer should be proficient with PHP, and Java, Flash is a plus, but must have experience developing a chat app. Features needed include an admin panel, login/registration, user profile with feedback, rating, comments, and a few others. I have a fully written design document ready upon request.

    Find Out More

    And Lots More…

    These are just a handful of the positions currently being offered over at at Job Board, so be sure to head over and take a look at the full selection. We also have a few RSS feeds that will keep you updated with new openings, and you can even choose only to hear about those specific to web development!

    To apply for any of these jobs, simply pick up a FreelanceSwitch membership for an affordable $7 a month. See something you like? Join now!


  • Permalink for '50 Practical, Problem Solving Items'

    50 Practical, Problem Solving Items

    Posted: November 25th, 2011, 11:14am MST by Siddharth

    In the real world, we have to adhere to tight deadlines — so tight that it’s often not feasible to create everything from scratch. In these situations, a well-built and tested template can be of enormous help. I’ll show you some of my favorites today, including everything from landing pages, to resumes, to under construction templates!

    Admin Templates Adminica | The Professional Admin Template Tutorial Image

    Adminica is a cleanly coded, beautifully styled, easily customisable, cross-browser compatible Admin Template and Web Application Interface.

    TERMINATOR – 13 different Admin Backend pages Tutorial Image

    Admin backend template that has a hell of a lot of features. It’s designed with cool “Storm Black / Aluminium” colors to make your backend even better than it is

    White Label – a full featured Admin Skin Tutorial Image

    A full featured skinable and responsive CMS /Admin Panel with custom plugins, widgets, forms, validations, charts, galleries and much more

    Grape – Professional & Flexible Admin Template Tutorial Image

    Grape is a professional and very flexible admin template for huge and small backend solutions. It includes custom plugins, forms, validations, charts, tables, notifications and much more.

    Chameleon Circuit – Full Featured Admin Theme Tutorial Image

    Chameleon Circuit is a beautifully coded full featured admin panel theme ready to be implemented in the back end of your application, or as an intranet theme! The theme, like its namesake, can change colors into anything you want, so instead of a specific number of skins, you have an unlimited variation!

    Admin Control Panel v2 Tutorial Image

    Features a very slick design, rich typography ans is tablet ready (iPad + Android)

    Streamlined – Content Management/CRM Template Tutorial Image

    Streamlined is an admin template for Contact Management and CRM applications. It includes element styles for buttons, tabs, tooltips, progress bar, and others.

    vPanel – Application Framework Tutorial Image

    vPanel is an application framework with all the necessary features and tools you would need to build an admin panel or a software-as-a-service app. It comes with an html template version, so you can use it with other frameworks, and a zend framework ready version.

    Constellation Complete Admin Skin Tutorial Image

    Constellation is a powerfull admin skin for building advanced backends, both for desktop and mobile users. It provides a wide range of styles from data visualization to lists and calendars, all fluid and nestable. This skin is build on HTML5 and CSS3 , and is powered by jQuery for maximum user experience.

    Email Templates FeastMail 2 – Christmas Email Template Tutorial Image

    Feast Mail 2 is a Christmas email template with twelve exclusively designed Christmas collages. It is a great possibility to make warm relations with your clients by sending them this beautiful Christmas greetings email! This email has all you need to promote your products this Christmas and make awesome discount propositions.

    Market – Newsletter and Template Builder Tutorial Image

    Market features 8 Prebuild Layouts, 24 Color Variations, 26 different Elements and 768 HTML Files.

    High Definition E-mail Template Tutorial Image

    Aren’t you making any money from your Apps? Do you think more people should see your awesome designed software? Boost up your views with this extremely clean designed E-mail Template.

    Christmas Season Email Template
    Tutorial Image

    Christmas Season Email Template is a premium HTML email template designed and built especially for the Holiday Season to showcase anything from your mobile or desktop application, portfolio, product(s), services or simply to share news with customers, friends and clients.

    Versatile Newsletter 3 – automated layout creator! Tutorial Image

    The combination between the 11 unique newsletter templates, an easy to use automated layout creator that allows the creation of new newsletter templates instantly, modular layouts that simplify extending/ adapting newsletter templates and robust, properly tested and commented source code makes Versatile Newsletter 3 one of the most complete newsletter packages you can buy at themeforest.

    COPRO – 14 E-mail Templates Tutorial Image

    14 modern corporate newsletter templates made in 7 different color schemes (orange, red, purple, blue, turquoise, green, gray) with inline CSS and flexible table structure for quick and easy layout manipulation (delete/copy/replace table rows inside and between layouts).

    Express Mail Newsletter Template Tutorial Image

    Express Mail is a template design that caters for all businesses. The template comes with all the essential generic information and elements to get you started.

    Virtual Business Cards Stylish Vcard – 11 Modern Skins Tutorial Image Squares – HTML5 vCard/Portfolio Template Tutorial Image

    Squares is a vCard/Portfolio template built with the latest web standards and best practices. Introduce yourself and your work to future clients and employers through a clean and simple web page.

    vCard – a personal profile template vCard – a personal profile template Tutorial Image

    vCard is a simple template designed to showcase your online persona in a list of your social network profiles. There’s also space fo an about page and a fully functional AJAX contact form is included.

    vCard – a personal profile template Tutorial Image

    DotMe is a premium HTML /CSS business card template perfect for any creatives – designers, developers or even photographers.

    Strokes! Personal Website Template Tutorial Image

    Strokes! is a vibrant personal website template, which can be used as a virtual business card on the web.

    Grey & Black – Stylish Online vCard Html Template Tutorial Image

    Grey & Black is a professional online vCard template that is minimal and clean in design. It will help you to create your very own virtual business card, with the ability to showcase your featured projects in style.

    Introducto – Personal Website / V Card Template Tutorial Image

    Introducto is a virtual business card (vcard) template intended for people who want to set up a professional looking web presence in minutes.

    My VCard – Premium Template Tutorial Image

    This is a clean and professional flash like template, perfect for personal website. It’s a simple and minimal looking site with a rare shuffle effect.

    Elegant Vcard Tutorial Image

    Features 6 backgrounds, 4 Pages, fully labeled layered, grid based, easily sliceable PSD files and valid CSS /XHTML

    Under Construction Templates Landerous – Under Construction Page Tutorial Image

    Landerous is just another Under Construction/Coming Soon/Landing template – specially created to tell your visitor that your site is in progress. Clean and professional look with unique design will satisfy all your needs.

    Under Construction page with twitter & pie graph! Tutorial Image

    Make sure your visitors know whats going on with this Under construction site template that features a feed of your latest tweets (which can be easily removed if you dont use twitter) and a pie chart that is easy to change to reflect your progress!

    NEOTERIC—The Ultimate Under Construction Page! Tutorial Image

    NEOTERIC is a clean single page “Under Construction/Coming Soon” template in 10 SKINS designed to keep your users up to date on your site’s progress.

    Easy Coming Soon with Pie Chart, 10 colors + Bonus Tutorial Image

    Easy Coming Soon is an easy and flexible under construction page that will easily let you define your upcoming website and represent it’s current status, supported by a nice looking easily editable pie chart, and ajaxed mailing-list form to keep your visitors up to date.

    Chronos Under Construction Template + WP Theme Tutorial Image

    Easily customize all settings in PHP configuration file or simply install Chronos as a WordPress theme and manage everything from one single page, with a click of a mouse.

    Launch Pad – Full Screen Image Under Construction Tutorial Image

    Launch Pad is a stylish full screen background under construction template with animated progress bar and countdown timer, perfect for showing off your visual work while your website is being developed. Background switcher controls allow you to cycle through background images, which are preloaded to cut loading time. A Fancybox gallery is included so you can show your work.

    Marketing and Landing Pages Promo – Landing Page for Digital Product Sales Tutorial Image

    Sporting a clean minimal style, with lots of breathing space, ensuring nothing get in the way of your product’s showcase. Easy to set up, maintain and easy to replicate for new products, this sophisticated little template is a steal.

    TheLanding Landing Page Tutorial Image

    TheLanding is a simple landing page with half or full header video options! Easily customize the landing page with the included instructions.

    Oceanic Landing Page Tutorial Image

    Oceanic Landing Page is a premium landing page design for any kind of app or download product – even just a service – your choice! With multiple sections available, plus a tabbed area for a huge amount of information if required, this template takes good use of the Z Reading pattern to guide the eye around the design and ultimately convert your visitors in to buyers.

    Unveiled – Ultimate Product Focused Landing Page Tutorial Image

    Unveiled is the ultimate product-centered landing page. With an eye-catching design, the call-to-action high-up the page and an impactful splash intro – this theme is sure to convert your visitors into customers.

    BookPage – Sell your books with Style! Tutorial Image

    BookPage is the landing page template for all those internet marketeers who are releasing their own (E) Book. It has everything you need to show of your hard work.

    Autopilot Landing Page (3 Themes) Tutorial Image

    Autopilot is a landing page design best suited for all businesses and industries. The template comes with one HTML and one PHP file (contact form). It comes with three themes – realistic, festive and generic.

    Resumes and CVs Clean CV / Resume Html Template + 4 Bonuses! Tutorial Image

    Clean Cv / Resume is a html template that will help you set up a professional online CV in minutes and broaden the chance of finding a suitable job as many recruiters resort more and more to browsing online for prospective applicants instead of advertising their position and calling for applicants.

    Awesome Online Resume/CV Tutorial Image

    This is a clean, modern and colorful (optional) Resume/CV theme suited for everyone! It is very easy to edit and includes 10 minutes of video documentation showing you exactly what to do!

    Bold – CV / Resume Template – Minimal & Smart Tutorial Image

    Bold is a minimal and clean one-page CV / resume HTML + PHP template featuring print-ready and mobile-ready versions, downloadable PDF version generated on-the-fly, working Ajax contact form, jQuery lightbox gallery and social media section. It is also very easily editable and configurable.

    Professional & Clean HTML CV RESUME Tutorial Image

    This template is a complete HTML CV Resume. Useful to present your skills and your personal portfolio.

    Pinstripe – Premium Resume / CV Template Tutorial Image

    This is a professional pinstriped CV / Resume with a plethora of slick jQuery effects. A great way to present yourself to any potential employers / clients.

    Typographic CV – impressive resume template Tutorial Image

    Typographic CV is online resume / CV template. It was created to impress your future employers or clients. And it definitely will: strong typographic design, good visual hierarchy, unique layout, cool gallery section and much more.

    JumpBox – Animated Resume/Portfolio Tutorial Image

    Jump Box is a premium Ajax based CV(Resume)/Portfolio animated website template. This template is perfect to use for small websites. It can be used as a CV/Portfolio Template, Landing Page, or any website with a little number of pages.

    404 and Error Pages Lost in Space – Error 404 Lost in Space – Error 404

    Tutorial Image

    Simple and aesthetically pleasing template with animated background. Valid HTML and CSS. Ready for all common HTTP errors, like 401, 403, 404, 500 and 503 or for many other purposes.

    Modern Custom 404 Error Page Tutorial Image

    You can use this Modern Custom 404 Error Page pack for any type of errors on your site. It is designed with usability in mind – to help the user get what he wants . It’s fully customizable and browser compatible and you can choose between 16 color schemes.

    Save me – 404 Error Page Tutorial Image

    “Save me” is an unique new error page, that focuses on helping the user through the frustration of getting a website error, in an user friendly and intuitive way.

    Cosmo Error Page Tutorial Image

    Cosmo Error page. It has all you need – links to your other pages, links to your social profiles, working contact form.

    Custom 404 Error Page – Missing Jigsaw Piece Tutorial Image

    Missing jigsaw piece custom 404 error page, in two styles; grey and dark gloss. The layout has subtle embossed text effects and textures, giving you an original look to the design.

    Lost in the Clouds – Error 404 Tutorial Image

    Valid HTML and CSS. Ready for all common HTTP errors, like 401, 403, 404, 500 and 503 or for many other purposes.


  • Permalink for 'Easy Package Management for CodeIgniter with Sparks'

    Easy Package Management for CodeIgniter with Sparks

    Posted: November 24th, 2011, 9:31am MST by RJ Zaworski

    Sparks is a new package-management system for CodeIgniter that extends the core with support for gem-like sparks.

    This tutorial interweaves an entry-level overview of the architecture and usage of the sparks system with the creation of dovecote—a simple spark for managing RSS data.

    Introduction

    Packages are blocks of recyclable code that can make developers’ lives a whole lot easier.

    CodeIgniter’s developers have long salivated over package managers like gems and npm, systems that empower their respective communities with tools and a central repository for developing, recycling, and sharing useful application components with each other. Now, the wait is over. Thanks to a new system—sparks—CodeIgniter developers can finally rejoice, as a growing package management system is finally their own.

    Overview

    If you haven’t worked with them before, just think of packages as blocks of recyclable code that can make developers’ lives a whole lot easier. Maybe you need an interface to an storage bucket in Amazon’s cloud? Skip the late nights pouring over S3 documentation and just grab the spark.

    For its part, the sparks system consists of three parts:

    1. A central repository (getsparks.org) for storing and sharing sparks
    2. A utility for managing the sparks installed in a given CodeIgniter app
    3. The sparks themselves

    For the purposes of this tutorial, we’ll introduce the first two but focus on spark development and some basic considerations in developing a spark. Sound good? Let’s see how it’s done.

    Step 1: Installing Sparks

    It’s official: sparks is slated for integration into CodeIgniter’s core, possibly as soon as the upcoming 2.1 release. But since it isn’t part of a default installation—yet—you’ll need to set the system up manually.

    If you’re on OSX or Linux, or if you have PHP’s command-line interface installed on Windows, installation is as simple as installing a clean copy of CodeIgniter and issuing the following in the installation directory:

    $ php -r "$(curl -fsSL [getsparks.org] 

    If all went well, you should see something like this:

    Installing the sparks system

    If for some reason that didn’t work, or if you’re on Windows and haven’t added PHP to your command path, you can also install sparks manually. It’s a little more work, but the result is the same:

    1. Adding a directory named sparks in the root of your codeigniter directory
    2. Adding a custom Loader Class to application/core/MY_Loader.php
    3. (optional) Downloading and extracting the sparks command line utility into your codeigniter directory

    Your CodeIgniter installation should now be patched to support sparks.

    Step 2: Getting Started

    In medieval Europe, every manor house included a small outbuilding for pigeons to nest called a dovecote. Since we’ll be building a spark that involves both tweeting and feed, the name is appropriate enough. But it also meets the only requirement on naming: to be included in the repository at GetSparks.org,

    GetSparks project names must be unique

    Outlining the Spark

    Before we can code, we’ll need to layout a project. In the sparks directory in the root of your CodeIgniter installation (create it, if it doesn’t exist), add a new folder to hold the spark:

    /sparks/dovecote

    Convention dictates that sparks are organized by version, so we’ll need a subfolder to hold the first draft. 0.0.1 is a good place to start.

    /sparks/dovecote/0.0.1

    This folder is where all the action will take place. When the rest of the tutorial refers to our “spark directory”, this is it.

    The spark.info File

    Things are looking pretty bare so far, but we’re ready to start filling them out. The first piece in the spark–and the only file technically required by the spark utility—is spark.info. Create a new file called spark.info in your spark directory, and add the following:

    name: dovecote
    version: 0.0.1
    compatibility: 2.0.2
    dependencies:
       Atomizer: 0.0.1
    tags: ["twitter","api","social"]
    

    These fields represent all the information the spark utility needs manage the version and dependencies of all the sparks in this CodeIgniter installation. The utility will look for five things, but only the first three are required:

    Even if you aren’t planning to use the spark utility yourself, it’s still polite to include a spark.info file with any spark you plan on distributing. One of the real advantages to managing sparks this way, rather than pasting them directly into the sparks directory, is that the spark manager can use the compatibility, dependency, and version information in each spark to ensure nice play with the current CodeIgniter installation—and each other. There’s another benefit, too, as we will see in a moment: sparks installed outside of the manager utility must have their dependencies installed manually.

    Organizing the Spark

    With the info file written, it’s time to give the spark some structure. Create four new folders in the spark directory:

    If you’ve worked with CodeIgniter before, these are probably familiar names. CodeIgniter’s loader class treats sparks as packages, meaning that the contents of these directories are checked for any application components that can’t be found in the /application directory. For now, this applies to five types of resources:

    Step 3: Writing the Spark

    Before we begin coding, take a moment to ensure that your spark directory contains all the necessary pieces.

    Installing the sparks system

    Everything in order? Let’s proceed.

    Create a file in the newly-created config directory and name it dovecote.php. We’ll store a few basic options here to tell the spark where it can find RSS data:

    <?php /** config/dovecote.php **/
    
    // Username to retrieve tweets from:
    $config[ 'twitter' ]    = 'getsparks';
    
    // API endpoint to query for tweets:
    $config[ 'twitterURL' ] = 'http://twitter.com/statuses/user_timeline/%s.rss';
    
    // Feed carrying RSS data:
    $config[ 'feedURL' ]    = 'http://feeds.bbci.co.uk/news/rss.xml';
    
    ?>
    

    Not much to it—we’ve defined a twitter username (@getsparks) to grab tweets from, provided an API endpoint for Twitter’s Timeline API, and added an additional URL to search for RSS stories.

    Now the spark knows where data can be found, it’s time to go retrieve some feeds. To do this, we’ll need to create a library—call it dovecote.php—and save it in the libraries directory:

    <?php /** libraries/dovecote.php **/ 
    
    class dovecote {
    
        protected $ci, $timeline;
    
        public function __construct() {
            $this->ci = &amp;get_instance();
        }
    
        public function retrieve() {
    
            // build twitter request URL
            $twitterURL = sprintf( $this->option( 'twitterURL' ), $this->option( 'twitter' ) );
    
            // get RSS Data
            $tweets = $this->ci->atomizer->loadURL( $twitterURL );
            $feed = $this->ci->atomizer->loadURL( $this->option( 'feedURL' ) );
    
            // set channel information for new feed
            $info = array(
                'title' => 'Convolved feed'
            );
    
            // mix the two feeds together
            $this->timeline = $feed->convolve( $tweets, $info );
    
            return $this->timeline;
        }
    
        public function publish() {
            header('content-type: application/rss+xml');
            echo $this->timeline->save();
        }
    
        // retrieve an option ($key) from config files
        protected function option( $key ) {
            return $this->ci->config->item( $key );
        }
    }
    
    ?>
    

    This library provides helper functions to retrieve options from our config file and publish an RSS feed, but the critical piece is retrieve(). This function grabs RSS data from the providers described in dovecote’s configuration file in several steps:

  • Permalink for 'Getting Started with MongoDB'

    Getting Started with MongoDB

    Posted: November 23rd, 2011, 2:29pm MST by Matthew Setter

    Ready to get in and start learning about MongoDB, one of the coolest technologies for web developers?

    In this new series, you’ll go from beginner to pro and be able to use Mongo just as easily as MySQL in your web apps. But first, let’s look at the basics.

    Why MongoDB?

    What if you could store the programmatic models almost exactly like you model them?

    In object-oriented development, we’re encouraged to approach code development through logical models, so that we can more readily conceptualise it in our mind. When we do this, we’re better able discern the logical operations used to interact with it and information that it would contain at different times.

    What if you could store the programmatic models almost exactly like you model them? What if you could store them as they are instead of in a series of rows in tables? By learning about MongoDB, you’re going to be able to do just that!

    In this series, we’ll be learning everything from the basics of MongoDb, such as creating, updating and deleting databases and records, to being able to perform complex searches for data and elementary data mining with MapReduce. So, without much ado – let’s get started!

    Note: This tutorial is done from the perspective of NIX based system a la Mac OSX, Linux BSD and so on. But you should be able to follow along if you’re running Windows pretty well as there are builds for most platforms.

    Step 1 : Installing Mongo

    Ok, so here’s where the fun begins. We’re going to get started by installing Mongo. Go to the MongoDb website and click on the downloads link.

    The MongoDb link to downloads

    This will bring you to a page where you can grab a build for your platform and architecture.

    The MongoDb download options

    This tutorial only covers stable releases, so please do not grab a nightly build. Once it’s downloaded, please install it as per the requirements of your platform.

    If you’re on a Nix machine, then please use its package manager to install the latest version for your platform.

    With that out of the way, fire up a terminal and type in mongo. That will open up the Mongo shell and let us get under way. All being well, you’ll see output similar to below:

    The MongoDb shell

    If you see that, then you’re ready to go.

    Step 2 : Creating a Database/Inserting Records

    Initially, no database is created. But don’t worry, they’ll instantly be created when we start inserting our records, which we’re going to do right now. Copy the content below and paste it in your mongo shell

    db.nettuts.insert({
        first: 'matthew',
        last: 'setter',
        dob: '21/04/1978',
        gender: 'm',
        hair_colour: 'brown',
        occupation: 'developer',
        nationality: 'australian'
    });
            db.nettuts.insert({
        first: 'james',
        last: 'caan',
        dob: '26/03/1940',
        gender: 'm',
        hair_colour: 'brown',
        occupation: 'actor',
        nationality: 'american'
    });
    db.nettuts.insert({
        first: 'arnold',
        last: 'schwarzenegger',
        dob: '03/06/1925',
        gender: 'm',
        hair_colour: 'brown',
        occupation: 'actor',
        nationality: 'american'
    });
    db.nettuts.insert({
        first: 'tony',
        last: 'curtis',
        dob: '21/04/1978',
        gender: 'm',
        hair_colour: 'brown',
        occupation: 'developer',
        nationality: 'american'
    });
    db.nettuts.insert({
        first: 'jamie lee',
        last: 'curtis',
        dob: '22/11/1958',
        gender: 'f',
        hair_colour: 'brown',
        occupation: 'actor',
        nationality: 'american'
    });
    db.nettuts.insert({
        first: 'michael',
        last: 'caine',
        dob: '14/03/1933',
        gender: 'm',
        hair_colour: 'brown',
        occupation: 'actor',
        nationality: 'english'
    });
    db.nettuts.insert({
        first: 'judi',
        last: 'dench',
        dob: '09/12/1934',
        gender: 'f',
        hair_colour: 'white',
        occupation: 'actress',
        nationality: 'english'
    });
    

    All good? Excellent! To confirm that the database and accompanying records have been created, type in the following command:

    db.nettuts.find()

    If everything went to plan, then you will see the following output:

    Finding all records

    This shows that all of the records were created in the database. One thing to note before we go any further is the id field. This is auto generated by Mongo for you, if you don’t specify an id. The reason is that every record must have a unique id field.

    You can see that we have one record for each of the ones that we insert – now we’re ready to start querying them.

    Step 3 : Searching For Records

    You remember the previous command? It retrieved and displayed every record in the database. Helpful, yes, but how do you be more specific? How do you find all female actors, filtering out the males? That’s a good question and the answer is selectors.

    Selectors

    Selectors are to Mongo what where clauses are to SQL. As with where clauses, Mongo selectors allow us to do the following:

    Records That MUST Match

    Let’s start with a basic selector. Say that we want to find all actors that are female
    . To accomplish that, you’ll need to run the following command:

    db.nettuts.find({gender: 'f'});

    Here we have specified that gender must be equal ‘f’.

    Running that command will return the following output:

    Finding all female records

    What if we wanted to search for male actors? Run the following command:

    db.nettuts.find({gender: 'm'});

    We’ll get the following results:

    Finding all male records Searching with Multiple Criteria

    Let’s step it up a notch. We’ll look for male actors that are English.

    db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}]});

    Running that will return the following results:

    Finding all male, English, records

    What about male actors who are English or American. Easy! Let’s adjust our earlier command to include the Americans:

    db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'}]}); 

    For that query, we’ll see the following results:

    Finding all male, English or American, records Step 4 : Sorting Records

    What if we want to sort records, say by first name or nationality? Similar to SQL, Mongo provides the sort command. The command, like the find command takes a list of options to determine the sort order.

    Unlike SQL, however we specify ascending and descending differently. We do that as follows:

    Let’s have a look at an example:

    db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'}]}).sort({nationality: -1}); 

    This example retrieves all male, English or American, actors and sorts them in descending order of nationality.

    Finding all male, English or American, records sorted by nationality

    What about sorting by nationality in descending order and name in ascending order? No problem at all! Take a look at the query below, which is a modified version of the last one we ran.

    db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'}]}).sort({nationality: -1, first: 1}); 

    This time we retrieve the following results et:

    Finding all male, English or American, records sorted by nationality first and first name second

    You can see that this time Arnold Schwarzenegger is placed before Tony Curtis.

    Step 5 : Limiting Records

    What if we had a pretty big data set (lucky us, we don’t) and we wanted to limit the results to just 2? Mongo provides the limit command, similar to MySQL and allows us to do just that. Let’s update our previous query and return just 2 records. Have a look at the following command:

    db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'}]}).limit(2); 

    From that command, we’ll get the following results:

    Limit output to 2 records

    If we wanted the third and fourth records, i.e., skip over the first two? Once again, Mongo has a function for that. Have a look at the further customisation of the previous command:

    db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'}]}).limit(2).skip(2); 

    Running that will return the following results:

    Limit output to the 3rd and 4th records

    You can see from the original result set that the first two were skipped.

    Step 6 : Updating Records

    As expected, Mongo provides an option to update records as well. As with the find method and SQL queries, you need to specify the criteria for the record that you want to modify, then the data in that record that’s going to be modified.

    Let’s say that we need to update the record for James Caan specifying that his hair is grey, not brown. Well for that we run the update function. Have a look at the example below:

    db.nettuts.update({first: 'james', last: 'caan'}, {$set: {hair_colour: 'brown'}});

    Now when you run that, if all went well, there won’t be anything to indicate whether it was a success or failure. To find out if the record was update properly, we need to search for it. So let’s do that.

    db.nettuts.find({first: 'james', last: 'caan'});

    After this you will see the following result:

    Update record

    This shows that the update worked. One word of caution though, if you don’t pass in the $set modifier, then you will replace the record, if it’s available, instead of updating it. Be careful!

    Step 7 : Deleting Records

    I think by this stage, you have really started to get the idea of working with Mongo. That’s right, if you want to delete a record, you have to pass in a set of selectors, as you also would with SQL, to determine the set of records to delete. If you don’t do this, you will delete all records – and the database.

    So, let’s say that we don’t want James Caan in our list of actors. Let’s remove him from the database using the following command:

    db.nettuts.remove({first: 'james', last: 'caan'});

    As with update, no visible output is provided to indicate whether we were successful or not – so let’s do a search to double check.

    db.nettuts.find({first: 'james', last: 'caan'});

    After this, you should see no results returned. If that’s what you’ve found, then we’ve successfully deleted James Caan from our database. But what if we want to delete all the records from the database?

    Well, to do that, just remove the selectors from the previous call to remove, as below.

    db.nettuts.remove();
     db.nettuts.find();

    After running both commands above, we’ll see no output, indicating that the database, with all records have now been removed.

    Remove all records Conclusion

    In this rapid introduction to using MongoDB we looked at:

    With this knowledge, you can go, practice, and learn more about this wonderful technology. If you want more information, feel free to check out the MongoDb website or follow @mongodb on Twitter.

    In the next tutorial, we’re going to start to learn more about complex queries. So stay tuned and thank you so much for reading.


  • Permalink for 'How to Generate a Complete Excel Spreadsheet From MySQL'

    How to Generate a Complete Excel Spreadsheet From MySQL

    Posted: November 22nd, 2011, 11:15am MST by David Brumbaugh

    A CSV (Comma Separated Value) file is usually sufficient for exporting MySQL data as an Excel Spreadsheet. These CSV files are data only though. A real Excel spreadsheet has formatting, formulas and perhaps even graphics — the difference between a simple method of data transfer and a professional report.

    This tutorial shows how to use open source PHP components to create "real" Excel spreadsheets from MySQL SELECT statements. Interested? Let’s get started!

    Overview

    PHPExcel is a set of PHP classes that allow you to to read and write different spreadsheet file formats as well as manipulate the spreadsheets themselves. Before you begin, you’ll need a copy of PHPExcel. To get the latest copy of the PHPExcel component, go to [www.phpexcel.net] and download the latest stable release.

    An Excel spreadsheet is a series of pages (called Worksheets) which have numbered rows and alphabetically labeled columns.

    The Fundamental Relationship Between Data Tables and Spreadsheets

    A SQL SELECT statement returns a result set that is a collection of labeled columns with the data contained in rows. In PHP/MySQL, each row of a result set can be (and often is) represented by an associative array, where the key to the associative array is the column name.

    An Excel spreadsheet is a series of pages (called Worksheets) which have numbered rows and alphabetically labeled columns.

    The general technique will be to map one SQL statement to one spreadsheet page (worksheet), specifically by matching column names in the associative array returned by the PDO fetch command to alphabetical column labels on the spreadsheet.

    Step 1: Understand How to Properly Label Alphabetical Columns

    The key to this technique is the underlying column labeling algorithm, which will allow you to properly label alphabetical columns for an arbitrarily large number of columns. As previously noted, in an Excel spreadsheet, columns are identified with letters and rows are identified with numbers. If your query will contain less than 26 columns, you could simply stop at "Column Z". However, many queries have substantially more columns than that.

    Excel Column Labelling Scheme

    When the column labels get to Z a second letter is added: "A… Z,AA, AB … AZ". After "AZ" comes "BA" as shown below.

    The Column Labeling Algorithm

    The following PHP snippet shows how to label column headers from "A" to "ZZ".

    $keys = array_keys($row); // Get the Column Names
    $min = ord(&quot;A&quot;); // ord returns the ASCII value of the first character of string.
    $max = $min + count($keys);
    $firstChar = ""; // Initialize the First Character
    $abc = $min;   // Initialize our alphabetical counter
    for($j = $min; $j <= $max; ++$j)
    {
    	$col = $firstChar.chr($abc);   // This is the Column Label.
      $last_char = substr($col, -1);
    	if ($last_char> "Z") // At the end of the alphabet. Time to Increment the first column letter.
    	{
    		$abc = $min; // Start Over
    		if ($firstChar == "") // Deal with the first time.
    			$firstChar = "A";
    		else
    		{
    			$fchrOrd = ord($firstChar);// Get the value of the first character
    			$fchrOrd++; // Move to the next one.
    			$firstChar = chr($fchrOrd); // Reset the first character.
    		}
    		$col = $firstChar.chr($abc); // This is the column identifier
    	}
    	/*
    		Use the $col here.
       */
    
      $abc++; // Move on to the next letter
    }
    

    This algorithm will not go beyond ZZ. The algorithm is implemented (in a slightly different form) in the accompanying source file in the MySqlExcelBuilder::mapColumns member function.

     

    Step 2: Format and Test Your SQL Statement A Simple Schema

    The schema below shows a simplified customer/order relationship. The SQL CREATE statements for the schema below are included in the file xls_sample.sql in the zip file that accompanies this tutorial.

    A "Quick and Dirty" SELECT Statement

    It’s common practice to simply grab the data quickly from these tables in a SQL statement that looks something like this:

    SELECT * FROM `order`,`customer`,`order_item`
             WHERE `customer_id` = `customer`.`id`
             AND item_id = `order_item`.`id`
    

    The primary advantage of this "quick and dirty" statement is that it’s fast and easy to program. The results usually don’t look very good.

    PHPMyAdmin is a tool for MySQL database administration that comes standard with many hosting plans. To prototype and test your spreadsheet pages you can use the SQL composition tools that come with PHPMyAdmin.

    The following screenshot shows the result of the query above:

    And a close up of some of the columns shows that the column names are meaningful to programmers, but unattractive to business users.

    The column names are not capitalized according to "real world" rules, there are underscores instead of spaces, etc.

    Get More Attractive Results From a SELECT Statement

    We want to format the SELECT statement to look like business a report on the spreadsheet. So, using the PHPMyAdmin tool, edit the SQL statement so that the column names are real words and only the columns the business user wants to see are displayed. The reformatted SQL Statement looks like:

    SELECT `name` AS `Customer Name`,
            `email_address` AS `Email Address`,
            CONCAT( right(`phone_number`,3) , '-' , mid(`phone_number`,4,3) , '-', right(`phone_number`,4)) AS `Phone Number`,
            `item_sku` AS `Part Number`,
            `item_name` AS `Item Name`,
             `price` AS `Price`,
            `order_date` as `Order Date`
     FROM `order`,`customer`,`order_item`
     WHERE `customer_id` = `customer`.`id`
             AND item_id = `order_item`.`id`
    

    Resulting in :

    The prototype above demonstrates very much what the spreadsheet page will look like.

    Step 3: Displaying A MySQL Result Set on A Spreadsheet Page

    The Class MySqlExcelBuilder encapsulates the functionality necessary to add SQL statements to an Excel spreadsheet page using PDO and PHPExcel. The full class is in the accompanying zip file.

    The MySqlExcelBuilder Class

    This class enables an arbitrary number of SQL result sets to be placed on named pages within an Excel spreadsheet. The following code snippet shows the important data members.

    <?
    class MySqlExcelBuilder
    {
            protected $pdo; // PHP Data Object
            public $phpExcel; // PHP Excel
            protected $sql_pages = array(); //Sheet Name, Sql Statement, Options
    
    Preparing Each Page

    The spreadsheet image below is a prototype made in Excel to show what we might want the spreadsheet to look like when it is rendered.

    The add_page member function is used to add SQL Statements to the named pages:

    public function add_page($wsName,$sql,$total_colums=null,$start_col="A",$start_row="1")
    {
    	 // $wsName, is the Work Sheet Name that will be shown on the tab at the bottom of the spreadhseet
    	$this-&gt;sql_pages[$wsName]['Sql'] = $sql; // This is the statement to be executed
    	$this-&gt;sql_pages[$wsName]['Col'] = $start_col; // This is the column to start putting data into.
                                                    // Note that it must be between "A" and "Z", staring in Column "AA" and after is not supported.
    	$this-&gt;sql_pages[$wsName]['Row'] = $start_row; // This the row number to start putting data into
    	$this-&gt;sql_pages[$wsName]['Totals'] = $total_colums; // This is a comma delimted list of Column Names (NOT Column Labels) that will be totaled.
                                                          //If null it will be ignored.
    
    }
    

    The sql_pages data member holds the information we want to use to put sql on pages.

    Member Function Usage Example

    This snippet is an example of how to use the add_page member function:

    $xls_sql = new MySqlExcelBuilder('database','username','password');
    $sql_statement = &lt;&lt;&lt;END_OF_SQL
    
    SELECT `name` AS `Customer Name`,
            `email_address` AS `Email Address`,
            CONCAT( right(`phone_number`,3) , '-' , mid(`phone_number`,4,3) , '-', right(`phone_number`,4)) AS `Phone Number`,
            `item_sku` AS `Part Number`,
            `item_name` AS `Item Name`,
             `price` AS `Price`,
            `order_date` as `Order Date`
     FROM `order`,`customer`,`order_item`
     WHERE `customer_id` = `customer`.`id`
             AND item_id = `order_item`.`id`
             AND `item_sku` = 'GMG1'
    
    END_OF_SQL;
    
    $xls_sql->add_page('Gold Mugs',$sql_statement,'Price');
    

    The illustration below shows how the add_page member function should map to the spreadsheet.

    Step 4: Building the Spreadsheet Understanding PHPExcel

    If you understand how to manipulate an Excel spreadhseet with your mouse and keyboard, you can become quite adept at using PHPExcel. PHPExcel is built on the principle of manipulating the underlying spreadhseet model using commands that are similar to the commands you would give to Excel itself. The PHPExcel Developer Documentation has details.

    The getExcel() Member Function

    The member function getExcel()uses PHPExcel to build each of the worksheets from the SQL statements you defined in Step 3. When the worksheets have been built, it returns the PHPExcel object to the caller. There are four major sections of the getExcel member function described below.

    A. Iterate Through the Pages

    The main loop of this member function iterates through the pages previously added with add_page. In each iteration, it creates the corresponding page in the phpExcel object and then adds the data. The createSheet member function of PHPExcel is used to create a new worksheet for each page previously added.

            public function getExcel()
            {
                $i = 0;
                foreach($this->sql_pages as $wsName=>$page)
                {
                    $start_of_page = true;
                    $sql = $page['Sql'];
                    $start_col = $page['Col'];
                    $start_row = $page['Row'];
                    $this->phpExcel->createSheet();
                    $sheet = $this->phpExcel->setActiveSheetIndex($i);
    
                    if ($sh = $this->pdo->query($sql))
                    {
    

    The illustration below shows how the code corresponds to the spreadsheet. The column_map is discussed in the next section.

    B. “Start of Page” Logic

    Each page has special formatting at the start. The first time a row is retrieved from the database for a particular page, it performs the tasks necessary to perform the start-of-page formating. It invokes the “mapColumns” member function that was discussed in Step 1. PHPExcel, like Excel uses the a LetterNumber pair to identify a particular cell. In MySqlExcelBuilder it’s referred to as a cellKey. A cell key is built by concatenating a column label and a row number.

    	$rowNum = $start_row;
    	while($row = $sh->fetch(PDO::FETCH_ASSOC))
    	{
    		$keys = array_keys($row); // Get the Column Names
    		if ($start_of_page) // Initialize the Page
    		{
    			$this->mapColumns($wsName,$keys,$start_col);
    			foreach($keys as $key)
    			{
    			   $col = $this->column_map[$wsName]['xls'][$key];
    			   $cellKey = $col.$rowNum;
    				$sheet->setCellValue($cellKey,$key);
    				// The next two lines are for formatting your header
    				$style = $sheet->getStyle($cellKey);
    				$style->getFont()->setBold(true);
    				$sheet->getColumnDimension($col)->setAutoSize(true);
    			}
    			$rowNum++; // The next row is for data
    			$start_of_page = false; // Done with Intialization
    		}
    

    Some additional things to note in the above code snippet:
    * setCellValue – Puts the actual value in the field. Note that a cell is a member of a worksheet. The specific cell is identified by the cellKey variable.

    * getStyle – This returns a reference to the style attribute of a particular cell, so it can be manipulated.
    * getColumnDimension is a method of the worksheet object. A column dimension (width) is associated with the col variable.

    C. Fill in the Data

    Thanks to the preparation and column mapping, the process of actually putting each data item in the cell is now relatively trivial. We look up the spreadsheet column for a particular data column, build a cell key and then put the value in a cell.

    foreach($keys as $key) // Put the value of the data into each cell
    {
    	 $col = $this->column_map[$wsName]['xls'][$key]; // Get the appropriate column
    	 $cellKey = $col.$rowNum; // Build the column key
    	 $val = $row[$key]; // Get the data value
    	 $sheet->setCellValue($cellKey,$val); // Put it in the cell.
    }
    $rowNum++;
    
    D. Add in the Formulas

    The last part of getExcel() shows how to add forumulas to a PHPExcel spreadhseet. In this case, it’s a column total. PHPExcel puts formulas into cells exactly as you would with an Excel Spreadsheet. The value of a cell starts with an equal sign ( = ) and contains a forumla. In this case, the SUM of a range of data cells. See below:

    And now the code:

     $col = $this->column_map[$wsName]['xls'][$key];
    	// Add the Total Label
    	$cellLabelKey = $col.$rowNum;
    	$total_label = "Total $key";
    	$sheet->setCellValue($cellLabelKey,$total_label);
    	$style = $sheet->getStyle($cellLabelKey);
    	$style->getFont()->setBold(true);
    
    	// Add the actual totals
    	$total_row = $rowNum+1;
    	$cellKey = $col.$total_row;
    	$startTotal = $col.$start_row;
    	$endTotal = $col.$this->sql_pages[$wsName]['lastDataRow'];
    	$total_forumla = "=SUM($startTotal:$endTotal)";
    	$sheet->setCellValue($cellKey,$total_forumla);
    	$style = $sheet->getStyle($cellKey);
    	$style->getFont()->setBold(true);
    

     

    Step 5: Put on the Finishing Touches

    After you’ve gotten an Excel spreadsheet that’s been filled with data from your MySQL database with getExcel it’s time to put the finishing touches on the spreadsheet. In this example, we add a title to each worksheet.

    // Get the spreadsheet after the SQL statements are built...
    $phpExcel = $mysql_xls->getExcel(); // This needs to come after all the pages have been added.
    
    $phpExcel->setActiveSheetIndex(0); // Set the sheet to the first page.
    // Do some addtional formatting using PHPExcel
    $sheet = $phpExcel->getActiveSheet();
    $date = date('Y-m-d');
    $cellKey = "A1";
    $sheet->setCellValue($cellKey,"Gold Mugs Sold as Of $date");
    $style = $sheet->getStyle($cellKey);
    $style->getFont()->setBold(true);
    
    $phpExcel->setActiveSheetIndex(1); // Set the sheet to the second page.
    $sheet = $phpExcel->getActiveSheet();
    $sheet->setCellValue($cellKey,"Tea Sold as Of $date");
    $style = $sheet->getStyle($cellKey);
    $style->getFont()->setBold(true);
    
    $phpExcel->setActiveSheetIndex(0); // Set the sheet back to the first page, so the first page is what the user sees.
    
    Step 6: Save The File

    PHPExcel uses an object factory to create a writer that will write the spreadsheet you’ve built into the appropriate format. In this case I used "Excel5" because even very old spreadsheet programs can read it, so my report is available to the biggest demographic possible.

    // Write the spreadsheet file...
    $objWriter = PHPExcel_IOFactory::createWriter($phpExcel, 'Excel5'); // 'Excel5' is the oldest format and can be read by old programs.
    $fname = "TestFile.xls";
    $objWriter->save($fname);
    
    // Make it available for download.
    echo "&lt;a href=\"$fname\"&gt;Download $fname&lt;/a&gt;";
    
    Final Product

    The image below shows a partial screen shot of the final product built by the included sample code. It’s a two page spreadsheet, populated from the sample database and formatted with custom titles on each page:

    Conclusion

    Once the data from the database is in the PHPExcel object, you can use the other features of the PHPExcel class to perform addtional formatting, add more formulas, save it to different file formats and anything else that PHPExcel allows you to do.

    The MySqlExcelBuilder class could, for example, be extended to use the features of PHPExcel to populate an existing spreadsheet template with data from your MySQL database. Since PDO is the underlying database interface, the DSN in the constructor of MySqlExcelBuilder can be altered for other databases quite easily.

    If you have any questions or have run into any troubles, please let me know in the comments section below. Thank you so much for reading!


  • Permalink for 'Join the Nettuts+ Community on Google+'

    Join the Nettuts+ Community on Google+

    Posted: November 22nd, 2011, 9:39am MST by David Appleyard

    We’re excited to let you know that now, in addition to Twitter and Facebook, you can get involved with the Nettuts+ community over at Google+! We’ll be using Google+ to let you know about our latest tutorials, competitions, and Tuts+ news. Read on to find out more…

    What to Expect on Google+ Nettuts+ on Google+

    Through Google+, we’ll be publishing links to our new tutorials and articles, industry news, graphics and examples from our community, and lots more! It’s going to be an extension of the Nettuts+ site and community, in the same way we treat Twitter and Facebook.

    Don’t have a Google+ account? You can head over and create one here, or find out a little more about how it works.

    Add Nettuts+ to Your Circles (function() {var po = document.createElement("script"); po.type = "text/javascript"; po.async = true;po.src = "https://apis.google.com/js/plusone.js"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(po, s); })();

    Just use the button above to add Nettuts+ to your circles, so you don’t miss out on any of our new content. We look forward to seeing you on Google+!


  • Permalink for 'How to Inject Custom HTML and CSS into an iframe'

    How to Inject Custom HTML and CSS into an iframe

    Posted: November 21st, 2011, 2:59pm MST by Jeffrey Way

    Ever been to a site like JSBin, where you can write HTML, CSS, and JavaScript, and then see the results in a panel to the right? An iframe is how we can accomplish this task. In today’s quick tip, I’ll show you how to inject HTML and CSS into an iframe.

    Select 720p for optimal viewing.


  • Permalink for 'How to Create a Time Based CSS Style Sheet Switcher'

    How to Create a Time Based CSS Style Sheet Switcher

    Posted: November 21st, 2011, 12:29pm MST by Janet Wagner

    Style switchers have become a popular feature on websites these days. CSS style sheets allow a Web Designer to change the look and feel of a website with little effort. Some sites use “Day” and “Night” type of style switchers that automatically change the site theme based on the time of day.

    This tutorial shows you how to create a time based CSS style sheet switcher using PHP that lets you change multiple style sheets at once at specific times of the day. There’s also a little bit of jQuery UI thrown in just for fun!

    Why PHP instead of JavaScript?

    The one drawback to using PHP for a time based CSS style sheet switcher is that the time is based on either the web hosting server or on a “time zone” set in the script.

    When I was building my personal portfolio site, I created a time based style sheet switcher using JavaScript and jQuery. The time function of the script worked correctly. However, there was always a brief “flash” of the default style sheet when the web pages loaded.

    JavaScript heavy websites can have problems with conflicts between various JavaScript scripts. I decided to use PHP instead for the CSS style sheet switcher. Because PHP is server side, there were no JavaScript conflicts and the script worked as expected.

    The one drawback to using PHP for a time based CSS style sheet switcher is that the time is based on either the web hosting server or on a “time zone” set in the script. With JavaScript you can set time functions to be based on a user’s computer.

    Before We Begin

    If you are new to PHP, you need to set up and configure a server environment on your local computer (PHP files can not be viewed in a web browser). My personal preference is XAMPP. This article includes a few software options and basic instructions on how to set up a local server.

    Although you can use Notepad to create and edit PHP files, a code editor can be very helpful when writing web pages in PHP and other programming languages. Please refer to these articles for additional information on choosing a code editor:

    The code used in the tutorial creates a basic CSS style sheet switcher and you can view the demo here. The source files include two additional demos.

    Now, let’s get started!

    Step 1: Create the 1st CSS Style Sheet (Night)

    Create a CSS style sheet called style-1.cssand include the following code:

    
    /*  Default Styles
    --------------------------------------------------- */
    
    body {
    	margin: 0px;
    	padding: 0px;
    	background: url("../images/bokeh_2.jpg");
    	background-position: top left;
    	background-repeat: no-repeat;
    	background-attachment: fixed;
    	background-color: #666;
    	font-size: 20px;
    	font-family: Arial, Helvetica, sans-serif;
    	color: #fff;
    	text-align: left;
    }
    
    #wrapper	{
    	width: 965px;
    	margin: 0 auto;
    	position: relative;
    }
    
    a:link, a:visited, a:active {
    	color: #99ccff;
    }
    
    a:hover {
    	color: #0073ea;
    }
    
    .content_container_1	{
    	float: left;
    	width: 650px;
    	margin: 0px 0px 60px 0px;
    }
    
    p.main_description	{
    	margin: 5px 0px 50px 0px;
    	text-align: center;
    }
    
    /* Main Image
    --------------------------------------------------- */
    
    .main_image	{
    	background: url("../images/main_image_1.jpg");
    	background-repeat: no-repeat;
    	width: 630px;
    	height: 425px;
    	border: #fff solid 10px;
    	margin: 40px 0px 10px 0px;
    }
    
    /*  Tabs
    --------------------------------------------------- */
    
    #tabs p	{
    	font-family: Arial, Helvetica, sans-serif;
    	font-size: 20px;
    }
    
    a.tabs_link_1:link, a.tabs_link_1:visited, a.tabs_link_1:active {
    	text-decoration: underline;
    	color: #0073ea;
    	font-weight: bold;
    }
    
    a.tabs_link_1:hover {
    	text-decoration: underline;
    	color: #ff0084;
    	font-weight: bold;
    }
    
    #tabs .tabs_img	{
    	float: left;
    	background-color: #ddd;
    	padding: 8px;
    	margin: 0px 12px 0px 0px;
    }
    
    Step 2: Create the 2nd CSS Style Sheet (Morning)

    Open style-1.css and save it as style-2.css. Change the body background image from bokeh_2.jpg to bokeh_4.jpg. Change main_image_1.jpg to main_image_4.jpg.

    Step 3: Create the 3rd CSS Style Sheet (Afternoon)

    Use style-1.css or style-2.css to create a 3rd style sheet style-3.css. Change the body background image to bokeh_3.jpg and the main image to main_image_5.jpg

    Step 4: Create the 4th CSS Style Sheet (Evening)

    Create a 4th style sheet style-4.css. Change the body background image to bokeh_1.jpg and the main image to main_image_8.jpg

    For steps 2 through 4, feel free to change other elements like font colors and image borders. Instead of using the images provided in the source files, you can use your own images to create custom CSS styles.

    Step 5: Download jQuery and jQuery UI

    To show how the PHP script changes multiple style sheets at once, jQuery Themeroller Themes are being used to style the tabbed content area of the web page.

    Go to the jQuery UI Download Page and download the “Flick” and “Start” themes.

    Next, go to the official jQuery website and download jQuery.

    Step 6: The Markup

    Create a PHP file that includes the following code:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    " [www.w3.org] <html xmlns=" [www.w3.org] xml:lang="en" lang="en">
    <head>
    
    <meta [http-equiv="Content-Type"] content="text/html; charset=iso-8859-1" />
    
    <!-- CSS style sheets -->
    <?php include("style sheets.php"); ?>
    
    <!-- jQuery / JavaScript -->
    <script type="text/javascript" src="js/jquery-1.6.3.min.js"></script>
    <script type="text/javascript" src="js/jquery-ui-1.8.16.custom.min.js">></script>
    <script type="text/javascript">
    	$(function() {
    		$( "#tabs" ).tabs();
    	});
    </script>
    
    <meta name="description" content="This demo uses PHP to change multiple CSS style sheets (Main CSS and jQuery UI Theme) at specific times during a 24 hour period. The timezone for this demo is set to Australia/Melbourne." />
    <meta name="keywords" content="time,based,css,stylesheet,switcher,php" />
    <title>Simple Time Based CSS Style Sheet Switcher</title>
    
    </head>
    <body>
    
    <!-- Begin Wrapper -->
    <div id="wrapper">
    
    <!-- Begin Content Container 1 -->
    <div class="content_container_1">
    
    <!-- Main Image Switches at Set Times -->
    <div class="main_image"></div>
    <p class="main_description">
    Main Image changes at the times set in PHP Script (Australia/Melbourne).
    </p>
    
    <!-- Begin Tabs Area -->
     <div id="tabs">
    	<ul>
    		<li><a href="#tabs-1">About Envato</a></li>
    		<li><a href="#tabs-2">Marketplaces</a></li>
    		<li><a href="#tabs-3">Tuts+ Network</a></li>
    	</ul>
    
    	<div id="tabs-1">
    	<p>
    	<img class="tabs_img" src="images/envato_1.jpg" width="300" height="195" alt="About Envato" />
    	Envato is a startup based out of Australia with people around the world and sites serving pages every second. We started in a living room in 2006 and have been steadily working to build our company into a world-class contender. Our background is creative, we love open source, we believe that work is about way more than just making money, and we're totally committed to making products that are awesome!
    	</p>
    	<p>
    	<a class="tabs_link_1" href=" [envato.com] target="_blank" title="Visit The Envato Website">Visit The Envato Website</a>
    	</p>
    	</div>
    
    	<div id="tabs-2">
    	<p>
    	<img class="tabs_img" src="images/marketplace_1.jpg" width="300" height="195" alt="Marketplaces" />
    	The Envato Marketplaces allow anyone to buy or sell digital goods like WordPress themes, background music, After Effects project files, Flash templates and much more. The marketplaces are home to a thriving community of over 500,000 users, authors and buyers and every day hundreds of new files are added.
    	</p>
    	<p>
    	<a class="tabs_link_1" href=" [themeforest.net] target="_blank" title="Visit the Theme Marketplace">Visit the Theme Marketplace</a>
    	</p>
    	</div>
    
    	<div id="tabs-3">
    	<p>
    	<img class="tabs_img" src="images/psdtuts_1.jpg" width="300" height="195" alt="Tuts+ Network" />
    	At Envato we're very passionate about education, that's why we've created one of the most popular networks of educational blogs around. Tuts+ serves up over 18 million pageviews a month across its many subsites on subjects like graphics, web development, audio production, iPhone development and motion graphics.
    	</p>
    	<p>
    	<a class="tabs_link_1" href=" [tutsplus.com] target="_blank" title="Visit Tuts+ Hub">Visit Tuts+ Hub</a>
    	</p>
    	</div>
    
    </div>
    <!-- End Tabs Area -->
    
    </div>
    <!-- End Content Container 1 -->
    
    </div>
    <!-- End Wrapper -->
    
    </body>
    </html>
    
    Step 7: PHP CSS Stylesheet Switcher Code

    Create a PHP file that includes the following code:

    <?php
    
    date_default_timezone_set("Australia/Melbourne"); // Set default time zone
    
    $time = date("H"); // Set the time in 24 hour format
    
    if (00 <= $time && $time < 07) // 12:00am to 7:00am   Night
    	{
    	echo
    '<link href="css/style-1.css" rel="stylesheet" type="text/css" media="screen" /><link href="css/flick/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" media="screen" />';
    	}
    
    elseif (07 <= $time && $time < 12) // 7:00am to 12:00pm   Morning
    	{
    	echo
    '<link href="css/style-2.css" rel="stylesheet" type="text/css" media="screen" /><link href="css/start/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" media="screen" />';
    	}
    
    elseif (12 <= $time && $time < 18) // 12:00pm to 6:00pm   Afternoon
    	{
    	echo
    '<link href="css/style-3.css" rel="stylesheet" type="text/css" media="screen" /><link href="css/start/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" media="screen" />';
    	}
    
    else // all other hours   Evening
    	{
    	echo
    '<link href="css/style-4.css" rel="stylesheet" type="text/css" media="screen" /><link href="css/flick/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" media="screen" />';
    	}
    
    ?>
    
    Breakdown of the Markup PHP Include for rel="stylesheet" Links

    The script for the CSS Style sheet Switcher is going to be contained in a PHP include file called stylesheets.php.

    A PHP include() statement includes and evaluates a specified file. The stylesheets.php include file is referenced by this code:

    <!-- CSS style sheets -->
    <?php include("style sheets.php"); ?>
    

    Because we are using a PHP script to change CSS style sheets at set times, the rel=”stylesheet” links will be generated by the PHP script.

    Reference jQuery and jQuery UI Libraries

    We need to make sure that the web page references the jQuery and jQuery UI libraries.

    Between the head tags of the web page the following code has been added:

    <!-- jQuery / JavaScript -->
    <script type="text/javascript" src="js/jquery-1.6.3.min.js"></script>
    <script type="text/javascript" src="js/jquery-ui-1.8.16.custom.min.js"></script>
    
    Initialize jQuery UI Tabs

    This tutorial includes jQuery UI Tabs using the default functionality. The following code initializes the tabs:

    <script type="text/javascript">
    	$(function() {
    		$( "#tabs" ).tabs();
    	});
    </script>
    
    Container Div for jQuery UI Tabs
    <!-- Begin Wrapper -->
    <div id="wrapper">
    
    <!-- Begin Content Container 1 -->
    <div class="content_container_1">
    

    (Ending </div> tags for Wrapper and Content Container 1 are shown in the Code block for the Markup of the jQuery UI Tabs)

    Most of the jQuery UI Widgets are programmed to expand to 100% width of the content area where they are placed.

    The container div content_container_1 has been set to a fixed width of 650px in the CSS so that the tabbed content area does not expand the entire width of the screen.

    Main Image Markup

    In order for the main image to also be changed at set times using the PHP script, it needed to be included on the web page as a CSS background image.

    So instead of adding the image to the web page using markup like this:

    <img src="main_image_1.jpg" width="630" height="425" alt="Image" />
    

    It was added to the web page as a CSS background image of a <div> with the class “main_image”, like this:

    <!-- Main Image Switches at Set Times -->
    <div class="main_image"></div>
    <p class="main_description">
    Main Image changes at the times indicated.
    </p>
    
    Markup for the jQuery UI Tabs

    The below markup adds the tabbed content area that is powered by jQuery UI and has been styled using jQuery Themeroller Themes.

    <!-- Begin Tabs Area -->
     <div id="tabs">
    	<ul>
    		<li><a href="#tabs-1">About Envato</a></li>
    		<li><a href="#tabs-2">Marketplaces</a></li>
    		<li><a href="#tabs-3">Tuts+ Network</a></li>
    	</ul>
    
    	<div id="tabs-1">
    	<p>
    	<img class="tabs_img" src="images/envato_1.jpg" width="300" height="195" alt="About Envato" />
    	Envato is a startup based out of Australia with people around the world and sites serving pages every second. We started in a living room in 2006 and have been steadily working to build our company into a world-class contender. Our background is creative, we love open source, we believe that work is about way more than just making money, and we're totally committed to making products that are awesome!
    	</p>
    	<p>
    	<a class="tabs_link_1" href=" [envato.com] target="_blank" title="Visit The Envato Website">Visit The Envato Website</a>
    	</p>
    	</div>
    
    	<div id="tabs-2">
    	<p>
    	<img class="tabs_img" src="images/marketplace_1.jpg" width="300" height="195" alt="Marketplaces" />
    	The Envato Marketplaces allow anyone to buy or sell digital goods like WordPress themes, background music, After Effects project files, Flash templates and much more. The marketplaces are home to a thriving community of over 500,000 users, authors and buyers and every day hundreds of new files are added.
    	</p>
    	<p>
    	<a class="tabs_link_1" href=" [themeforest.net] target="_blank" title="Visit the Theme Marketplace">Visit the Theme Marketplace</a>
    	</p>
    	</div>
    
    	<div id="tabs-3">
    	<p>
    	<img class="tabs_img" src="images/psdtuts_1.jpg" width="300" height="195" alt="Tuts+ Network" />
    	At Envato we're very passionate about education, that's why we've created one of the most popular networks of educational blogs around. Tuts+ serves up over 18 million pageviews a month across its many subsites on subjects like graphics, web development, audio production, iPhone development and motion graphics.
    	</p>
    	<p>
    	<a class="tabs_link_1" href=" [tutsplus.com] target="_blank" title="Visit Tuts+ Hub">Visit Tuts+ Hub</a>
    	</p>
    	</div>
    
    </div>
    <!-- End Tabs Area -->
    
    </div>
    <!-- End Content Container 1 -->
    
    </div>
    <!-- End Wrapper -->
    

    The Menu “Tabs” are generated by an unordered list. The content sections are generated by <div> tags that have unique IDs that correspond to anchor links in the <li></li> tags.

    For example: <div id=”tabs-1″> corresponds with <a href=”#tabs-1″>

    Breakdown of PHP Stylesheet Switcher Code Set the Default Time Zone:
    date_default_timezone_set("Australia/Melbourne"); // Set default time zone
    

    The code date_default_timezone_set sets the default timezone used by all date/time functions in a script.

    If the script does not include date_default_timezone_set, then the web hosting server time will be used for all date/time functions in the script.

    Please refer to the List of Supported Timezones to find the appropriate timezone for your location.

    Newer versions of PHP incorporate “Daylight Savings Times” into the functionality of date_default_timezone_set. Some older versions of PHP do not take “Daylight Savings Times” into account.

    Set the Time in 24 Hour Format:
    $time = date("H"); // Set the hour in 24 hour format
    

    date(“H”) formats the local time/date in a 24-hour format of an hour, with leading zeros. Click Here to view information about the 24-hour clock.

    Breakdown of If, Elseif, Else Statement

    I’ve broken down the rest of the PHP code to show how the PHP script will function line by line. There are several functions being utilized in the code including:

    if
    if (00 <= $time && $time < 07) // 12:00am to 7:00am   Night
    	{
    	echo
    '<link href="css/style-1.css" rel="stylesheet" type="text/css" media="screen" /><link href="css/flick/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" media="screen" />';
    	}
    

    If 00 (midnight) is Less than or equal to current time AND current time is Less than 07 (7:00am) Then the script will apply style-1.css and flick CSS style sheets.

    elseif
    elseif (07 <= $time && $time < 12) // 7:00am to 12:00pm   Morning
    	{
    	echo
    '<link href="css/style-2.css" rel="stylesheet" type="text/css" media="screen" /><link href="css/start/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" media="screen" />';
    	}
    

    If 07 (7:00am) is Less than or equal to current time AND current time is Less than 12 (12:00pm) Then the script will apply style-2.css and start CSS style sheets.

    elseif
    elseif (12 <= $time && $time < 18) // 12:00pm to 6:00pm   Afternoon
    	{
    	echo
    '<link href="css/style-3.css" rel="stylesheet" type="text/css" media="screen" /><link href="css/start/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" media="screen" />';
    	}
    

    If 12 (12:00pm) is Less than or equal to current time AND current time is Less than 18 (6:00pm) Then the script will apply style-3.css and start CSS style sheets.

    else
    else // all other hours   Evening
    	{
    	echo
    '<link href="css/style-4.css" rel="stylesheet" type="text/css" media="screen" /><link href="css/flick/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" media="screen" />';
    	}
    

    If NONE of the conditions are met in the “if…elseif” statements, Then the script will apply style-4.css and flick CSS style sheets.

    Conclusion

    With CSS, you can create many different styles for your web pages. Using PHP, you can apply those styles dynamically to your website. Throw in a little jQuery UI, and your web pages will not only be fun for you to create, but fun for your visitors as well!

    If you have any questions about this tutorial, please ask them below, Thank you so much for reading!


  • Permalink for 'Python from Scratch – Create a Dynamic Website'

    Python from Scratch – Create a Dynamic Website

    Posted: November 19th, 2011, 2:32pm MST by Giles Lavelle

    We’ve covered quite a bit of Python in the previous tutorials in this Session. Today, we’re going to combine everything we’ve learned so far to build a dynamic website with Python.

    Prefer a Video Tutorial?

    Watch more video tutorials on YouTube.

    So, how do you get started creating websites with Python? Well, you could do it all yourself, and write a program that runs on a web server, accepting page requests and serving up responses in the form of HTML and other resources. However, that’s a lot of work, so why go to all the trouble when there are plenty of existing tools out there to do the job for you? These tools are called frameworks, and they’re what we’ll use today to create our website.

    Python Frameworks

    There are quite a few Python web frameworks, but here are some of the best:

    A more comprehensive list can be found on the Python website if you’re in need of additional options. Today we’re going to set Django up for development on a local machine, and then build a simple blog. We’re also going to review the process of installing it on a remote web server.

    Installing Django

    We’ll be performing most of our work today in the Terminal. This should all work on Mac and Linux; however, if you’re running Windows, the process is somewhat different. A familiarity with the command line isn’t necessary if you’re only writing Python, though, if you’re planning on using Django, or running a dynamic website in general, it’s worth learning.

    Terminal Tutorials

    Consider reviewing these tutorials to get yourself up and running with the Terminal.

    Here are the commands you need to install Django. It’s not compatible with Python 3, so you’ll need to install version 2.7 or earlier to get it running.

        wget [www.djangoproject.com]     tar xzvf Django-1.3.1.tar.gz
        cd Django-1.3.1
        python setup.py install
    

    Next, we can optionally remove the install files.

        cd ..
        rm Django-1.3.1.tar.gz
    

    That should do it! Let’s test it out.

        python
        from django import get_version
        get_version()
    

    You should see ’1.3.1′. If you do, everything worked and Django is installed on your system. Congratulations! We’re ready to begin creating our site!

    Building our Blog

    We’re going to build a blog system today, because it’s an excellent way to learn the basics. First, we need to create a Django project.

    cd ~/Documents/Projects
    django-admin.py startproject FirstBlog
    cd FirstBlog
    ls
    

    What do each of these files do?

    Django refers to itself an MTV framework, which stands for Model Template View.

    Apps

    However none of these files on their own make a functional website. For that, we need Apps. Apps are where you write the code that makes your website function, but before we take a look at them, we need to understand a bit about Django’s design principles.

    First, Django is an MVC framework, which stands for Model View Controller. Django refers to itself an MTV framework, which stands for Model Template View. It’s a slightly different approach than MVC, but fundamentally, they’re quite similar. Anyhow, MVC is an architectural pattern that provides a method for structuring your projects. It separates the code that’s used to process data from the code that manages the user interface.

    Django subscribes to the DRY, or “Don’t Repeat Yourself” philosophy.

    Secondly, Django subscribes to the DRY, or Don’t Repeat Yourself philosophy, which means that you should never be writing code that performs a certain task more than once. For example, in our blog, if we wrote a feature that picked a random article from the archive, and implemented this feature on multiple pages, we wouldn’t code it again each time it was needed. We’d code it once and then use it on each page.

    So how does this relate to apps? Well, apps allow you to write your website in a DRY style. Each project, like the one we have here, can contain multiple apps. Conversely, each app can be part of multiple projects. Using the example from earlier, this means that if we made another site in the future that also needed a random page feature, we wouldn’t have to write it all over again. We could simply import the app from this project. Because of this, it’s important that each app serves one distinct purpose. If you write all the functionality of your site within one app, and then need to use part of it again later, you have to import it all. If you were making an eCommerce website, for example, you wouldn’t want to import all the blog features. However, if you make one app for the random feature and one app for the blog publishing system, you could pick and choose the bits that you require.

    This also means that within the site, the code is well organized. If you want to alter a feature, you don’t have to search through one massive file; you can instead browse to the relevant app and change it without worrying about interfering with anything else.

    python mangage.py startapp blog
    cd blog
    ls
    

    Again, we’ve got an __init__.py file to make it a package, and three other files: models, tests and views. We don’t need to worry about tests for now, but the other two are important. Models and Views are the M and V parts of MVC.

    In models, we define our data structures.

    If you’ve ever worked with PHP before, you might have used PhpMyAdmin to create your MySQL tables, and then written out your SQL queries manually in your PHP scripts. In Django, it’s much easier. We define all the data structures we need in this models file, then run a command and all the necessary databases are made for us.

    When you wish to access that data, you go via these models by calling method on them, instead of running raw queries. This is very helpful, because Django can use several database programs. We’re going to use MySQL today, because it’s the most powerful, and is what most hosts provide, but if we needed to switch to a different database in the future, all of the code will still be valid! In other languages, if you wanted to switch to SQLite or something similar, you would need to rewrite the code that accesses your database.

    In the views file, we write the code that actually generates the web pages. This ties all the other parts together. When a user types in a URL, it is sent by the urls script we saw earlier to the views script, which then gets relevant data from the models, processes it and passes it into a template, which finally gets served up as the page the user sees. We’ll take a look at those templates shortly. They’re the easiest part – mostly HTML.

    For a blog, we’ll need a table of posts, with several fields for the title, body text, author, the time it was written, and so on. A real blog would have comments, but that’s beyond the scope of today’s demo.

    from django.db import models
    
    class posts(models.Model):
        author = models.CharField(max_length = 30)
        title = models.CharField(max_length = 100)
        bodytext = models.TextField()
        timestamp = models.DateTimeField()
    
    MySQL

    These models are just a description. We need to make an actual database from them. First, however, we need MySQL running on our system. On an actual web server, this wouldn’t be a problem, because they usually have it preinstalled. Luckily, with a package manager, it’s easy to install. First, you need to install Homebrew and Easy Install

    brew install mysql
    easy_install mysql-python
    
    mysqld_safe --skip-grant-tables #let anyone have full permissions
    mysql -u root
    UPDATE mysql.user SET Password=PASSWORD('nettuts') WHERE User='root'; #give the user 'root' a password
    FLUSH PRIVILEGES;
    
    mysql -u root -p #log in with our password 'nettuts'
    CREATE DATABASE firstblog;
    quit
    
    python2.6 manage.py runserver
    

    When you reboot, MySQL won’t be running, so every time you need to do this in the future, run mysqld to start the server. You can then run python2.6 manange.py runserver in a new tab to start the development server.

    This command won’t run the server yet, it will just return an error. That’s because we need to configure our settings. Let’s take a look at settings.py.

    You need to change the database settings first. These begin on line twelve.

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
            'NAME': 'firstblog',                      # Or path to database file if using sqlite3.
            'USER': 'root',                      # Not used with sqlite3.
            'PASSWORD': 'nettuts',                  # Not used with sqlite3.
            'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
            'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
        }
    }
    

    If you try to run the server again, it should work, provided that you successfully installed MySQL. If you visit 127.0.0.1:8000 in your web browser, you should see the default Django page.

    Now let’s turn our Django site into a blog. First, we need to use our Models to create tables in the database by running the following command:

    python2.6 manage.py syncdb

    Every time you change your models, you should run this command to update the database. Note that this can’t alter existing fields; it may only add new ones. So if you want to remove fields, you’ll have to do that manually with something like PhpMyAdmin. Because this is the first time we’ve run the command, Django will set up all the default built in tables for things like the administration system. Just type ‘yes’ and then fill in your details.

    Now let’s set up the urls.py file. Uncomment the first line in the examples section, and change it to say url(r'^$', 'FirstBlog.blog.views.home', name='home') .

    Now, let’s create the views file to respond to these requests.

    from django.shortcuts import render_to_response
    
    from blog.models import posts
    
    def home(request):
        return render_to_response('index.html')
    
    Templates

    This index.html file doesn’t exist yet, so let’s make it. Create a folder, called templates in the blog app and save a file in it called index.html, which can simply contain “Hello World” for now. Then, we need to edit the settings file so Django knows where this template is located.

    Line 105 is where the section for declaring template folders starts; so adjust it, like so:

    TEMPLATE_DIRS = (
        "blog/templates",
        # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
        # Always use forward slashes, even on Windows.
        # Don't forget to use absolute paths, not relative paths.
    )
    

    If you run the server again and refresh the page in your browser, you should see the “Hello World” message. We can now begin laying out our blog. We’ll add some boilerplate HTML for the home page.

    <!DOCTYPE html>
    
    <html lang="en">
    
    <head>
        <meta charset="utf-8" />
        <link rel="stylesheet" href="css/style.css">
        <link href="images/favicon.ico" rel="shortcut icon">
        <title>First Blog</title>
    </head>
    
    <body>
    
    <div class="container">
        <h1>First Blog</h1>
        <h2>Title</h2>
        <h3>Posted on date by author</h3>
        <p>Body Text</p>
    
    </div>
    
    </body>
    
    </html>
    

    If you save and refresh the page, you should see that the page has been updated with this new content. The next step is to add dynamic content from the database. To accomplish this, Django has a templating language that allows you to embed variables with curly braces. Change the middle section of your page to look like this:

    <div class="container">
        <h1>First Blog</h1>
        <h2>{{ title }}</h2>
        <h3>Posted on {{ date }} by {{ author }}</h3>
        <p>{{ body }}</p>
    
    </div>
    

    We can then pass in values to these variable placeholders from the views.py file by creating a dictionary of values.

    from django.shortcuts import render_to_response
    
    from blog.models import posts
    
    def home(request):
        content = {
            'title' : 'My First Post',
            'author' : 'Giles',
            'date' : '18th September 2011',
            'body' : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam cursus tempus dui, ut vulputate nisl eleifend eget. Aenean justo felis, dapibus quis vulputate at, porta et dolor. Praesent enim libero, malesuada nec vestibulum vitae, fermentum nec ligula. Etiam eget convallis turpis. Donec non sem justo.',
        }
        return render_to_response('index.html', content)
    

    Save and refresh, and you should see that you’re now passing in content to a template from your views file. The final step is to get data from our database and pass that in instead. Luckily, we can do this all without SQL queries, using Django’s models. We need to add our blog app to our FirstBlog project by changing another setting. Go to INSTALLED_APPS on line 112, and add the

    'FirstBlog.blog',

    to the list.

    Then change views.py so it adds data from the database.

    from django.shortcuts import render_to_response
    
    from blog.models import posts
    
    def home(request):
        entries = posts.objects.all()[:10]
        return render_to_response('index.html', {'posts' : entries})
    

    Next, update the template to access this data.

    <div class="container">
        <h1>First Blog</h1>
        <hr />
        {% for post in posts %}
            <div class="post">
            <h2>{{ post.title }}</h2>
            <h3>Posted on {{ post.timestamp }} by {{ post.author }}</h3>
            <p>{{ post.bodytext }}</p>
            </div>
            <hr />
        {% endfor %}
    </div>
    

    Here, we can access all the data in our table in the views.py file, then select only the first ten entries. We pass this data into the template, loop through the entries and display the data with the HTML of our site. This won’t work just yet, because there’s nothing in the database. Stop the server and run:

    python2.6 manage.py syncdb
    

    This will add the new table for our posts to the database. Then, open a new tab and type:

    mysql -u root -p
    

    …type your password, hit enter, and execute:

    INSERT INTO blog_posts (author, title, bodytext) values ('Bob', 'Hello World', 'Lorem Ipsum');
    

    Return to the previous tab and run the server again. Refresh the page and you should see a blog post with the dummy content you just added. If you run the MySQL command a few more times, you should see more posts appear on the page when you refresh.

    Django’s Admin System

    The last thing we need to do today is review Django’s administration system. This is a really powerful feature of Django that lets you manage your site without writing any more code, as you would have to if you were creating a site from scratch. To enable it, we need to change a few settings. First, uncomment lines 4, 5, 13 and 16 within urls.py, so that you can actually access the admin page. Next, go to the INSTALLED_APPS section of settings.py and uncomment 'django.contrib.admin', and 'django.contrib.admindocs',. To let the admin control your posts table, create a new file called admin.py in the blog folder, and add the following lines:

    from django.contrib import admin
    from blog.models import posts
    
    admin.site.register(posts)
    

    Run python2.6 manage.py syncdb again to add the tables for the admin section, and restart the server.

    If you visit 127.0.0.1:8000/admin now in your browser, you should see a login page. Use the details you chose earlier when you first ran the syncdb command to log in. You should see a section, called Blog, with a subtitle for the posts table. You can use this to create, edit and remove blog posts with a simple interface.

    That’s all there is to do. You’ve just created a fully functioning, albeit simple, blog. To finish this lesson, we’re going to look at installing Django on a web server.

    Installing on a Web Server

    There are two types of web hosting, and which one you have will affect whether you can use Django. If you have shared hosting, you’re entirely at the mercy of your host.

    Many cheap web hosts don’t support Python. While PHP is nearly guaranteed, support for other languages often isn’t. You’ll have to check the control panel to determine if Python (and Django) are available. Obviously the process is slightly different with every host. Almost all hosting runs on Apache, and we can use it to host Django, using the mod_wsgi or mod_python Apache modules.

    Most web hosts run scripts in several languages using CGI. Django can run on FastCGI, and also, theoretically, on CGI, but this is not officially supported and would be far too slow for an actual production website. You’ll need to check if these are installed. They’re usually found under a heading, like “CGI and Scripting Language Support”.

    If you have VPS hosting, or are lucky enough to have a dedicated server, your life is much easier. Usually these come with Python preinstalled, and from there, you only need to follow the same steps we went through to get a local copy of Django running. If you don’t have Python, you can install it with a package manager. Your system may even come with Django.

    ssh root@example.com
    
    wget [www.djangoproject.com] tar xzvf Django-1.3.1.tar.gz
    cd Django-1.3.1
    python setup.py install
    

    Once you’ve installed Django on your server, upload the site you just made using any file transfer client. You can put the files anywhere, but keep them out of the public folder, or anyone will be able to see the source code of your site. I use /home for all my projects.

    Next, create a MySQL database, called ‘firstblog’ on your server and run syncdb again. You’ll have to create your account for the admin control panel again, but this is a one-time thing.

    If you try and run this, you might receive an error, and that’s because the settings for the server are different those on your local computer. You may need to change the database password within settings.py, but depending on your server configuration, you may also encounter other issues. Google is your friend in these situations!

    To run the server this time, the command is slightly different. You have to specify an IP address and port so that you can access the site over the internet.

    python manage.py runserver 0.0.0.0:8000

    If you visit your site in a web browser, on port 8000, you should see your site!

    Conclusion

    That’s it for this lesson…and our series. I hope you’ve learned a number of useful skills over these past five lessons, and that you’re ready to go on and learn even more Python in the future. If you like the look of Django, and wish to continue increasing your knowledge of the framework, here’s some additional tutorials on the subject.

    As always, I’m happy to discuss any questions about this tutorial or Python in general within the comments. Thanks for reading.


  • Permalink for 'Quick Tip: The Awesome Details Element'

    Quick Tip: The Awesome Details Element

    Posted: November 17th, 2011, 5:16pm MST by Jeffrey Way

    One of my favorite new HTML5 tags, which has only recently been integrated into Chrome (as of version 12), is the details element. I’ll show you to use it in today’s quick tip.

    What Does the details Tag Do?

    It essentially allows us to show and hide content with the click of a button. You’re surely familiar with this type of effect, but, up until now, it had always been achieved with JavaScript. Imagine a heading with an arrow next to it, and when you click on it, additional information below becomes visible. Clicking the arrow again hides the content. This sort of functionality is very common in FAQ pages.

    Here’s a two minute example of this sort of effect. (Type Control + Enter to process the JavaScript.)

    The details element allows us to omit the JavaScript entirely. Or, better put, it eventually will. Browser support is still a bit sparse.

    image An Example

    So let’s dive in and learn how to use this new tag. We begin by creating a new details element.

    <details>
    
    </details>
    

    Next, we need to give it a title, or summary of the content within.

    <details>
    	<summary> Who Goes to College? </summary>
    </details>
    

    By default, in browsers that understand the details element, everything within it — other than the summary tag — will be hidden. Let’s add a paragraph after the summary.

    <details>
    	<summary> Who Goes to College? </summary>
      <p> Your mom. </p>
    </details>
    
    Default Display

    Go ahead and try the demo out in Chrome 12 or higher (as of November 17th, 2011).

    Okay, let’s do something a bit more practical. I want to display various Nettuts+ articles using the details element. We first create the markup for a single article.

    <details>
       <summary>Dig Into Dojo</summary>
       <img src=" [d2o0t5hpnwv4c1.cloudfront.net] alt="Dojo" />
       <div>
          <h3> Dig into Dojo: DOM Basics </h3>
          <p>Maybe you saw that tweet: “jQuery is a gateway drug. It leads to full-on JavaScript usage.” Part of that addiction, I contend, is learning other JavaScript frameworks. And that’s what this four-part series on the incredible Dojo Toolkit is all about: taking you to the next level of your JavaScript addiction.
         </p>
       </div>
    </details>
    
    image

    Next, we’ll give it just a touch of styling.

    body { font-family: sans-serif; }
    
    details {
      overflow: hidden;
      background: #e3e3e3;
      margin-bottom: 10px;
      display: block;
    }
    
    details summary {
      cursor: pointer;
      padding: 10px;
    }
    
    details div {
      float: left;
      width: 65%;
    }
    
    details div h3 { margin-top: 0; }
    
    details img {
     float: left;
     width: 200px;
      padding: 0 30px 10px 10px;
    }
    
    image

    Please note that I’m showing you the open state for convenience, but, when the page loads, you’ll only see the summary text.

    If you’d prefer to be in this state by default, add the open attribute to the details element: <details open>

    Styling the Arrow

    It’s not quite as straight-forward to style the arrow itself as we might hope. Nonetheless, it is possible; the key is to use the -webkit-details-marker pseudo class.

    details summary::-webkit-details-marker {
      color: green;
      font-size: 20px;
    }
    
    Styling the arrow

    Should you need to use a custom icon, possibly the easiest solution is to hide the arrow (using the pseudo class above), and then either apply a background image to the summary element, or use the :after or :before pseudo elements.

    View the final project.

    Conclusion

    It’s certainly a simple effect, but it sure is nice to have such a common feature built-in. Until we can reliably use the details element across all browsers, you can use this polyfill to provide fallback support. One final note: at the time of this writing, there doesn’t seem to be a way to toggle the contents with a keyboard. This could potentially present some accessibility issues.


  • Permalink for 'Dig into Dojo: DOM Basics'

    Dig into Dojo: DOM Basics

    Posted: November 16th, 2011, 8:08am MST by Andrew Burgess

    Maybe you saw that tweet: “jQuery is a gateway drug. It leads to full-on JavaScript usage.” Part of that addiction, I contend, is learning other JavaScript frameworks. And that’s what this four-part series on the incredible Dojo Toolkit is all about: taking you to the next level of your JavaScript addiction.

    Before We Begin

    I should mention before we begin that the only prerequisite for this series is that you have at least a basic knowledge of JavaScript. If you’ve used another JS library before, you’ll be even better off. But, although I compare Dojo to jQuery a couple of times, you don’t need to know jQuery to be comfy in this class.

    Prefer Visual Training?

    And, one more thing: I’ll be producing a screencast for each one of these tutorials, covering everything in the written tutorials, and maybe a little bit more. The ‘casts are part of the Net Premium Subscription, so if you aren’t a member, sign up to get them and a metric ton of other incredible Premium content.

    Meeting Dojo Dojo Toolkit

    Dojo is officially called the Dojo Toolkit. This is actually very fitting. Most other collections of lines of JavaScript available bill themselves as frameworks or libraries. In my mind, a framework is a more or less end-to-end solution for building good web applications, and a library is a collection of tools that assist you with a few specific (usually related) tasks. Dojo fits into both categories, and then some. It’s got all the DOM manipulation, events and animation helpers, and AJAX functions that you’d get with a library like jQuery. But there’s more, much more.

    On your first few dates with Dojo, you won’t realize just how much there is to it. So, let me introduce you to the three main parts of Dojo:

    Getting Dojo

    We’ll start, of course, by getting Dojo on the page. I want to tell you that Dojo isn’t like jQuery, because there are dozens of files that make up Dojo, Dijit, and Dojox. The reason I’m hesitant to say this is that you’ll say that jQuery isn’t just one file: there are all the plugins and extensions that are made for it. The difference with Dojo is that, all these extra parts are officially part of Dojo, and can be called into your webpage at any time.

    However, right now, we only need the Dojo Base. This is a subset of Dojo Core, available in a single file. So, while you can download all of Dojo (and Digit and Dojox), or create custom builds of it with just the parts of it you want, we’re going to take the easy route and get the Base from the the Google CDN.

    <script src=" [ajax.googleapis.com] 

    So, create an index.html file and start with this little template:

    <html>
    <head>
        <title> Intro to Dojo, part 1 </title>
        <style>
    	    .highlight {
      			background: yellow;
      			font-weight: bold;
      			font-size: 1.5em;
    		}
    	</style>
    </head>
    <body>
        <h1> A Heading </h1>
    
        <ul id="nav">
          <li> <a href="/">Home</a> </li>
          <li class="highlight"> <a href="/portfolio"> Portfolio </a> </li>
          <li> <a href="/about">Abou</a> </li>
          <li> <a href="/contact">Contact</a> </li>
        </ul>
    
        <p> This is a paragraph (albeit a very <em>short</em> paragraph). Also, <a href=" [google.com">here's] a link</a>. </p>
     	<script src=" [ajax.googleapis.com] </body>
    </html>

    I’ve included a bunch of elements in this little demo page. We’ll be using them as we explore Dojo.

    I’ll mention one more thing before we get started: when you’re learning a library like Dojo, you’ll probably find it useful to view our testing page in your browser of choice and pop open the respective JavaScript console. Take any line of code in this tutorial and paste it into the console, and you’ll see what’s happening.

    Finding Elements

    In this tutorial, we’re going to be learning Dojo primarily as a replacement for jQuery, or whatever DOM-focused library you use. Of course, that’s hardly a floorboard in this Titanic, but it’s a good place to start. Once you’re comfortable using it in place of your normal library, we can go on to what makes Dojo unique.

    The usual M.O. with these things is get it, use it; so, let’s start with finding DOM elements.

    Dojo has a couple of methods for hunting through the DOM. The first one we’ll look at is dojo.query, which is very much like the jQuery (or $) method. Just pass it a CSS selector string, and it will find all the elements in your document that match the selector.

    dojo.query("a"); 

    Running that in a console, you’ll get a NodeList with 5 items. It holds the five anchor tags you’ll expect. What do you expect to get when you try dojo.query("p > a")? dojo.query can also take a root, or context element as a second parameter. As you might expect, this limits the scope of the query to elements inside that root element. So:

    dojo.query("a", "nav"); // returns a `NodeList` of 4 <a>s

    The root parameter can be either a DOM element, or a string that’s an ID of an element.

    The returned NodeLists also have a query method, which finds nodes that match the selector that are children of the nodes in the original NodeList. For example:

    dojo.query("a"); // a `NodeList` of 5 <a>s
    
    dojo.query("p").query("a"); // a `NodeList` of 1 <a>

    But wait, there’s more, as they say. There are two other Dojo methods for getting elements. If the element you want has an id attribute, you can use the dojo.byId method.

    dojo.byId("nav");

    If you try that out, you’ll notice that you don’t get a NodeList object back: it’s just a plain old DOM element. This will be important to remember.

    One more, and that’s even more specific: dojo.body(). It returns the element, predictably.

    Now, if there’s one “main thing” that most devs use their JS libraries for, it’s working with DOM elements. Of course, Dojo has all the facilities for this too, so let’s take the tour.

    Creating Elements

    We’ll start by creating elements, with dojo.create. First, you can simply just get a new DOM element like this:

    var h = dojo.create("h2"); // <h2></h2>

    Simple. But, usually, you want to do more. Well, you can pass an attributes object as a second parameter:

    var h = dojo.create("section", { role: "banner", innerHTML: "Learning Dojo"});
    // <section> role=​"banner">​Learning Dojo​</section>​

    The dojo.create method can also add elements directly to the DOM. For that, we can add parameters 3 and 4:

    dojo.create("p", { innerHTML: "Hi there!"}, dojo.body(), "first");
    
    dojo.create("h1", { innerHTML: "Heading"}, dojo.query("h1")[0], "before");

    The third parameter is called the reference node; our new node will be placed in the DOM relative to that element.

    But where, in reference?

    That’s where the fourth parameters, the position, comes in. By default (i.e., if you leave it out), it is “last”, which appends the new element to the reference node (as its last child). Your other options are these:

    Modifying Nodes

    You don’t know it yet, but you’ve pretty much learned the dojo.attr method. Let’s formalize this introduction.

    dojo.attr is used to get and set attributes on DOM nodes. Remember that attributes object that we passed as the second parameter to dojo.create? You can pass that as the second parameter to dojo.attr. The first parameter, of course, is the node that is having its attributes modified (or an id string):

    var navUl = dojo.query("p")[0];
    
    dojo.attr(navUl, {
    	onclick : function () {
    		alert("Learning Dojo!");
    	},
    	role: "banner",
    	style : {
    		backgroundColor: "red",
    		fontSize: "2em"
    	}
    });

    If you just want to set a single attribute, just pass the name as the second parameter and the value as the third:

    dojo.attr("nav", "className", "module"); // first parameter is an id string

    To get an attribute, only two parameters are required:

    dojo.attr(dojo.byId("nav"), "id"); // "nav"

    You can use the NodeList method attr in the same way:

    var items = dojo.query("li");
    
    items.attr("innerHTML"); // [" <a href="/">Home</a>", " <a href="/portfolio">Portfolio</a>", " <a href="/about">About</a>", " <a href="/contact">Contact</a>"]
    
    items.attr({ className: "btn" });

    One more thing: to remove attributes, you can use dojo.removeAttr and the NodeList counterpart to remove attributes from elements completely:

    dojo.removeAttr("nav", "id");
    
    dojo.query("#nav").removeAttr("id");

    There are other ways to modify those nodes, though. How about dojo.addClass, dojo.removeClass, or dojo.toggleClass? You can use these to add, remove, or toggle a class or array of classes on single nodes:

    var nav = dojo.byId("nav");
    
    dojo.addClass(nav, "selected");

    There are also NodeList counterparts for these methods:

    dojo.query("li").removeClass(["selected", "highlighted"]);

    Oh, and don’t forget about dojo.replaceClass and the NodeList version:

    dojo.query("p").replaceClass("newClass", "oldClass");
    Removing Nodes

    Want to get rid of a node? Easy: pass dojo.destroy either a DOM node or an id string:

    var navList = dojo.byId("nav");
    dojo.destroy(navList);
    
    // or, easier:
    
    dojo.destroy("nav");

    I should note that there’s no way to destroy a NodeList; dojo.destroy only accepts single nodes, and doesn’t have a NodeList counterpart method.

    But let’s say you just want to take nodes out of the DOM, but not actually destroy them. After all, you might want to plug them in somewhere else, or when something else happens. This is where the orphan method comes in. This method is only a NodeList method:

    dojo.query("li").orphan();

    On our example page, this removes the four

  • s and returns a NodeList of them. If you’d only like to orphan certain nodes from original NodeList, pass is a filtering selector. Note that this filter only matches against nodes in the original NodeList, and not their children:

    dojo.query("li").orphan("li:first-of-type"); // will only orphan the first &amp;lt;li>

    While it isn’t removing an element, I’ll throw this in here: dojo.empty() will take a single node or id and remove everything inside it. Behind the scenes, Dojo is actually just doing node.innerHTML = "". There’s also a NodeList version of this method that, obviously, requires no parameters.

    Moving / Duplicating Nodes

    There are a couple methods related to moving or duplicating DOM nodes.

    You’ll find you’re already partly familiar with dojo.place, from dojo.create. It takes three parameters: the node, the reference node, and the position. As you might expect, these parameters play the same roles they do in dojo.create:

    var nav = dojo.byId("nav"),
        p = dojo.query("p")[0];
    
    dojo.place(nav, p, "after"); // moves `nav` to right after `p` in the DOM

    Following the trend of so many Dojo DOM method, there’s a NodeList method counterpart:

    dojo.query("p").place(dojo.body(), "first");

    Then there’s dojo.clone. While it will clone more than just DOM node structures, that’s what we’ll use it for right now: if you pass this method a reference to a DOM node, it will clone, or copy, that node and all its children. This’ll duplicate our example navigation ul, and put the copy at the top of the document:

    var u2 = dojo.clone( dojo.byId("nav") );
    
    dojo.attr(u2, "id", "nav2");
    
    dojo.place(u2, dojo.body(), "first");

    You can use dojo.clone to clone other JavaScript objects as well.

    var o1 = { one: "one"},
        o2 = dojo.clone(o1);
    
    o1 === o2; // false

    Then, there’s the NodeList method adopt. I’ll have to admit that, while this is an interesting method, I’m still not exactly sure where I would use it. Here’s what it does: it takes two parameters: a selector string or DOM node(s), and an optional position value, which has the same options as dojo.place (“last” as default, etc. ). Then, the adopt method will take the element(s) you passed in as the first parameter (or the elements in the DOM that match the selector) and position them relative to the first element in the NodeList. Then, it returns the adopted elements as a new NodeList. So, in our example page, this will replace all the children of the first <li> with the paragraph:

    dojo.query("li").adopt("p", "only");

    So, there’s that.

    Iterating over Nodes

    Since NodeLists are similar to arrays, you could use just a regular for loop to iterate over them. However, NodeLists have a forEach method:

    dojo.query("li").forEach(function (element, index, arr) {
    	// do your thing
    });

    As you can see, the callback function takes three parameters, the element, the index, and the array itself. If you want to loop over other arrays, you can use dojo.forEach in the same way, just passing that array as the first parameter:

    dojo.forEach([1,2,3], function (item) {
    	// act here
    });

    forEach returns the NodeList or array that you started with. If you want to return a changed array, you can use the map method. Whatever you return from the callback function will be in the array (or NodeList) returned at the end.

    dojo.map([1,2,3], function (item) {
    	return item * item;
    }); // [1, 4, 9]

    Somewhat related to this is filtering nodes out of a NodeList, with filter.You can just pass this method a CSS selector, and only elements that match it will be kept.

    dojo.query("li").filter(".highlight"); // NodeList with one <li class="selected">	

    However, filter can also take a callback function that receives three parameters: the current item, its index, and the array. If the function returns true, the element is kept; otherwise, it’s left out. A new NodeList of the kept elements is returned.

    dojo.query("li").filter(function (el) {
    	return dojo.query("a", el)[0].innerHTML === "About";
    }); // returns a NodeList that holds only the list item with the text "About"

    Handily, there’s also a dojo.filter version that takes an array as the first parameter and the callback as a second.

    dojo.filter(["Nettuts", "Psdtuts", "Phototuts"],  function (el, idx, arr) {
    	return el.slice(0,1) === "P"
    }); // ["Psdtuts", "Phototuts"]
    Working with Events

    Let’s now talk about events with Dojo. And we will start with DOM events, since that’s usually what you’re using. let’s say we want to do something when our <h1> is clicked. There are several ways to do this, and we’ll discuss them all here.

    First, let’s assume we are handling an event that occurs on an element or elements that we have retrieved with dojo.query. We could use the onclick method that NodeList s have:

    dojo.query("h1").onclick(function () {
    	alert("Learning Dojo");
    });

    However, this is really just a “syntactic sugar” method. Behind the scenes, Dojo is using the connect NodeList method:

    dojo.query("h1").connect("onclick", function (e) {
    	alert("learning Dojo");
    });

    This method actually passes the job on to another method, dojo.connect; you’ll probably use this method directly when you’ve got a single DOM node that you want to handle an event on:

    var h = dojo.query("h1")[0]; // or dojo.byId("some_element"), for example
    
    dojo.connect(h, "onclick", function () {
    	alert("learning Dojo");
    });

    Notice how, each time we “move up a layer”, we add another parameter to the beginning of the method call.

    Let’s talk briefly about disconnecting events. When using the methods provided on a NodeList instance, there’s currently no easy way to disconnect the events. This is because dojo.connect returns a handle that is used in the disconnection of events. To disconnect an event, pass its handle to dojo.disconnect:

    var h = dojo.query("h1")[0],
    
    	handle = dojo.connect(h, "onclick", function () {
    		alert("learning Dojo");
    		dojo.disconnect(handle);
    	});

    If you put that in your console, and then click the <h1>, you’ll get an alert. Then the handler will be disconnected, so subsequent clicks won’t do anything.

    If you want to create your own events (or, using Dojo’s terminology, your own topics), you can use Dojo’s publish and subscribe methods. If you’re familiar with how other pub/sub systems work, you’ll have no trouble with this.

    To subscribe an topic, simply pass the name of the topic and the function that should run when the topic is published:

    dojo.subscribe("myTopic", function (data, moreData) {
    	alert(data);
    	console.log(moreData);
    });

    Then, you can publish the topic almost as easily:

    dojo.publish("myTopic", ["some data", "some more data"]);

    Notice that any data you want to pass to functions that subscribe to your topic gets put in an array and passed as a second parameter.

    Conclusion

    In this tutorial, we’ve covered probably 90% of the DOM functionality built into the Dojo Base file we’re getting from Google’s CDN. However, there’s more functionality to discuss. Before we get there, however, we’re going to have to learn about pulling in Dojo’s extra functionality. We’ll discuss that and much more in the next episode of this series.

    Have any requests for things you’d like to learn to do in Dojo? I always read the comments, so you know what to do!


  • Permalink for 'A Massive Guide to Custom Theming jQuery UI Widgets: Premium Tutorial'

    A Massive Guide to Custom Theming jQuery UI Widgets: Premium Tutorial

    Posted: November 14th, 2011, 1:30pm MST by Janet Wagner

    jQuery UI is an open source library of interface components that features interactions, animation effects and ready-to-use widgets. jQuery UI is based on the jQuery JavaScript library and is themeable, which makes integrating jQuery UI easy for developers of any skill level to integrate into their web pages and applications.

    Become a Premium member to read this tutorial as well as hundreds of other advanced tutorials and screencasts from the Tuts+ network.

    This tutorial covers how to theme jQuery UI widgets and write custom CSS so that you can make your own jQuery UI theme. Having a basic understanding of CSS and JavaScript will help you successfully complete this tutorial.

    About This Tutorial

    For this tutorial, I wanted to show how you can customize and theme jQuery UI widgets to match a specific design style.

    For this tutorial, I wanted to show how you can customize and theme jQuery UI widgets to match a specific design style. The widgets in the source files demos have been themed to match the style of the Nettuts+ Freelance Jobs Board Graphic.

    The tutorial source files zip also includes a few extra demos to show different options and settings for jQuery UI Accordion, Tabs, Datepicker and Slider widgets.

    This tutorial includes a Table of Contents so that you can quickly find the sections you are interested in. The tutorial also features many of the available jQuery UI ready-to-use widgets such as Accordion, Tabs, Buttons, Dialog and Datepicker. Because the tutorial covers multiple jQuery UI widgets, it has been set up so that you can pick and choose which widgets you want to create a custom theme for.

    Become a Premium member to read this tutorial/screencast, as well as hundreds of other advanced tutorials and screencasts from the Tuts+ network.


  • Permalink for 'How to Create a Sublime Text 2 Plugin'

    How to Create a Sublime Text 2 Plugin

    Posted: November 14th, 2011, 9:20am MST by Will Bond

    Sublime Text 2 is a highly customizable text editor that has been increasingly capturing the attention of coders looking for a tool that is powerful, fast and modern. Today, we’re going to recreate my popular Sublime plugin that sends CSS through the Nettuts+ Prefixr API for easy cross-browser CSS.

    When finished, you’ll have a solid understanding of how the Sublime Prefixr plugin is written, and be equipped to start writing your own plugins for the editor!

    Preface: Terminology and Reference Material

    The extension model for Sublime Text 2 is fairly full-featured.

    The extension model for Sublime Text 2 is fairly full-featured. There are ways to change the syntax highlighting, the actual chrome of the editor and all of the menus. Additionally, it is possible to create new build systems, auto-completions, language definitions, snippets, macros, key bindings, mouse bindings and plugins. All of these different types of modifications are implemented via files which are organized into packages.

    A package is a folder that is stored in your Packages directory. You can access your Packages directory by clicking on the Preferences > Browse Packages… menu entry. It is also possible to bundle a package into a single file by creating a zip file and changing the extension to .sublime-package. We’ll discuss packaging a bit more further on in this tutorial.

    Sublime comes bundled with quite a number of different packages. Most of the bundled packages are language specific. These contain language definitions, auto-completions and build systems. In addition to the language packages, there are two other packages: Default and User. The
    Default package contains all of the standard key bindings, menu definitions, file settings and a whole bunch of plugins written in Python. The User package is special in that it is always loaded last. This allows users to override defaults by customizing files in their User package.

    During the process of writing a plugin, the Sublime Text 2 API referencewill be essential.

    During the process of writing a plugin, the Sublime Text 2 API referencewill be essential. In addition, the Default package acts as a good reference for figuring out how to do things and what is possible. Much of the functionality of the editor is exposed via commands. Any operation other than typing characters is accomplished via commands. By viewing the Preferences > Key Bindings – Defaultmenu entry, it is possible to find a treasure trove of built-in functionality.

    Now that the distinction between a plugin and package is clear, let’s begin writing our plugin.

    Step 1 - Starting a Plugin

    Sublime comes with functionality that generates a skeleton of Python code needed to write a simple plugin. Select the Tools > New Plugin…menu entry, and a new buffer will be opened with this boilerplate.

    import sublime, sublime_plugin
    
    class ExampleCommand(sublime_plugin.TextCommand):
        def run(self, edit):
            self.view.insert(edit, 0, "Hello, World!")

    Here you can see the two Sublime Python modules are imported to allow for use of the API and a new command class is created. Before editing this and starting to create our own plugin, let’s save the file and trigger the built in functionality.

    When we save the file we are going to create a new package to store it in. Press ctrl+s (Windows/Linux) or cmd+s (OS X) to save the file. The save dialog will open to the User package. Don’t save the file there, but instead browse up a folder and create a new folder named Prefixr.

    Packages/
    …
    - OCaml/
    - Perl/
    - PHP/
    - Prefixr/
    - Python/
    - R/
    - Rails/
    …

    Now save the file inside of the Prefixr folder as Prefixr.py. It doesn’t actually matter what the filename is, just that it ends in .py. However, by convention we will use the name of the plugin for the filename.

    Now that the plugin is saved, let’s try it out. Open the Sublime console by pressing ctrl+`. This is a Python console that has access to theAPI. Enter the following Python to test out the new plugin:

    view.run_command('example')

    You should see Hello World inserted into the beginning of the plugin file. Be sure to undo this change before we continue.

    Step 2 - Command Types and Naming

    For plugins, Sublime provides three different types of commands.

    Since we will be manipulating the content of a CSS file/buffer with this plugin, we are going to use the sublime_plugin.TextCommand class as the basis of our custom Prefixr command. This brings us to the topic of naming command classes.

    In the plugin skeleton provided by Sublime, you’ll notice the class:

    class ExampleCommand(sublime_plugin.TextCommand):

    When we wanted to run the command, we executed the following code in the console:

    view.run_command('example')

    Sublime will take any class that extends one of the sublime_plugin classes
    (TextCommand, WindowCommand or ApplicationCommand), remove the suffix Command and then convert the CamelCaseinto underscore_notation for the command name.

    Thus, to create a command with the name prefixr, the class needs to be PrefixrCommand.

    class PrefixrCommand(sublime_plugin.TextCommand):
    Step 3 - Selecting Text

    One of the most useful features of Sublime is the ability to have multiple selections.

    Now that we have our plugin named properly, we can begin the process of grabbing CSS from the current buffer and sending it to the Prefixr API. One of the most useful features of Sublime is the ability to have multiple selections. As we are grabbing the selected text, we need to write our plug into handle not just the first selection, but all of them.

    Since we are writing a text command, we have access to the current view via self.view. The sel() method of the View object returns an iterable RegionSet of the current selections. We start by scanning through these for curly braces. If curly braces are not present we can expand the selection to the surrounding braces to ensure the whole block is prefixed. Whether or not our selection included curly braces will also be useful later to know if we can tweak the whitespace and formatting on the result we getback from the Prefixr API.

    braces = False
    sels = self.view.sel()
    for sel in sels:
        if self.view.substr(sel).find('{') != -1:
            braces = True

    This code replaces the content of the skeleton run() method.

    If we did not find any curly braces we loop through each selection and adjust the selections to the closest closing curly brace. Next, we use the built-in command expand_selection with the to arg set to brackets to ensure we have the complete contents of each CSS block selected.

    if not braces:
        new_sels = []
        for sel in sels:
            new_sels.append(self.view.find('\}', sel.end()))
        sels.clear()
        for sel in new_sels:
            sels.add(sel)
        self.view.run_command("expand_selection", {"to": "brackets"})

    If you would like to double check your work so far, please compare the source to the file Prefixr-1.py in the source code zip file.

    Step 4 - Threading

    To prevent a poor connection from interrupting other work, we need to make sure that the Prefixr API calls are happening in the background.

    At this point, the selections have been expanded to grab the full contents of each CSS block. Now, we need to send them to the Prefixr API. This is a simple HTTP request, which we are going to use the urllib and urllib2 modules for. However, before we start firing off web requests, we need to think about how a potentially laggy web request could affect the performance of the editor. If, for some reason, the user is on a high-latency, or slow connection, the requests to the Prefixr API could easily take a couple of seconds or more.

    To prevent a poor connection from interrupting other work, we need to make sure that the Prefixr API calls are happening in the background. If you don’t know anything about threading, a very basic explanation is that threads are a way for a program to schedule multiple sets of code to run seemingly at the same time. It is essential in our case because it lets the code that is sending data to, and waiting for a response from, the Prefixr API from preventing the rest of the Sublime user interface from freezing.

    Step 5 - Creating Threads

    We will be using the Python threading module to create threads. To use the threading module, we create a new class that extends threading.Thread called PrefixrApiCall. Classes that extend threading.Thread include a run() method that contains all code to be executed in the thread.

    class PrefixrApiCall(threading.Thread):
        def __init__(self, sel, string, timeout):
            self.sel = sel
            self.original = string
            self.timeout = timeout
            self.result = None
            threading.Thread.__init__(self)
    
        def run(self):
            try:
                data = urllib.urlencode({'css': self.original})
                request = urllib2.Request('http://prefixr.com/api/index.php', data,
                    headers={"User-Agent": "Sublime Prefixr"})
                [http_file] = urllib2.urlopen(request, timeout=self.timeout)
                self.result = [http_file.read()]             return
    
            except (urllib2 [HTTPError)] as (e):
                err = '%s: HTTP error %s contacting API' % (__name__, str(e.code))
            except (urllib2.URLError) as (e):
                err = '%s: URL error %s contacting API' % (__name__, str(e.reason))
    
            sublime.error_message(err)
            self.result = False

    Here we use the thread __init__() method to set all of the values that will be needed during the web request. The run() method contains the code toset up and execute the HTTP request for the Prefixr API. Since threads operate concurrently with other code, it is not possible to directly return values. Instead we set self.result to the result of the call.

    Since we just started using some more modules in our plugin, we must add them to the import statements at the top of the script.

    import urllib
    import urllib2
    import threading

    Now that we have a threaded class to perform the HTTP calls, we need to create a thread for each selection. To do this we jump back into the run() method of our PrefixrCommand class and use the following loop:

    threads = []
    for sel in sels:
        string = self.view.substr(sel)
        thread = PrefixrApiCall(sel, string, 5)
        threads.append(thread)
        thread.start()

    We keep track of each thread we create and then call the start() method to start each.

    If you would like to double check your work so far, please compare the source to the file Prefixr-2.py in the source code zip file.

    Step 6 - Preparing for Results

    Now that we’ve begun the actual Prefixr API requests we need toset up a few last details before handling the responses.

    First, we clear all of the selections because we modified them earlier. Later we will set them back to a reasonable state.

    self.view.sel().clear()

    In addition we start a new Edit object. This groups operations for undo and redo. We specify that we are creating a group for the prefixr command.

    edit = self.view.begin_edit('prefixr')

    As the final step, we call a method we will write next that will handle the result of the API requests.

    self.handle_threads(edit, threads, braces)
    Step 7 - Handling Threads

    At this point our threads are running, or possibly even completed. Next, we need to implement the handle_threads() method we just referenced. This method is going to loop through the list of threads and look for threads that are no longer running.

    def handle_threads(self, edit, threads, braces, offset=0, i=0, dir=1):
        next_threads = []
        for thread in threads:
            if thread.is_alive():
                next_threads.append(thread)
                continue
            if thread.result == False:
                continue
            offset = self.replace(edit, thread, braces, offset)
        threads = next_threads

    If a thread is still alive, we add it to the list of threads to check again later. If the result was a failure, we ignore it, however for good results we call a new replace() method that we’ll be writing soon.

    If there are any threads that are still alive, we need to check those again shortly. In addition, it is a nice user interface enhancement to provide an activity indicator to show that our plugin is still running.

    if len(threads):
        # This animates a little activity indicator in the status area
        before = i % 8
        after = (7) - before
        if not after:
            dir = -1
        if not before:
            dir = 1
        i += dir
        self.view.set_status('prefixr', 'Prefixr [%s=%s]' % \
            (' ' * before, ' ' * after))
    
        sublime.set_timeout(lambda: self.handle_threads(edit, threads,
            braces, offset, i, dir), 100)
        return

    The first section of code uses a simple integer value stored in the variable i to move an = back and forth between two brackets. The last part is the most important though. This tells Sublime to run the handle_threads()method again, with new values, in another 100 milliseconds. This is just like the setTimeout() function in JavaScript.

    The lambda keyword is a feature of Python that allows us to create a new unnamed, or anonymous, function.

    The sublime.set_timeout() method requires a function or method and the number of milliseconds until it should be executed. Without lambda we could tell it we wanted to run handle_threads(), but we would not be able to specify the parameters.

    If all of the threads have completed, we don’t need to set another timeout, but instead we finish our undo group and update the user interface to let the user know everything is done.

    self.view.end_edit(edit)
    
    self.view.erase_status('prefixr')
    selections = len(self.view.sel())
    sublime.status_message('Prefixr successfully run on %s selection%s' %
        (selections, '' if selections == 1 else 's'))

    If you would like to double check your work so far, please compare the source to the file Prefixr-3.py in the source code zip file.

    Step 8 - Performing Replacements

    With our threads handled, we now just need to write the code that replaces the original CSS with the result from the Prefixr API. As we referenced earlier, we are going to write a method called replace().

    This method accepts a number of parameters, including the Edit object for undo, the thread that grabbed the result from the Prefixr API, if the original selection included braces, and finally the selection offset.

    def replace(self, edit, thread, braces, offset):
        sel = thread.sel
        original = thread.original
        result = thread.result
    
        # Here we adjust each selection for any text we have already inserted
        if offset:
            sel = sublime.Region(sel.begin() + offset,
                sel.end() + offset)

    The offset is necessary when dealing with multiple selections. When we replace a block of CSS with the prefixed CSS, the length of that block will increase. The offset ensures we are replacing the correct content for subsequent selections since the text positions all shift upon each replacement.

    The next step is to prepare the result from the Prefixr API to be dropped in as replacement CSS. This includes converting line endings and indentation to match the current document and original selection.

    result = self.normalize_line_endings(result)
    (prefix, main, suffix) = self.fix_whitespace(original, result, sel,
        braces)
    self.view.replace(edit, sel, prefix + main + suffix)

    As a final step we set the user’s selection to include the end of the last line of the new CSS we inserted, and then return the adjusted offset to use for any further selections.

    end_point = sel.begin() + len(prefix) + len(main)
    self.view.sel().add(sublime.Region(end_point, end_point))
    
    return offset + len(prefix + main + suffix) - len(original)

    If you would like to double check your work so far, please compare the source to the file Prefixr-4.py in the source code zip file.

    Step 9 - Whitespace Manipulation

    We used two custom methods during the replacement process to prepare the new CSS for the document. These methods take the result of Prefixr and modify it to match the current document.

    normalize_line_endings() takes the string and makes sure it matches the line endings of the current file. We use the Settings class from the Sublime API to get the proper line endings.

    def normalize_line_endings(self, string):
        string = string.replace('\r\n', '\n').replace('\r', '\n')
        line_endings = self.view.settings().get('default_line_ending')
        if line_endings == 'windows':
            string = string.replace('\n', '\r\n')
        elif line_endings == 'mac':
            string = string.replace('\n', '\r')
        return string

    The fix_whitespace() method is a little more complicated, but does the same kind of manipulation, just for the indentation and whitespace in the CSS block. This manipulation only really works with a single block of CSS, so we exit if one or more braces was included in the original selection.

    def fix_whitespace(self, original, prefixed, sel, braces):
        # If braces are present we can do all of the whitespace magic
        if braces:
            return ('', prefixed, '')

    Otherwise, we start by determining the indent level of the original CSS. This is done by searching for whitespace at the beginning of the selection.

    (row, col) = self.view.rowcol(sel.begin())
    indent_region = self.view.find('^\s+', self.view.text_point(row, 0))
    if self.view.rowcol(indent_region.begin())[0] == row:
        indent = self.view.substr(indent_region)
    else:
        indent = ''

    Next we trim the whitespace from the prefixed CSS and use the current view settings to indent the trimmed CSS to the original level using either tabs or spaces depending on the current editor settings.

    prefixed = prefixed.strip()
    prefixed = re.sub(re.compile('^\s+', re.M), '', prefixed)
    
    settings = self.view.settings()
    use_spaces = settings.get('translate_tabs_to_spaces')
    tab_size = int(settings.get('tab_size', 8))
    indent_characters = '\t'
    if use_spaces:
        indent_characters = ' ' * tab_size
    prefixed = prefixed.replace('\n', '\n' + indent + indent_characters)

    We finish the method up by using the original beginning and trailing white space to ensure the new prefixed CSS fits exactly in place of the original.

    match = re.search('^(\s*)', original)
    prefix = match.groups()[0]
    match = re.search('(\s*)\Z', original)
    suffix = match.groups()[0]
    
    return (prefix, prefixed, suffix)

    With the fix_whitespace() method we used the Python regular expression (re)module, so we need to add it to the list of imports at the top of the script.

    import re

    And with this, we’ve completed the process of writing the prefixr command.The next step it to make the command easy to run by providing a keyboard shortcut and a menu entry.

    Step 10 - Key Bindings

    Most of the settings and modifications that can be made to Sublime are done via JSON files, and this is true for key bindings. Key bindings are usually OS-specific, which means that three key bindings files will need to be created for your plugin. The files should be named Default (Windows).sublime-keymap, Default (Linux).sublime-keymap and Default (OSX).sublime-keymap.

    Prefixr/
    ...
    - Default (Linux).sublime-keymap
    - Default (OSX).sublime-keymap
    - Default (Windows).sublime-keymap
    - Prefixr.py
    

    The .sublime-keymap files contain a JSON array that contains JSON objects to specify the key bindings. The JSON objects must contain a keys and command key, and may also contain a args key if the command requires arguments. The hardest part about picking a key binding is to ensure the key binding is not already used. This can be done by going to the Preferences > Key Bindings – Default menu entry and searching for the keybinding you wish to use. Once you’ve found a suitably unused binding, add it to your .sublime-keymap files.

    [
    	{
    		"keys": ["ctrl+alt+x"], "command": "prefixr"
    	}
    ]

    Normally the Linux and Windows key bindings are the same. The cmd key on OS Xis specified by the string super in the .sublime-keymap files. When porting a key binding across OSes, it is common for the ctrl key onWindows and Linux to be swapped out for super on OS X. This may not, however, always be the most natural hand movement, so if possible try and test your keybindings out on a real keyboard.

    Step 11 - Menu Entries

    One of the cooler things about extending Sublime is that it is possible to add items to the menu structure by creating .sublime-menu files. Menufiles must be named specific names to indicate what menu they affect:

    There are a whole handful of other menu files that affect various other menus throughout the interface. Browsing through the Default package is the easiest way to learn about all of these.

    For Prefixr we want to add a menu item to the Edit menu and some entries to the Preferences menu for settings. The following example is the JSON structure for the Edit menu entry. I’ve omitted the entries for the Preferences menu since they are fairly verbose being nested a few levels deep.

    [
    {
    	"id": "edit",
    	"children":
    	[
    	    {"id": "wrap"},
    	    { "command": "prefixr" }
    	]
    }
    ]

    The one piece to pay attention to is the id keys. By specifying the idof an existing menu entry, it is possible to append an entry without redefining the existing structure. If you open the Main.sublime-menu file from the Default package and browse around, you can determine what idyou want to add your entry to.

    At this point your Prefixr package should look almost identical to the official version on GitHub.

    Step 12 - Distributing Your Package

    Now that you’ve taken the time to write a useful Sublime plugin, it is time to get into the hand of other users.

    Sublime supports distributing a zip file of a package directory as a simple way to share packages. Simply zip your package folder and change the extension to .sublime-package. Other users may now place this into their Installed Packages directory and restart Sublime to install the package.

    Along with easy availability to lots of users, having your package available via Package Control ensures users get upgraded automatically to your latest updates.

    While this can certainly work, there is also a package manager forSublime called Package Controlthat supports a master list of packages and automatic upgrades. To get your package added to the default channel, simply host it on GitHubor BitBucket and then fork the channel file (on GitHub, or BitBucket), add your repository and send a pull request. Once the pull request is accepted, your package will be available to thousands of users using Sublime. Along with easy availability to lots of users, having your package available via Package Control ensures users get upgraded automatically to your latest updates.

    If you don’t want to host on GitHub or BitBucket, there is a customJSON channel/repository system that can be used to host anywhere, while still providing the package to all users. It also provides advanced functionality like specifying the availability of packages by OS. See the PackageControl page for more details.

    Go Write Some Plugins!

    Now that we’ve covered the steps to write a Sublime plugin, it is time for you to dive in! The Sublime plugin community is creating and publishing new functionality almost every day. With each release, Sublime becomes more and more powerful and versatile. The Sublime Text Forum is a great place to get help and talk with others about what you are building.


  • Permalink for 'A Look at Popcorn'

    A Look at Popcorn

    Posted: November 11th, 2011, 1:19pm MST by Dan Harper

    Today we’re going to take a look at Popcorn.JS, a library from Mozilla which makes it very easy to manipulate a webpage based on the current position of a video. This allows you to create rich “hypermedia” experiences around your video content.

    With Popcorn, you could display information about actors currently on-screen, or show Google Street View maps of locations in the video.

    Take a look at the Demo Page to see what we’ll be achieving – a mix of images, Google Maps, Wikipedia, tagging, RSS feeds, Facebook and web content – all in a 22 second video clip.

    About Popcorn

    Popcorn makes video work like the web. We create tools and programs to help developers and authors create interactive pages that supplement video and audio with rich web content, allowing your creations to live and grow online.

    Popcorn provides a collection of plugins to easily pull in remote data to the screen. For example, to display a snippet from the Wikipedia article about the Queen, you’d use this little snippet:

    popcorn.wikipedia({
        start: 12,
        end: 14,
        target: 'wiki',
        src: 'http://en.wikipedia.org/wiki/Elizabeth_II',
        title: 'The Queen',
        numberofwords: 40
    });
    

    This pulls in the first 40 words from the Queen’s Wikipedia page into the element with an ID of wiki. It will appear on-screen at 12 seconds, and disappear at 14 seconds.

    You can just as easily display a Google Map:

    pop.googlemap({
        start: 10,
        end: 12,
        target: 'map',
        type: 'ROADMAP',
        location: 'England',
        zoom: 6
    });
    

    This displays a Google Map of England in #map at 10 seconds, and disappears at 12. You could set the type setting to HYBRID, ROADMAP, SATELLITE, TERRAIN or STREETVIEW and display more precise maps by setting the lat and lng (and for Street View, the heading and pitch for more accurate images).
    A full list of the options available for the Google Maps plugin can be found on the Popcorn site.

    Getting Started

    Create your file structure like so:

    | index.html
    | css/
    |   - style.css
    | js/
    |   - popcorn.js
    |   - script.js
    | img/
    | vid/
    
    HTML

    Inside index.html, enter the following base template:

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>A Look at Popcorn</title>
        <link rel="stylesheet" href="css/style.css">
    </head>
    <body>
    
        <section id="side">
            <div id="wiki"></div>
        </section>
    
        <section id="main">
            <video id="demo_video" controls autobuffer>
                <source src="vid/demo.webm" type="video/webM">
                <source src="vid/demo.mp4" type="video/mp4">
                <source src="vid/demo.ogv" type="video/ogg">
            </video>
            <section id="tags"></section>
        </section>
    
        <footer>
            <p>Demo created by <a href=" [danharper.me">Dan] Harper</a> for <a href=" [net.tutsplus.com] using <a href=" [mozillapopcorn.org">PopcornJS<]     </footer>
    
        <script src="js/popcorn.js"></script>
        <script src="js/script.js"></script>
    </body>
    </html>
    

    We have a simple HTML5 template, with a section#side which we’ll be using to display most of the content from Popcorn. The div#wiki will be used to display Popcorn data from Wikipedia – the only reason it gets its own element is to aid in styling.

    section#main is where the video sits: we’ve specified 3 video formats:

    Below the video is section#tags where we’ll display “tags” using Popcorn.

    Directly before the closing </body> tag, we include the JavaScript files.

    CSS

    Inside your css/style.css file, add in the following basic styling. It’s pretty basic, and I won’t go over it for this tutorial:

    body {
        font-family: sans-serif;
        color: #444;
    }
    
    a:link, a:visited {
        color: orangeRed;
        text-decoration: none;
    }
    
    a:hover, a:active {
        color: crimson;
        text-decoration: underline;
    }
    
    #main {
        width: 640px;
        float: left;
        margin: 0 0 0 10px;
    }
    
    #tags {
        border: 5px solid #eee;
        border-radius: 5px;
        padding: 5px 10px;
    }
    
    #tags a {
        line-height: 30px;
        vertical-align: top;
    }
    
    #side {
        border: 5px solid #eee;
        border-radius: 5px;
        height: 405px;
        width: 390px;
        float: left;
        overflow: hidden;
        padding: 10px;
        position: relative;
    }
    
    video, iframe {
        border-radius: 5px;
        border: 5px solid #eee;
        -webkit-background-clip: content;
    }
    
    #wiki a {
        color: #444;
        font-size: 20px;
    }
    
    #wiki a + p {
        margin: 5px 0 0;
    }
    
    #webpage {
        width: 100%;
        height: 460px;
    }
    
    #tags img {
        width: 30px;
        height: 30px;
    }
    
    footer {
        clear: both;
        font-size: 12px;
    }
    
    Images

    Save the following files into the img/ directory – we’ll be displaying them on the page with Popcorn:

    danharper.jpg nettuts.jpg queen-large.jpg cup-of-tea.jpg

    (Images of the Queen and the cup of tea are in the public domain. That handsome fellow is me.)

    Videos

    Right-click and save the following three video files to your vid/ directory. They’re all the same video, saved into three different formats:

    vids/demo.webm
    vids/demo.mp4
    vids/demo.ogv

    Popcorn also supports videos from YouTube and Vimeo. Click the links for a demo of the plugins.

    Include Popcorn

    Finally, include Popcorn in your project by saving the following into js/popcorn.js:

    [popcornjs.org]

    In a production environment, it’s not really recommended to include the full Popcorn library with all the plugins, as we are doing here. Instead, use the Popcorn Build Tool to create your own version of the library with only the plugins you need.

    Get Popping!

    Inside js/script.js include the following to get started with Popcorn:

    document.addEventListener("DOMContentLoaded", function() {
    
        var pop = Popcorn('#demo_video', {
            pauseOnLinkClicked: true
        });
    
        pop.play();
    
    });
    

    Here we’re creating a new Popcorn instance on #demo_video (the ID we gave our video element). We’re also passing Popcorn the pauseOnLinkClicked argument so that the video is paused when the user clicks a link.

    We then call the play() method to instruct Popcorn to automatically play the video. Remove this line if you would rather wait for the user to explicitally hit ‘Play’.

    Load up the page in your browser and if the video auto-plays, you’re on the right track!

    Step 1: Tag “Dan Harper”

    If you watch the demo video through again, you’ll notice the first Popcorn event we create is a “tag” at 1s displaying my name, link & image. Let’s create that first, and we’ll add in each event as they occur, in chronological order.

    To create this tag, we’ll use Popcorn’s built-in Tag This Person plugin. If you look on the plugin page, you’ll see the plugin takes an object as an argument with the following properties as options:

    Below pop.play(); add the following:

    pop.tagthisperson({
        start: 1,
        target: 'tags',
        person: 'Dan Harper',
        image: 'img/danharper.jpg',
        href: 'http://danharper.me'
    });
    

    Working with Popcorn is really that easy!

    You’ll notice we don’t explicitly specify an end time. Instead, Popcorn will stop the plugin when the video ends. (Personally I’d like the option to have the content persist after the video has ended, but Popcorn does not seem to offer this functionality yet).

    Take a look at the page in your browser and you should see my tag appear at 1s.

    Step 2: Display the ‘Nettuts+’ logo

    At 2 seconds, the Nettuts+ logo is displayed to the side of the video, and disappears at 10 seconds. This is just as easy as tagging a person. The Image plugin allows you to display an image inside an element.

    Like all Popcorn plugins, image takes an object as an argument. image accepts the following options:

    To use this plugin; add the following below the .tagthisperson(…); event:

    pop.image({
        start: 2,
        end: 10,
        target: 'side',
        href: 'http://net.tutsplus.com',
        src: 'img/nettuts.jpg'
    });
    

    As you can see we’re using all the available options except for text. Refresh your browser and try it out! The logo should display in the sidebar between 2 and 10 seconds.

    Step 3: Display the latest Nettuts+ posts

    Googlefeed is one of the plugins which really demonstrated to me the potential of Popcorn. Give it the URL to an RSS feed, and it will display the posts in a little widget inside the element you specify.

    In the demo video it displays at 4 seconds at lasts until the 10 second mark.

    Googlefeed accepts the following options for customisation:

    With these options in mind, let’s add the plugin to our Popcorn events:

    pop.googlefeed({
        start: 4,
        end: 10,
        target: 'side',
        url: 'http://net.tutsplus.com/feed/'
    });
    

    So easy, right?

    Step 4: Let’s Get Social

    The Facebook plugin makes it very easily to display social elements from Facebook at certain times in your video. For example, in a real-world example, you might invite your viewers to Like you on Facebook, or share their comments about the show – and have the box display on-screen in realtime; as if by magic ;)

    This plugin contains a lot of options, the majority of which aren’t relevant for our needs – displaying a Like box – so for the full list of options, check out the plugin’s page on the Popcorn site.

    The options which do concern us, however, are:

    Display our Like button on the page with the following:

    pop.facebook({
        start: 8,
        end: 10,
        target: 'side',
        href: 'http://net.tutsplus.com'
    });
    

    Refresh the page, and the Facebook Like button should pop into existence at 8 seconds, and disappear with the RSS feed and Nettuts+ image at 10 seconds.

    This is getting so easy, your grandma could do it, right?

    Note: In my testing I found the Facebook button to be quite temperamental and sometimes displays before it is due to appear, or disappears early.

    Step 5: On Location

    At 10 seconds, we want to display a Google Map of England for 2 seconds. As you might have guessed, there’s an app a plugin for that!

    The Google Maps plugin allows you to display any sort of map the API allows (Road, Satellite, Terrain, Hybrid or Street View). The options are as follows:

    * You must provide either a location or a lat and lng

    So let’s include the England map on the page. Add the following to your script:

    pop.googlemap({
        start: 10,
        end: 12,
        target: 'side',
        type: 'ROADMAP',
        location: 'England',
        zoom: 6
    });
    

    Why not try out some different options – like zooming on a specific building in Street View? Here’s one to start with:

    pop.googlemap({
        start: 10,
        end: 12,
        target: 'side',
        type: 'STREETVIEW',
        lat: 50.844537,
        lng: -1.081544,
        zoom: 2,
        heading: 145,
        pitch: 1
    });
    
    Step 6: Meet The Queen

    Next up in the demo, at 12 seconds, we add a new tag for the Queen and in the sidebar display an image of her, and include some content from Wikipedia. The image & Wikipedia content disappear at 14 seconds.

    We’ve already gone over the tagthisperson and image plugins, so implementing those should be easy. Why not try doing those bits yourself? Go ahead, I’ll wait.

    Done it? Struggling? Or just too lazy? Well, here’s the answer anyway:

    pop.tagthisperson({
        start: 12,
        target: 'tags',
        person: 'The Queen',
        image: 'img/queen-large.jpg',
        href: 'http://royal.gov.uk'
    });
    
    pop.image({
        start: 12,
        end: 14,
        target: 'side',
        src: 'img/queen-large.jpg'
    });
    

    Now let’s take a look at Popcorn’s Wikipedia plugin. It takes a few options to specify what content you want, and how much of it:

    With these options in mind, try creating this bit yourself. The plugin name is wikipedia.

    pop.wikipedia({
        start: 12,
        end: 14,
        target: 'wiki',
        src: 'http://en.wikipedia.org/wiki/Elizabeth_II',
        title: 'The Queen',
        numberofwords: 40
    });
    

    I’m setting a custom title for the article as I’d rather display the title ‘The Queen’ instead of ‘Elizabeth II’. Also note that we’ve set the target to #wiki – as I mentioned earlier, this is purely for cosmetic purposes.

    Step 7: Tea?

    One of the final pieces of interactivity in the demo is the appearance of a picture of a cup of tea and the new tag of ‘Tea’ at 14 seconds, and ending at 16 seconds.

    As we’ve used both the tagthisperson and image plugins several times already, I won’t bother explaining this code:

    pop.tagthisperson({
        start: 14,
        target: 'tags',
        person: 'Tea',
        image: 'img/cup-of-tea.jpg',
        href: 'http://en.wikipedia.org/wiki/Black_tea'
    });
    
    pop.image({
        start: 14,
        end: 16,
        target: 'side',
        href: 'http://en.wikipedia.org/wiki/Black_tea',
        src: 'img/cup-of-tea.jpg'
    });
    

    In fact, why not try using Popcorn’s Flickr plugin to load a picture of a cup of tea, instead of loading a local one with image.

    Step 8: IFrames?

    Finally, at the end of the demo video we load up the official Mozilla Popcorn site in an IFrame in #side. This is, as you might expect, achieved using another one of Popcorn’s plugins – webpage. This plugin takes just a few options:

    So including an iframe on the page is as simple as:

    pop.webpage({
        start: 16,
        target: 'side',
        src: 'http://mozillapopcorn.org/'
    });
    
    The Popcorn’s Ready!

    Load up the page in your browser for the grand finale – why not grab a bag of popcorn to enjoy the show with? (ha, ha).

    I really hope you find Popcorn as interesting as I do. The potential for this is incredible, and it can really push the boundaries for what we consider interactive content.

    Quiz shows could use this to easily allows viewers to play along in their browser, magazine shows can invite you to join them on social media sites like Facebook, Twitter or G+. Documentaries could display additional information about what’s being shown.

    Or a complex detective crime drama could use your browser as the detective’s note pad – adding clues, witnesses, victims and suspects to the screen in real-time.

    There are already a number of projects incorporating Popcorn in an innovative way. I can’t wait to see what the future holds.

    Extra, Extra! Read All About It!

    A number of libraries and sister projects are already cropping up in the Popcorn eco-system. Mozilla have an alpha-stage app for creating Popcorn content without having to write code, called Popcorn Maker which will be great for cutting-edge film makers wanting to venture into this new browser-based land on the web.

    Other projects, as detailed on the official site, include:

    The Plugins

    A full list of Popcorn plugins can be found here, or for the lazy (I’ve marked the ones we’ve tried):

    Please note: if this article is slightly dated when you’re reading this, the plugin list may have grown substantially, so check out the official site for an up-to-date list!


  • Permalink for 'Nettuts+ Quiz #7: Abbreviations – Darth Vader Edition'

    Nettuts+ Quiz #7: Abbreviations – Darth Vader Edition

    Posted: November 10th, 2011, 3:00pm MST by Siddharth

    Abbreviations are an inevitable part of being a web developer. HTML, CSS, [HTTP,] XML… the list goes on and on.

    This Darth Vader edition should be a moderate test of your web development force-fu. Don’t get too cocky though! The upcoming ones will make you cry! Make Yoda proud!



    $(document).ready(function(){ $('#quiz-container').jquizzy({ questions: init.questions, resultComments: init.resultComments, twitterStatus: 'Woo! I scored {score} on the Nettuts Abbreviations quiz. Give it a shot!', twitterImage: 'http://d2o0t5hpnwv4c1.cloudfront.net/jquizzy-1.0/img/share.png', twitterUsername: 'envatowebdev', splashImage: 'http://d2o0t5hpnwv4c1.cloudfront.net/1082_quiz7/nettuts.png', }); });


  • Permalink for 'An Update on Nettuts+ Prefixr'

    An Update on Nettuts+ Prefixr

    Posted: November 9th, 2011, 9:46am MST by Jeffrey Way

    Many of you might be aware that we recently launched a helpful web service, called Nettuts+ Prefixr. Thankfully, the tool has come a long way since the initial launch, as I’ve squashed countless bugs, and added some neat new features. I’d like to give you a quick rundown on the current state of the tool, as well as how to use it.

    Wait – What is Prefixr? Prefixr

    Prefixr takes all of those pesky CSS3 prefixes that we must type over and over, and does away with them! If you create your stylesheets using the official syntax, you may then, at deployment, run your clean stylesheet through Prefixr, and it’ll instantly update your stylesheet to include every required prefix.

    This way, you don’t have to deal with remembering whether or not a particular CSS3 property requires a -ms prefix or not. That knowledge is built into Prefixr.

    Let’s review a quick example. Below, I have some scattered CSS that is badly in need of updating. Notice that, in some places, we’ve only declared a -moz prefix; in other areas, we’ve used the official syntax, etc.

    .box {
       opacity: .5;
    }
    
    .container {
       box-shadow: 20px;
       -moz-transition: box-shadow 2s;
       -webkit-border-radius: 4px;
       animation: slide 1s alternate;
       background: linear-gradient(top, #e3e3e3 10%, white);
    }
    
    @-webkit-keyframes "slide" {
       0% { left: 0; }
       100% { left: 50px; }
    }
    

    Copy the code above, and paste it into Prefixr. In return, you’ll receive:

    .box {
       -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
       filter: alpha(opacity=50);
       opacity: .5;
    }
    
    .container {
       -webkit-box-shadow: 20px;
       -moz-box-shadow: 20px;
       box-shadow: 20px;
    
       -webkit-transition: box-shadow 2s;
       -moz-transition: box-shadow 2s;
       -o-transition: box-shadow 2s;
       -ms-transition: box-shadow 2s;
       transition: box-shadow 2s;
    
       -webkit-border-radius: 4px;
       -moz-border-radius: 4px;
       border-radius: 4px;
    
       -webkit-animation: slide 1s alternate;
       -moz-animation: slide 1s alternate;
       -ms-animation: slide 1s alternate;
       animation: slide 1s alternate;
    
       background-image: -webkit-gradient(linear, left top, left bottom, color-stop(10%, #e3e3e3), to(white));
       background: -webkit-linear-gradient(top, #e3e3e3 10%, white);
       background: -moz-linear-gradient(top, #e3e3e3 10%, white);
       background: -o-linear-gradient(top, #e3e3e3 10%, white);
       background: -ms-linear-gradient(top, #e3e3e3 10%, white);
       background: linear-gradient(top, #e3e3e3 10%, white);
    }
    
    @keyframes "slide" {
     0% {
        left: 0;
     }
     100% {
        left: 50px;
     }
    
    }
    
    @-moz-keyframes "slide" {
     0% {
        left: 0;
     }
     100% {
        left: 50px;
     }
    
    }
    
    @-webkit-keyframes "slide" {
     0% {
        left: 0;
     }
     100% {
        left: 50px;
     }
    
    }
    
    @-ms-keyframes "slide" {
     0% {
        left: 0;
     }
     100% {
        left: 50px;
     }
    
    }
    

    Wow – that’s a lot of duplicate styling. But, unfortunately, it’s necessary at this point in time. If you want your web applications to be as consistent as possible from browser to browser, you need to use these various prefixes. However, as you can imagine, this can quickly bloat your code. That’s why Prefixr is so helpful!

    Create your stylesheets using the official syntax, and then run it through Prefixr when you deploy, or when you need a conversion.

    I Don’t Want to Copy and Paste into Prefixr

    No worries! I don’t either. Visiting Prefixr.com is only one way to update your stylesheets. I much prefer to use it within my favorite code editor. Thanks to various users, there are a handful of plugins and scripts available for the most popular editors. For example, as a Sublime Text user, I personally use Will Bond’s “Sublime Prefixr” plugin, which works wonderfully.

    Now, I never to have to manually visit Prefixr and copy and paste my stylesheet. I simply select the bit of CSS that I wish to optimize, and type ctrl+alt+x on Windows and Linux, or cmd+ctrl+x on OSX.

    Editors List

    Refer below for the current list of supported editors.

    Editors TextMate Commands

    There are countless TextMate users out there; let’s create a command that will run a selection through Prefixr, and place the result in the clipboard. Within TextMate, browse to the Bundle Editor, and create a new command.

    Bundle Editor

    Paste the following into the “Command” textarea. This will take the selected text, run it through Prefixr, and copy the response to your clipboard. Next, assign an activation key, and you’re all set! This is helpful if you’d prefer to store the Prefixed results in a separate stylesheet.

    curl -sSd "css=$TM_SELECTED_TEXT" " [prefixr.com] | pbcopy
    

    Or, if you’d prefer the result to be compressed, modify the command, like so:

    curl -sSd "css=$TM_SELECTED_TEXT&compress_option=true" " [prefixr.com] | pbcopy
    

    Now, if your stylesheet displays:

    .box {
    	border-radius: 5px;
    }
    

    Select the stylesheet, type the activation key that you assigned, and the following should now be stored in your clipboard (assuming you use the compress option).

    .box{-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;}
    
    Can I Use Variables?

    Prefixr isn’t the same type of preprocessor as Less, Stylus, or Sass. I love those – Sass and Stylus particularly. Prefixr is instead for the folks who dislike the idea of using them. That said, variables do come in handy, so if you’d like to use them in Prefixr, it will automatically update your stylesheets. For example:

    @variables {
      site_width: 960px;
    }
    
    .container {
       width: var(site_width);
    }
    

    Run it through Prefixr, and we get:

    .container {
       width: 960px;
    }
    

    It’s important to note that this is entirely an optional feature. If you feel that variables complicate CSS, then don’t use this feature!

    Requests?

    Nettuts+ Prefixr is under active development, so if you notice a bug or would like a new feature to be implemented, either leave a comment below, or click on the “Feedback” button at Prefixr.com.


  • Permalink for '30 Days to Learn HTML and CSS: a Free Tuts+ Premium Course'

    30 Days to Learn HTML and CSS: a Free Tuts+ Premium Course

    Posted: November 8th, 2011, 4:40pm MST by Skellie

    If you’ve ever wanted to learn how to build websites and web apps, HTML and CSS are the first skills you should learn. They are so fundamental that we believe everyone has the right to learn these skills for free.

    We set ourselves the challenge of designing the most effective and enjoyable way to learn HTML and CSS in one month. The result is 30 Days to Learn HTML and CSS, a free Tuts+ Premium course instructed by Nettuts+ editor and web dev veteran Jeffrey Way. We’re really excited to share this with you today! (Plus, get a sneak peek at the new Tuts+ Premium.)

    How it works

    30 Days to Learn HTML and CSS is a thirty-day video course designed to be completed over one month. Jeffrey Way will take you through a new topic each day, giving you the building blocks you need to eventually code an entire website based on a PSD design.

    If you’ve ever wanted to learn HTML and CSS, but either didn’t have the time, didn’t know where to start, or didn’t quite ‘get it’, we’re pretty sure you’re going to love this free course. All you need to give us in return is 10 minutes a day to go through each video and build your knowledge.

    Part of the new Tuts+ Premium

    In the next few weeks we’ll be launching a complete reinvention of Tuts+ Premium, including a massive redesign and UX overhaul, member forums, a library of eBooks and in-depth courses teaching you skills from the inside out.

    We’ve also drastically improved the way you access the content you know and love, with the ability to quickly filter content based on topic, difficulty, format, and estimated completion time.

    30 Days to Learn HTML and CSS is one of the courses that will be available as part of the new Tuts+ Premium. This course is free, but the rest of the courses are available to members. We’ll be covering topics like HTML5, CSS3, WordPress, digital painting, web design and web typography.

    For now, here are a few glimpses at the new Tuts+ Premium!


    Selecting a topic allows you to filter by sub-category, format, difficulty, and estimated completion time.
    Members can view content in their browser, rather than having to download it.
    Full members get access to educational eBooks worth more than $400.
    One of many upcoming courses.
    Juicy tabs! Stay up to date and win a 5-year scholarship

    If you’re a Tuts+ Premium member and want to be notified about the new Tuts+ Premium, or an interested non-member who’d like to learn more, you can sign up to our notification list. Every subscriber will have the opportunity to win one of 10 x Five-year scholarships to the new Tuts+ Premium, including access to 670+ tutorials, top-selling eBooks, 1,201 source files and a library of in-depth courses.

    To get notified and learn more about the competition, join the web design and dev courses mailing list.


  • Permalink for '20 Ways to Save Kittens and Learn PHP'

    20 Ways to Save Kittens and Learn PHP

    Posted: November 8th, 2011, 6:52am MST by Jason Lengstorf

    Twice a month, we revisit some of our readers’ favorite posts from through out the history of Nettuts+. This tutorial was first published in January, 2011.

    There’s an old adage – dating back to the 1700s – which, in English, says: “A kitten dies each time a PHP programmer doesn’t follow best practices.” Okay, not really; but just go with it!

    Getting started in PHP can be a daunting experience. With that in mind, these 20 tips will teach you how to follow best practices, and save lives…kitty lives.

    0. Program as Often as You Possibly Can

    Programming often and with purpose will make the lessons you learn stick.

    Did you study a foreign language in school? Studied all the parts of speech, learned the verbs and how to conjugate them, followed along as your teacher said common phrases?

    How much of that language do you still speak?

    If you’re answer is, “none,” I’m willing to bet it’s due to the fact that you never actually used the language — you only studied it. But if you can still hold up a conversation, it’s likely because you actually spent some time speaking that language outside of the learning environment. Perhaps you spent a year abroad, or worked a job where a second language was necessary?

    Whatever the reason, you retained it because you used it in real-life situations and put it into a personal context that is much easier to recall later.

    PHP is a foreign language, just like Spanish or French. In order to become comfortable with it, you need to use it outside of the classroom setting. Tutorials and sample projects are great for teaching the fundamentals, but unless you’re applying those concepts to your own projects, it will be much more difficult to apply those fundamentals in context and burn them into your memory.

    So, don’t worry that you “don’t know enough” to build a project. When you choose your project, you have a valid reason to research and implement a concept. Programming often and with purpose will make the lessons you learn stick.

    1. Get Familiar with the PHP Manual

    Every list of tips for beginners has this tip, and for good reason.

    Learning to navigate the PHP documentation is the single most useful thing you can do for yourself as a programmer.

    If you look in my browser history at the sites I most often visit, the PHP manual will be right at the top. I don’t suspect that will change for as long as PHP remains my programming language of choice.

    At first, the manual does look rather daunting — it doesn’t seem to be particularly easy to browse, and the navigation can be a bit awkward at times. However, you’ll get the hang of it quickly.

    Perhaps the best thing to know about the PHP manual is that most functions can be looked up using the pattern http://php.net/function-name in your address bar. For example, to look up the strpos() function, use http://php.net/strpos, and for array_key_exists(), use http://php.net/array-key-exists. (NOTE: pay attention to the omission of parentheses and the substitution of hyphens (-) for the underscore (_) in the address.)

    1a. Read the Comments!

    It's easy to overlook the comments, but do yourself a favor and have a look through them. If you're getting an unexpected result from a function, chances are someone has spotted it and explained it in the comments.

    You can also pick up a plethora of great tips and ideas from the developer community by reading through comments.

    2. Take Advantage of the Huge Online PHP Community

    In addition to the PHP manual, there are wonderful developer communities all over the internet. Some of my personal favorites include StackOverflow.com and the W3Schools.com forum.

    Additionally, Twitter is a surprisingly excellent place to post PHP questions. If you tag a tweet with #PHP, it's likely someone in the community will spot it and lend a hand.

    A Note About Twitter: Of course, anything that's useful will inevitably be overrun with spammers and those sorry individuals who deeply misunderstood the purpose of social media. If you're going to use Twitter as a support network, you'll probably want to routinely block or hide the accounts which spew job postings or retweet everything that mentions PHP.

    Just remember: as you get better, please try to pay it forward. The development community needs everyone to pitch in, and it won't be long before you'll have the ability to answer questions for other beginners. Don't turn a deaf ear.

    3. Don't Put Off Best Practices for Later

    As you're learning, you're going to hear a lot about "best practices" in programming; stuff like 4.1/prepared-statements.html">prepared statements and PEAR coding standards.

    Do not put off learning this stuff because it seems hard.

    If something is a best practice, it's not because we (meaning other PHP developers) got together and said, "How can we make life harder for the noobs?"

    Best practices exist to keep your scripts secure, fast, and manageable. Learn them as early as you can. In fact, don't even bother learning the wrong way.

    It takes just about the exact same amount of learning to figure out mysql_query() as it does to learn PDO or MySQLi. So if you start with your choice of the latter two, you're starting with a strong foundation in database interaction and, really, you've put in less overall effort.

    Be sure to browse Nettuts+ for a variety of tutorials on PHP best practices, including prepared statement usage.

    4. Don't Put Off Best Practices for Later!

    I just wanted to make sure you saw this.

    Seriously, folks. Don't take shortcuts. Every time you violate best practices because the right way seems "too hard," BP dips a kitten in crude oil.

    So if you won't do it for yourself, your projects, your peers, or the advancement of the community at large, at least consider the kittens.

    5. Make Code Self-Documenting

    If you need to squeeze characters off your variable names to shave .2ms off your script’s execution time, there’s likely a whole different problem going on.

    It's tempting, early on, to be "clever" with your variable and function names. Maybe you read an article about performance, or saw a code snippet that accomplished a ton of work in two lines of code. Maybe you want to create your own "signature style" of coding. Maybe you just heard that I hate it and you wanted to piss me off.

    Whatever your temptation, resist it at all costs.

    Consider the following snippet of code:

    <?php
    
     $a = b('jason.lengstorf@copterlabs.com');
    
     $c = explode('@', $a);
    
     $d = $c[1];
    
     echo 'The email address ', $a, ' belongs to the domain ', $d, '.';
    
     function b($e) { return htmlentities($e, ENT_QUOTES); }
    
    ?>

    Does that make any sense to you?

    Of course, you can figure out what it does, but why force anyone trying to work in your code to spend the extra 1-5 minutes scratching his head, trying to remember what $c is storing.

    So let's take that code and make it self-documenting:

    <?php
    
     $email = sanitize_string('jason.lengstorf@copterlabs.com');
    
     $email_pieces = explode('@', $email);
    
     $domain = $email_pieces[1];
    
     echo 'The email address ', $email, ' belongs to the domain ', $domain, '.';
    
     function sanitize_string($string) { return htmlentities($string, ENT_QUOTES); }
    
    ?>

    There. Much better. Now, just by glancing at the code, you can get the general idea of what's going on. No head-scratching, no muttered curses, and most importantly, no real difference.

    Sure, you save a few bytes with short variable names. But, honestly, if you need to squeeze characters off your variable names to shave .2ms off your script's execution time, there's likely a whole different problem going on.

    6. Add a Comment to Anything You Had to Think About

    Comments are the sign of a competent programmer.

    Comments are not the sign of a novice. In fact, as I see more and more code that's not mine, I'm starting to think that comments are the sign of a competent programmer, as they seem to be the only ones doing it.

    If your code is self-documenting, you won't require too many comments. However, no matter how clear your variable and function names are, you'll always have spots where the action taken simply isn't that obvious.

    When that happens, slap a comment in there. "Future You" will give "Present You" a high five when the time comes to update the script.

    As a rule of thumb, if you had to stop and think for a few seconds about what needed to happen to make the script work properly, it's probably a good spot for a quick note.

    Consider the following:

    $pieces = explode('.', $image_name);
    $extension = array_pop($pieces);

    What does that do? Did you have to stop and think about it? Do you still not know for sure what's stored in $extension?

    Look at that snippet again, but with one quick comment:

    // Get the extension off the image filename
    $pieces = explode('.', $image_name); $extension = array_pop($pieces);

    Now, even if you don't know how or why that code works, you at least know that $extension refers specifically to an image extension. If that saves "Future You" or another developer five seconds of processing the script's intent, it was well worth your ten seconds of effort to add the comment in the first place.

    As with most things, moderation is key. Too few comments and you risk leaving the next developer (or Future You) puzzled by a code snippet, which can even lead to accidental breaking of code because the solution, without explanation, might look silly or superfluous. Too many and it becomes too difficult to scan through your code, which is equally frustrating.

    Moderation is key.

    7. Learn Docblock and Use It

    If I could be sure every developer in the world would do one thing with absolute consistency, I think it would be the use of the Docblock commenting standard.

    I have a few reasons for my strong support of Docblock:

    1. It requires one to think about the what and why for each file, function, method, and so on.
    2. It gives a clear description of the expected types for parameters and return values in functions/methods
    3. It provides a quick description of what the code does
    4. When coupled with one of the many IDEs that support Docblock, it creates code hinting (which allows you to see a description and expected parameters/return values for the method or function you're using)

    This tip does border on the upper level of beginner, but I group this under "best practices to be learned as quickly as possible." Feel free to skip it, but before you do, think about the kittens.

    Docblock shows its versatility best when used to document a class:

    /**
     * A simple class to get the sum or difference of $_foo and a value
     *
     * @author Jason Lengstorf <jason.lengstorf@copterlabs.com>
     * @copyright 2011 Copter Labs
     * @license [www.opensource.org] */ 
    
    class CopterLabs_Test
    {
    
     /**
      * The value to use in addition and subtraction
      * @var int
     */
     private $_foo = 0;
    
     /**
      * Adds a value to $_foo and returns the sum *
      * @param int $add_me The value to add to $_foo
      * @return int The sum of $_foo and $add_me
    */
    public function add_to_foo( $add_me=0 )
    {
      return $this->_foo += $add_me;
    }
    
     /**
      * Subtracts a value from $_foo and returns the difference
      * @param int $subtract_me The value to subtract from $_foo
      * @return int The difference of $_foo and $subtract_me
    */
    public function subtract_from_foo( $subtract_me=0 )
    {
      return $this->_foo -= $subtract_me;
    }
    
    }
    

    At first it might look overwhelming, but the benefits are very much worth taking the time to familiarize yourself with the syntax.

    The above Docblock, when used in Netbeans, will generate the following code hint:

    Code hinting in Netbeans 8. Don't Be Too Hardcore to Use an IDE

    If you don't already know the type, you will soon: the developers who think real programmers don't use IDEs.

    Now, look: if you want to impress people, learn to juggle. Refusing to use anything but Emacs in the command line to write scripts will not get you chicks or grant you instant hacker status; it will, however, hang a sign on your forehead warning your coworkers that you are, in fact, That Guy.

    Don't be That Guy.

    There is nothing wrong with using software to give you on-the-fly syntax highlighting, error-checking, and code hints.

    How in-depth your IDE goes is entirely up to you. Personally, I really like Netbeans. I've heard tons of praise for Coda for Mac (though it's not really an IDE), and I previously used Eclipse before moving to Netbeans.

    Whatever IDE you choose, you'll see your coding speed increase and your facepalm-worthy bugs decrease. Further, as you expand your code library, you'll have code hinting for all of your custom software. (Because you're using Docblock, right? Right?!)

    Don't think IDEs are uncool -- no matter what "That Guy" tries to tell you.

    9. Group Common Code Into Functions

    If you see an action repeated, it's time to strongly consider moving that code into a function.

    When you first start programming, it's easy to start at the top of the page and work down, adding each piece of code right where it's needed.

    However, when you code this way, you'll begin to notice that certain pieces of code are appearing over and over again. This is a minefield when it comes to maintenance and upgrades, because you have to hunt through each file for every occurrence of that action to change its functionality.

    If you see an action repeated, even if it's only twice, it's time to strongly consider moving that code into a function.

    Consider the following for example:

    $unclean1 = '<a href="javascript:alert(\'Holy Crap!\');">Click Me!</a>';
    
    $detagged1 = strip_tags($unclean1);
    $deslashed1 = stripslashes($detagged1);
    $clean1 = htmlentities($deslashed1, ENT_QUOTES, 'UTF-8');
    
    $unclean2 = "Let's call Björn!";
    
    $detagged2 = strip_tags($unclean2);
    $deslashed2 = stripslashes($detagged2);
    $clean2 = htmlentities($deslashed2, ENT_QUOTES, 'UTF-8');
    
    echo $clean1, "<br />", $clean2;

    As you can see, both of those strings required a few steps before they could be considered safe to use. However, you'll also notice that those same steps could be considered necessary for every bit of information that is passed to the script.

    This is an instance where using a function instead is far more desirable:

    $unclean1 = '<a href="javascript:alert(\'Holy Crap!\');">Click Me!</a>'; $unclean2 = "Let's call Björn!";
    
    $clean1 = sanitize_input($unclean1);
    $clean2 = sanitize_input($unclean2);
    
    echo $clean1, "<br />", $clean2;
    
    function sanitize_input( $input )
    {
      $detagged = strip_tags($input);
      $deslashed = stripslashes($detagged);
      return htmlentities($deslashed, ENT_QUOTES, 'UTF-8');
    }
    

    By wrapping the common code in a function, it's a bit easier to see what's going on, and it's much easier to edit the steps you want to take when sanitizing your input.

    10. Group Related Functions Into Classes

    Getting a handle on OOP is another one of those things that I file under "best practices to learn as quickly as possible."

    If you have a handful of functions that all deal with database actions, you can save yourself a lot of time and effort by grouping them into classes.

    Learning object-oriented programming is definitely outside the scope of this list, but I felt it was definitely worth mentioning in this beginners' list.

    11. Use Constants, Not Globals

    PHP allows you to define your own constants with the function define().

    When I first started programming on larger projects, I found myself using global variables more often than seemed necessary or reasonable. Admitting you have a problem is the first step.

    I was storing things like application-wide data (such as the site's name or the maximum image width) and database credentials in variables, and I found myself required to use the $GLOBALS superglobal to access this information.

    Then I realized PHP allows you to define your own constants with the function define().

    A constant is a great way to store information like the aforementioned app-wide data and database info. An additional bonus is that it can't be modified, so you can't accidentally overwrite your database password somewhere later in the script.

    As a matter of best practices, the use of globals is generally discouraged to begin with, so the use of constants is preferred anyways. Review the following code for an example and see for yourself:

    <?php
    
    define('FOO', 'constant value');
    
    $bar = 'global value';
    
    echo baz();
    
    function baz()
    {
       $constant = ' Constant: ' . FOO;
       $global = 'Global: ' . $GLOBALS['bar'];
    
       return $constant . "<br />\n" . $global;
    }
    
    ?>
    
    12. Don't Be Afraid to Use Includes

    Often, as you're building larger products, it will make a lot of sense to break it apart into smaller chunks, or include files.

    A generally accepted way to look at includes is to put any bit of code that will be used in multiple scripts into an include file (such as your database connection details, the header and footer data that is common across the whole site, utility functions like your input sanitization actions, etc.) so it can be pulled in by the file that needs it, rather than being copy-pasted.

    For example, on a site with multiple pages, a standard template may emerge that looks something like this:

    <?php
    
    // Application-wide data and database connection
    require_once 'constants.inc.php';
    require_once 'database.inc.php';
    
    // Utility functions
    require_once 'utilities.inc.php';
    
    // Header markup
    require_once 'header.inc.php';
    
    /* * Page-specific processing goes here */
    
    // Footer markup
    require_once 'footer.inc.php';
    
    ?>
    13. Don't Obsess Over Performance

    This is a point of near-paralysis for some developers, and it's really too bad; there is a blurry line between writing efficient code and wasting time trying to squeeze an extra 5ms out of a script's execution.

    Definitely read a few performance articles and learn some of the major pitfalls that can drag your scripts to a slow crawl, but don't waste extra time refactoring your code to change double quotes to single quotes because you found out it was a tiny fraction faster.

    Use your head, avoid the big problems, and keep your ears open, in case a tip you've never heard comes along to speed up your code, but don't make it a race.

    No one can tell the difference between a 25ms page load and a 40ms page load. Make sure it's not 700ms and move on to more important things.

    14. Avoid Marrying HTML to Your Scripts

    This can be tricky, but do your best to avoid tangling up your HTML markup in your PHP. It's nearly impossible to get away from it completely, but try to make sure that you don't include any non-essential HTML markup in your code.

    Consider the following:

    echo '<div class="example-div"><p>This is some test content.</p></div>';

    Was it necessary for that code to wrap the paragraph tag in a div? Could it have been modified to only include the paragraph tag that holds the text? Have a look at an alternative solution:

    <div class="example-div">
       <?php echo '<p>This is some test content.</p>'; ?>
    </div>

    Note: This example is grossly oversimplified. Generating HTML with PHP is usually more of an issue when dealing with a complex function or method that organizes a dataset. The point I'm trying to make is that it can sometimes be tempting to include more markup than is necessary in the output.

    In most cases you can keep the HTML outside the PHP, which makes things easier to read and, usually, easier to work with as well.

    15. Try to Use at Least One Unfamiliar Concept in Every Project

    Push yourself outside your comfort zone.

    You're never going to learn if you keep doing the same old thing. Try out a concept that you're not quite comfortable with on every project you possibly can.

    Don't be over-ambitious, but definitely push yourself outside your comfort zone. It gives you a challenge, saves you from getting bored doing the same old thing over and over again, and forces you to progress as a developer.

    Look at the project, find all the bits that you know well (or at least well enough), and then pick an area you'd like to understand. Sign up for it. Then do it.

    16. Don't Be Too Proud to Change

    You will be wrong. Frequently. But that's not a bad thing.

    As you improve, you'll find newer, better solutions to problems that you've faced in the past. Don't feel stupid; you're learning.

    But it's extremely important that you don't become attached to the code you write. Don't think your way is better just because it's your way. If you happen across a great solution that makes yours look like a Band-Aid on a bullet wound, use it! Pay attention to what's different and what you did that could have been better. File that away under, "Things I've Learned."

    Never allow yourself to believe that an inelegant solution is acceptable because it's yours. That's hubris (which, if you're not aware, doesn't generally result in happy fun times).

    17. Validate

    If you're a web programmer, start becoming familiar with input validation as soon as possible.

    Keep in mind: validation is quite different from sanitization.

    Input validation is the practice of making sure data matches the format you've requested, like checking an email field for a valid email address or ensuring that a submitted username is 8-20 alphanumeric characters.

    It can be tedious and a pain in the ass, but making sure that only valid data makes it through your processing scripts will enhance the user experience and avoid a lot of bugs in the scripts that have to use the data later on.

    18. Whitelists Instead of Blacklists

    If you're not on top of your blacklist, vulnerabilities appear.

    In plenty of situations, you'll want to block or get rid of certain tags, words, email addresses, or other various bits of data.

    A common solution is to use a blacklist: a collection of the tags, terms, etc. that aren't allowed.

    This poses a problem, however; you have to be more clever than the person trying to do something naughty. For instance, in the case of disabling JavaScript in posts, you might blacklist the onclick attribute, as well as most of the event attributes, but what if you forget one? What if a new one is added to the spec sometime in the future?

    If you're not on top of your blacklist, vulnerabilities appear.

    However, to save headache later, use a whitelist whenever possible. A whitelist is the opposite of a blacklist: a collection of allowed tags, terms, etc.

    For instance, in the strip_tags() function, you can provide a whitelist to specify which tags are allowed in strings:

    strip_tags($string, '<em><strong><tt>');
    

    Now your problem is most likely going to be that you can actually do less than you wanted, but that's far safer and usually less of an emergency to handle.

    You can't get away with it in every situation, but saying what is allowed vs. what isn't will provide you with more confidence and control over your scripts.

    19. Learn to Count Like a Computer

    Are you looking for tip #20? Remember that in nearly all cases, counts in PHP start at 0, so this is actually the 20th tip. You'll find this to be the case in most languages; don't let this one trip you up!

    Summary

    If you're a beginner, the tips covered above will help you take great strides toward good habits and best practices. Don't get overwhelmed if all of this is news to you; take things one step at a time (see tip #15).

    Want to talk specifics? Discuss this post on the forums.


  • Permalink for 'Take the 2011 Web Design Survey'

    Take the 2011 Web Design Survey

    Posted: November 8th, 2011, 2:58am MST by Amanda Hackwith

    Do you design websites? Got five minutes? We want to hear from you! Take the 2011 Web Design survey hosted by Rockable Press and Webdesigntuts+ and get the chance to win the grand prize: an Apple iPad 2 and the entire library of Rockable Press e-books. What’s more, we’ll give every respondent a 50% off coupon for the up-coming book just for participating! Interested? Take the survey and read on for details.

    Last year, we polled 3,200 FreelanceSwitch readers on the hard truths of freelancing. The data from that survey eventually became the basis of Freelance Confidential, published by Rockable Press, which explored questions every freelancer asks: How much to charge? Where to find work? How are other freelancers working? This time around, we want to explore the state of the web design industry, but we can’t do it without your input. With a brand new survey for those who design websites, it’s your turn to have your say!

    The Details

    We’re working on a brand new book to give the inside scoop on the web design industry–but we need your help! We need the input of everyone who designs websites on common questions: How exactly do you work? Where do you find inspiration? What makes a good web designer?

    To participate, simply take the 2011 survey on web design–open to anyone who creates websites. Whether you’re a full-time web designer working in industry, a freelancing pro, or simply design websites on the side, we want to hear what you think! And make sure you enter your email so you can receive your coupon and be entered in the grand prize drawing.

    The Prizes

    To thank you for participating, every respondent in the survey will receive a 50% coupon for the ebook edition of “Web Design Confidential,” published by Rockable Press. What’s more, you’ll be entered to win the grand prize, which includes the ENTIRE Rockable Press e-book library. That’s a copy of every current title in the Rockable library, 20 books valued at over $500. And you’ll need something to read all those great books on, so you’ll also win a brand new 32GB wifi Apple iPad 2! That’s a grand prize valued over $1100 USD.

    The Fine Print
    • Although it’s optional in the survey, you must provide valid email address to receive your coupon and enter the grand prize drawing. (Email addresses will ONLY be used to deliver coupon and notify winner of grand prize drawing. We respect your privacy!)
    • You only need to complete the survey once. Grand prize drawing only eligible once per participant. Multiple entries will be disqualified from the grand prize drawing.
    • The winner will be randomly selected from survey participants directly following the close of the survey. Winner will be notified via e-mail and given one week to respond.
    • The winner will be announced on Webdesigntuts+ once confirmed.
    • If winner is unable to easily receive a prize shipment in his or her country of residence, Rockable Press reserves the right to award an equal cash value instead.
    • 50% off coupon will be awarded once per participant and is good towards any e-junkie purchase of “Web Design Confidential,” sold by Rockable Press. Coupons will be emailed to participants once the book is available and will be eligible for a limited time after launch.
    • Employees and staff of Envato are not eligible to win.

    So what are you waiting for? Head on over and take the 2011 Web Design survey to let us know what you think!


  • Permalink for 'How to Use Faye as a Real-Time Push Server in Rails'

    How to Use Faye as a Real-Time Push Server in Rails

    Posted: November 4th, 2011, 3:38pm MDT by Ian Murray

    There are multiple ways to add push functionality to an application, including Pushr and Pub-Nub, which are quite elegant and simple solutions. There are also some more advanced options. In this article, I’m going to show you how to use Faye, a messaging system that runs on both Ruby and Node.js.

    Step 1 - Get Everything Ready

    We’re going build a simple chat service. Now, Ryan Bates covered this on Railscast #260, however, we’re going to take a slightly different approach in this tutorial. First, we’ll create a chat service where users enter a public room, and everyone can chat with each other publicly. The second functionality we’ll be adding is private messages. Additionally, we’ll integrate some security to our implementation using Ryan Bate’s private_pub gem.

    Be sure you have a working setup of Ruby, and Ruby on Rails 3.1. Apart from that, you’ll need thin. Thin is a widely used Ruby webserver, and Faye requires it to run (it doesn’t work with WEBrick, Rails’ built-in server). You can install Thin, like so:

    gem install thin
    

    We should be all set, so let’s create the application:

    rails new faye-tutorial
    

    Now, add the faye gem to your Gemfile:

    gem 'faye'
    

    and run bundle install to install it. Faye needs to run on a separate web server from the web application itself; to accomplish this, you need to create a Rackup config file. Add a faye.ru file to the root of the project and make sure it looks like so:

    require 'faye'
    
    bayeux = Faye::RackAdapter.new(:mount => '/faye', :timeout => 25)
    bayeux.listen(9292)
    

    This file simply tells Rackup how to start the Faye server. Try it out to ensure that it’s working correctly. Run this in your Terminal:

    rackup faye.ru -E production -s thin
    

    If you don’t receive any errors, then you’re good to go!

    Step 2 - Some Basic Authentication

    To create a chat application, we need two basic things: users and a chat room. We’re not going to authenticate our users, but we still need to provide them with a way to set their username. Let’s create that. Run the following command to create a sessions controller so we can log them in:

    rails g controller sessions new create
    

    This will create a sessions controller and two methods: new and create. Add these routes to your routes.rb file:

    get  '/login' => 'sessions#new', :as => :login
    post '/login' => 'sessions#create', :as => :login
    

    These two routes should be self-explanatory to you. Go ahead and modify the app/views/sessions/new.html.erb file:

    <%= form_tag login_path do |f| %>
      <%= label_tag :username %>
      <%= text_field_tag :username %>
      <%= submit_tag "Enter" %>
    <% end %>
    

    And have the create method within the sessions controller look like the following:

    def create
      session[:username] = params[:username]
      render :text => "Welcome #{session[:username]}!"
    end
    

    Go ahead an try it out! Run rails server in the Terminal and point your browser to localhost:3000/login and enter a username. You should be greeted by your application after you submit the form.

    If you’re up for a challenge you could use Omniauth to add some Twitter or Facebook integration for this step!

    Step 3 - The Chat Room

    Now that we have some basic authentication, let’s add a chat room. Run the following command to create a chat controller:

    rails generate controller chats room
    

    This will generate our chats controller and one room method. We need to add some routes to make our chat work, so add this line to your routes.rb file:

    get  '/chatroom' => 'chats#room', :as => :chat
    

    This route will direct our user to the chat room, and let them post messages through a simple form. Modify the room method on the chats controller and make it look like so:

    def room
      redirect_to login_path unless session[:username]
    end
    

    This will ensure that users set a username if they want to chat. Now, let’s create the room itself! Add this to the app/views/chats/room.html.erb:

    <div class="chat_container">
      <div id="chat_room">
        <p class="alert"> Welcome to the chat room <%= session[:username] %>! </p>
      </div>
    
      <form id="new_message_form">
        <input type="text" id="message" name="message">
        <input type="submit" value="Send">
      </form>
    </div>
    

    This is some simple structure for the room. The form at the end will be managed by some JavaScript code that will publish the message to the chat room.

    Now, to post messages to the room, we need to add some JavaScript to our view. First, add Faye’s library to app/views/layouts/application.html.erb:

    <%= javascript_include_tag " [localhost:9292] %>
    

    Then, add the following to the beginning of the room.html.erb view:

    <script>
      $(function() {
        // Create a new client to connect to Faye
        var client = new Faye.Client('http://localhost:9292/faye');
    
        // Handle form submissions and post messages to faye
        $('#new_message_form').submit(function(){
          // Publish the message to the public channel
          client.publish('/messages/public', {
            username: '<%= session[:username] %>',
            msg: $('#message').val()
          });
    
          // Clear the message box
          $('#message').val('');
    
          // Don't actually submit the form, otherwise the page will refresh.
          return false;
        });
      });
    </script>
    

    This method takes the message in the form we added previously (when it’s submitted), and sends the author’s username and message to the “/messages/public” channel in a JSON object. Channels are Faye’s way of sending messages. A user subscribes to a channel and receives all messages that are sent to it. In our case, there is only one channel, which is the public one. Let’s dissect the code a bit more:

    1. First we instantiate a new Faye Client, and have it connect to our Faye server.
    2. Next, we handle the form’s submission. When the user hits the enter key or clicks “Send”, we’ll publish the aforementioned JSON object containing the message’s sender and the message itself to the public channel.
    3. Following that, we clear the message box and return false, as to avoid the form from actually being submitted and refreshing the page.

    Now, this will publish messages to the chat room, but our connected users won’t be able to receive them, because their browsers are not subscribed to the channel. This is achieved through a little more JavaScript. Make the JavaScript block on app/views/chats/room.html.erb look like so:

    <script>
      $(function() {
        // Create a new client to connect to Faye
        var client = new Faye.Client('http://localhost:9292/faye');
    
        // Subscribe to the public channel
        var public_subscription = client.subscribe('/messages/public', function(data) {
          $('<p></p>').html(data.username + ": " + data.msg).appendTo('#chat_room');
        });
    
        // Handle form submission to publish messages.
        $('#new_message_form').submit(function(){
          // ...
          // Leave this part as it is
          // ...
        });
      });
    </script>
    

    This simply connects to Faye’s server, and subscribes to the “/messages/public” channel. The callback we provide receives the messages sent. data will be the JSON object we published before, so we simply use that to create a

    tag with the message inside, and append it to the chat room container.

    You should now have a simple chat! Run both Faye and the Rails server, and open two browsers (or an Incognito Window on Chrome for example). You can enter two different usernames and test your chat. Messages should appear almost instantly on the chat room once you send them.

    Step 4 - Adding Private Messages

    Right now, users are able to chat with one another, but all messages are public. Let’s add some simple functionality where people can send someone private messages, by mentioning the recipient’s username – sort of like in Twitter. For this to work, we’re going to subscribe our users to their own channels, so they’re the only ones who are able to receive messages from it. Make your app/views/chats/room.html.erb JavaScript look like this:

    <script>
      $(function() {
        // Subscribe to receive messages!
        var client = new Faye.Client('http://localhost:9292/faye');
    
        // Our public subscription
        var public_subscription = client.subscribe('/messages/public', function(data) {
          $('<p></p>').html(data.username + ": " + data.msg).appendTo('#chat_room');
        });
    
        // Our own private channel
        var private_subscription = client.subscribe('/messages/private/<%= session[:username] %>', function(data) {
          $('<p></p>').addClass('private').html(data.username + ": " + data.msg).appendTo('#chat_room');
        });
    
        // Handle form submission to publish messages.
        $('#new_message_form').submit(function(){
          // Is it a private message?
          if (matches = $('#message').val().match(/@(.+) (.+)/)) {
            client.publish('/messages/private/' + matches[1], {
              username: '<%= session[:username] %>',
              msg: matches[2]
            });
          }
          else {
            // It's a public message
            client.publish('/messages/public', {
              username: '<%= session[:username] %>',
              msg: $('#message').val()
            });
          }
    
          // Clear the message box
          $('#message').val('');
    
          return false;
        });
      });
    </script>
    

    As you can see, we’re subscribing to two Faye channels: one is the public channel, and the second is a channel, called “/messages/private/USERNAME” (notice that we use the username on the Rails session). This way, when someone mentions that user, instead of sending the message through the public channel, we send it through the recipient’s private channel, so only that person can read it. We also add some simple styles to it, so it displays in bold.

    Another thing that’s changed is the code that publishes messages. We first check if the message is a private one, by applying a simple regular expression that looks for a mention. If it is, we publish a message to the recipient’s specific channel. If not, we do exactly as we did before – publish it to the public channel.

    Now try it out! Send messages to other users by mentioning them, you should only see them in the recipient’s chat window.

    Step 5 - Some Caveats

    This implementation has its flaws. First, we’re not checking to see if the username a person chooses is already in use. This would mean that anyone could enter the same username as someone else and send messages pretending to be them, and even receive their private messages! This is easily solved by adding some sort of authentication system or by storing the usernames, that are currently in use, within a database. I’m not going cover this in today’s tutorial, but it should be fairly easy for you to implement. If you need assistance, leave a comment, and we’ll help!

    The second caveat is not as obvious. The problem with our implementation is that anyone could manipulate the JavaScript on the fly (using Firebug for instance) to subscribe themselves to any channel they wish (even private channels), and they could publish messages to them pretending to be someone else. This is not as easily solved as the first flaw I pointed out (if we were to solve this manually), but Ryan Bates created a gem that makes this task a cinch, and our app very secure.

    The gem is called private_pub; it essentially forbids any user from publishing to channels with JavaScript, meaning only the Rails app is able to publish to them. This adds some security since a malicious user would not be able to publish to private channels. Another thing that this gem solves is subscriptions. With private_pub, a user can only receive messages from channels we subscribe them to, so they’re not able to add a subscription manually, solving the entire issue.

    So let’s add it to our Gemfile:

    gem 'private_pub', :git => 'git://github.com/ryanb/private_pub.git'
    

    run bundle install to install the gem and run the generator to create the configuration files:

    rails g private_pub:install
    

    You will receive a conflict warning when running this command (private_pub tries to overwrite the faye.ru file). Just type “Y” and hit enter, as it’s necessary to overwrite that file. You’ll also need to move the public/private_pub.js file to the app/assets/javascripts folder. And the last thing: remove the line that includes faye.js on application.html.erb, since Private Pub includes it automatically. Make sure you restart both servers (rails and faye) at this point.

    Now, we need to make some changes. First, subscribing a user to a channel is done differently with private_pub. Edit app/views/chats/room.html.erb and add the following before the JavaScript block:

    <%= subscribe_to "/messages/public" %>
    <%= subscribe_to "/messages/private/#{session[:username]}" %>
    

    This is private_pub’s way of subscribing to channels. This authorizes the user to receive messages through the channel you specify. Now, we need to change the JavaScript code to the following:

    [/js]
    PrivatePub.subscribe("/messages/public", function(data) {
      $('<p></p>').html(data.username + ": " + data.msg).appendTo('#chat_room');
    });
    
    PrivatePub.subscribe("/messages/private/<%= session[:username] %>", function(data) {
      $('<p></p>').addClass('private').html(data.username + ": " + data.msg).appendTo('#chat_room');
    });
    1

    The only difference here is that we’re using PrivatePub to subscribe to channels instead of the Faye library directly.

    We’re also going to need to change the way we publish messages. With Private Pub, only the Rails application is able to publish messages. The Javascript library can’t publish messages on its own. This is a good thing, since we take full control of who publishes messages and to which channel. In order to do this, we’re going to need to change the form used to send messages to the following:

    <%= form_tag new_message_path, :remote => true do %>
      <%= text_field_tag :message %>
      <%= submit_tag "Send" %>
    <% end %>
    

    This is an AJAX form, so it won’t refresh the page when submitted. It’s also going to be looking for new_message_path, so be sure you add this to routes.rb:

    post '/new_message' => 'chats#new_message', :as => :new_message
    

    You’re also going to need to create a new method on the chats controller:

    def new_message
      # Check if the message is private
      if recipient = params[:message].match(/@(.+) (.+)/)
        # It is private, send it to the recipient's private channel
        @channel = "/messages/private/#{recipient.captures.first}"
        @message = { :username => session[:username], :msg => recipient.captures.second }
      else
        # It's public, so send it to the public channel
        @channel = "/messages/public"
        @message = { :username => session[:username], :msg => params[:message] }
      end
    
      respond_to do |f|
        f.js
      end
    end
    

    This works very much like its JavaScript counterpart. It determines if the message contains a mention, and, if it does, it sends the message to the recipient’s private channel. If not, it sends the message through the public channel. Now, this isn’t actually sending the message, it just creates two variables that we need to use from within the view in order to send a one. Private Pub doesn’t allow you to send messages through the controller (at least not with the version I used for this tutorial), so go ahead and create the file app/views/chats/new_message.js.erb and add the following:

    // Clear message input
    $('#message').val('');
    
    // Send the message
    <% publish_to @channel, @message %>
    

    This will execute the first line of code, clearing the message box, and by calling publish_to, Private Pub will send @message (which will be converted to a JSON object when it arrives) to @channel. Simple, huh?

    Go ahead an try it out. It should work just like before, only with new added security!

    Conclusion

    I hope this article gave you some insight into how to use Faye for your projects. I would advise that you always use Private Pub, since it adds an important level of security, unless you don’t really need it.

    If you have any questions, feel free to ask them in the comments or send me a tweet!


  • Permalink for 'Getting Started with Spine Mobile'

    Getting Started with Spine Mobile

    Posted: November 3rd, 2011, 4:36pm MDT by Alex MacCaw

    With the growing complexity of JavaScript applications, frameworks are an absolute must if you need to meet real world deadlines. In this article, we’re going to take a look at a new framework called Spine Mobile which you can use to create awesome mobile applications in CoffeeScript and HTML, without sacrificing the great user experience of native apps.

    Interested? Let’s get started!

    What Exactly is Spine?

    Spine is a lightweight JavaScript MVC framework that you can use to create awesome client-side web applications. Spine Mobile is an extension to Spine, specifically designed for creating native-feeling mobile web applications.

    Task lists and contact managers are a dime a dozen, so let’s do something different in this tutorial and create a workout recorder. Users are going to be able to record workouts, including their type, time and duration. Then we’re going to have a simple list showing all recorded workouts. There’s also a lot of scope for further development, such as social features and graphs.

    You can checkout a live demo of the finished application here, as well as all the example’s source code on GitHub. I highly recommend you follow along this tutorial using the source code, at least initially, as it’ll help you get started if you’re new to Spine.

    If you ever need more details about Spine Mobile, then hit up the comprehensive docs or the mailing list. For a short introduction to CoffeeScript, take a look at The Little Book on CoffeeScript.

    Step 1: Setup

    First things first, we need to install some npm modules, namely spine.app and hem. The former generates Spine apps, whilst the latter acts as a dependency manager. If you haven’t got them installed already, you’ll need to download Node and npm (both sites have excellent installation guides). Then run:

    npm install -g spine.app hem
    

    Now to actually generate our Spine Mobile application:

    spine mobile spine.workout
    cd spine.workout
    

    Have a browse round the the directory structure and initial files that Spine has created for you.

    $ ls -la
    .gitignore
    Procfile
    app
    css
    package.json
    public
    slug.json
    

    The app directory is where all the application’s logic lives, such as its models and controllers. The public directory is just full of static assets, and is where our application will ultimately be compiled to. It’s the public directory that gets served up as our mobile application.

    Our new application also has some local dependencies (specified in package.json), so let’s go ahead and install those now:

    npm install .
    

    These will download and install the local dependencies in a folder called node_modules (which shouldn’t be in your source control).

    The last thing we need to do, is to run Spine’s development server, Hem.

    hem server
    

    Hem compiles CoffeeScript files, resolves dependencies, wraps source into CommonJS modules and concatenates everything into one JavaScript file, application.js.

    Now that the server is running, we can navigate to our initial application on http://localhost:9294.

    Step 2: Models

    In MVC frameworks, models store your application’s data, and any logic associated with that data. That’s it – models shouldn’t know anything else about the rest of your application; they should be completely de-coupled.

    Our application needs to track workouts, recording the type of workout, how long it took, and when it took place.

    So let’s go ahead and create a new model by running the following:

    spine model workout
    

    That’ll generate a model named: app/models/workout.coffee. Let’s open up that file and implement our Workout model by replacing the contents with this:

    Spine = require('spine')
    
    class Workout extends Spine.Model
      @configure 'Workout', 'type', 'minutes', 'date'
    
      @extend Spine.Model.Local
    
      load: ->
        super
        @date = new Date(Date.parse(@date))
    
      validate: ->
        return 'type required' unless @type
        return 'minutes required' unless @minutes
        return 'date required' unless @date
    
    module.exports = Workout
    

    Ok, so that’s a lot of code without any explanation; let’s drill down into it and look at the details.

    First off, we’re creating a Workout class inheriting from Spine.Model, calling @configure() to set the model’s name and attributes:

    class Workout extends Spine.Model
      @configure 'Workout', 'type', 'minutes', 'date'
    

    So far so good. Now we’re going to extend the model with a module named Spine.Model.Local. This ensures that the model data is persisted between page reloads using HTML5 Local Storage.

    @extend Spine.Model.Local
    

    Now the next function, load(), needs a bit of an explanation. load() gets called multiple times internally in Spine, especially when records are serialized and de-serialized. Our issue is that we’re serializing the records to JSON when persisting them with HTML5 Local Storage. However, JSON doesn’t have a native ‘Date’ type, and just serializes it to a string. This is a problem, as we want to date attribute to always be a JavaScript date. Overriding load(), making sure the date attribute is a JavaScript Date, will solve this problem.

    load: ->
      super
      @date = new Date(Date.parse(@date))
    

    Lastly, we have a fairly straightforward validate() function. In Spine, a model’s validation fails if the validate() function returns anything ‘truthy’ – i.e. a string. Here we’re returning "type required" unless the type attribute exists. In other words, we’re validating the presence of the type, minutes and date attributes.

    validate: ->
      return 'type required' unless @type
      return 'minutes required' unless @minutes
      return 'date required' unless @date
    

    You’ll notice that the final line in the model is a module.exports assignment. This exposes the Workout class, so other files can require it. Spine applications use CommonJS modules, which requires explicit module requiring and property exporting.

    WorkoutType model

    The only other model we’ll need is a WorkoutType model. This is just going to be a basic class, and contains a list of valid workout types. As before, we need to generate the model first:

    spine model workout_type
    

    And then its contents is a simple class, containing an array of valid workout types:

    class WorkoutType
      @types: [
        'running'
        'jogging'
        'walking'
        'swimming'
        'tennis'
        'squash'
        'handstands'
        'skipping'
        'aerobics'
        'biking'
        'weights'
      ]
    
      @all: ->
        @types
    
    module.exports = WorkoutType
    

    For more information about models, please see the Spine models guide.

    Step 3: Main Controllers

    In Spine applications, controllers are the glue between models and views. They add event listeners to the view, pull data out the model and render JavaScript templates.

    The key thing you need to know about Spine’s controllers, is that they’re all scoped by a single element, the el property. Everything a controller does in its lifetime is scoped by that element; whether it’s adding event listeners, responding to event callbacks, updating the element’s HTML, or pulling out form data.

    Spine Mobile applications have one global Stage controller, which encompasses the whole screen. Our generated application already includes a Stage in app/index.coffee, let’s replace it with the following:

    require('lib/setup')
    
    Spine    = require('spine')
    {Stage}  = require('spine.mobile')
    Workouts = require('controllers/workouts')
    
    class App extends Stage.Global
      constructor: ->
        super
    
        # Instantiate our Workouts controller
        new Workouts
    
        # Setup some Route stuff
        Spine.Route.setup(shim: true)
        @navigate '/workouts'
    
    module.exports = App
    

    Our App Stage is going to be the first controller instantiated, and in charge of setting up the rest of the application. You can see, it’s requiring an as-yet undefined controller named Workouts, and instantiating Workouts in the class’ constructor function.

    In other words, when our application first runs, the App stage is going to be instantiated. That will in turn instantiate our Workouts controller, where all the action is going to be. You can ignore all the route stuff for the time being.

    Now let’s setup the aforementioned Workouts controller:

    spine controller workouts
    

    The new Workouts controller is located under app/controllers/workouts.coffee. This controller is going to be where most of our application lives, so let’s start filling it out by replacing its contents with the following:

    Spine   = require('spine')
    {Panel} = require('spine.mobile')
    
    # Require models
    Workout     = require('models/workout')
    WorkoutType = require('models/workout_type')
    
    # To be implemented:
    class WorkoutsList extends Panel
    class WorkoutsCreate extends Panel
    
    class Workouts extends Spine.Controller
      constructor: ->
        super
    
        # Our application's two Panels
        @list   = new WorkoutsList
        @create = new WorkoutsCreate
    
        # Setup some route stuff
        @routes
          '/workouts':        (params) -> @list.active(params)
          '/workouts/create': (params) -> @create.active(params)
    
        # Fetch the initial workouts from local storage
        Workout.fetch()
    
    module.exports = Workouts
    

    Again, let’s drill down into that and explain what’s going on. Firstly, we’re requiring our application’s two models, Workout and WorkoutType:

    # Require models
    Workout     = require('models/workout')
    WorkoutType = require('models/workout_type')
    

    Then Workouts constructor is setting up a few Panels, as yet unimplemented, and then some routes which we can ignore for the time being. Finally, Workout.fetch() is being called, retrieving all the stored data from local storage.

    Step 4: Listing Workouts

    Ok, now we’ve done a fair bit of setting up with our App and Workouts controllers, but now comes the fun part, the panels.

    So our application has two Panel controllers, a list view, and a create view. These two panels belong to the main stage which ensures they transition in and out properly, only showing one panel at any one time.

    So let’s first define our WorkoutsList controller in app/controllers/workouts.coffee, which, you guessed it, will list the workouts. Add the following code after the require statements in workouts.coffee, before the Workouts controller definition:

    class WorkoutsList extends Panel
      title: 'Workouts'
    
      constructor: ->
        super
        # Add a button to the header
        @addButton('Add', @add)
    
        # Bind the model to the view
        Workout.bind('refresh change', @render)
    
      render: =>
        # Fetch all workout records from the model
        workouts = Workout.all()
    
        # Render a template with the workout array
        template = require('views/workouts')(workouts)
    
        # Replace the current element's HTML with the template
        @html(template)
    
      add: ->
        # Navigate to the 'create' controller, with a
        # swipe transition out to the left
        @navigate('/workouts/create', trans: 'right')
    

    The first thing you’ll notice is that WorkoutsList extends Panel, a class defined in the spine.mobile package. This ensures that it inherits Panel‘s properties, so the application’s Stage can work with it.

    The template uses a great library called Eco. Check out the view guide for more information on its syntax. Suffice to say, it’s CoffeeScript syntax, using the notation to render template variables to the page.

    Then we’ve got a property called title. This is an optional setting, and will be the title of our panel.

    In the constructor function, we’re adding a button to the panel header by calling @addButton(title, callback). When tapped, this will invoke the class’ add() function.

    Lastly, we’re adding binding to two events, refresh and change on the Workout model. Whenever the model is changed, these events will be fired, and our callback render() function invoked. render() first pulls out all the Workout records from the database, then renders a template, replacing the panel’s contents with the result.

    So this template merely acts as a function. All we’re doing is executing that function, passing in a template context, the result being the rendered DOM element. For more information on how this works, please see the views guide, otherwise let’s press on and define the template.

    In app/views, create a folder called workouts which will contain all our templates associated with the Workouts controller. Then let’s create a file under app/views/workouts/index.jeco containing:

      <div class="item">
        <span class="type"><%= @type %></span>
        <span class="minutes">for <%= @minutes %> mins</span>
        <span class="date">on <%= @date.toDateString() %></span>
      </div>
    

    The template’s .jeco extension isn’t a typo, it’s a jQuery extension to the Eco templating library provided by Hem. Amongst other things, it allows us to associate elements with the original template data, which will be useful later.

    The end result is a list of workouts looking like this:

    List

    Obviously, if you haven’t created any workouts, then the list will be empty. We can create a workout programmatically, using the command line inside the Web Inspector console:

    var Workout = require('models/workout');
    Workout.create({type: 'handstands', minutes: 5, date: Date.now()});
    
    Step 5: Creating New Workouts

    Now the last panel to define is WorkoutsCreate, which will contain the form for creating new workouts. This is going to be our largest controller, but it should be fairly straightforward now you’re familiar with the API and terminology.

    The only new addition here is the addition of an elements property, which is a convenience helper to match DOM elements to instance variables. In the example below, the elements property is set to {'form': 'form'}, which maps the
    element to the @form variable.

    class WorkoutsCreate extends Panel
      title: 'Add Workout'
    
      elements:
        'form': 'form'
    
      constructor: ->
        super
        @addButton('Back', @back)
        @addButton('Create', @create)
    
        # Render the view whenever this panel is activated,
        # resetting the form
        @bind 'active', @render()
    
      render: ->
        # Fetch all workout types
        types = WorkoutType.all()
    
        # Render the template, replacing the HTML
        @html require('views/workouts/form')(types: types)
    
      create: ->
        # Create new workout from form data
        item = Workout.create(@formData())
    
        # Navigate back to the list, if validation passed
        @back() if item
    
      # Navigate back to the list
      back: ->
        @form.blur()
        @navigate('/workouts', trans: 'left')
    
      # Retrive form data as a object literal
      formData: ->
        type    = @form.find('[name=type]').val()
        minutes = parseInt(@form.find('[name=minutes]').val())
        date    = @form.find('[name=date]')[0].valueAsDate
        {type: type, minutes: minutes, date: date}
    

    So let’s take that apart piece by piece. Firstly, in the WorkoutsCreate constructor, we’re adding two buttons to the panel, ‘Create’ and ‘Back’. You can probably guess what these are going to do.

    Next, we’re binding to the panel’s active event, triggered whenever the panel is shown. When the event is triggered, the render() function is called, replacing the controller element’s HTML with a rendered template. By attaching the render() invocation to the active event, rather than directly in the constructor, we’re making sure that the form is reset whenever the panel is navigated to.

    The last part to the panel is the create() function, where our Workout record is actually going to be created. We are using formData() to retrieve the user’s input, passing it to Workout.create().

    Now onto defining the app/views/workouts/form.eco template used in the render() function:

    <form>
      <label>
        <span>Select type</span>
    
        <select name="type" size="1" required>
          <% for type in @types: %>
            <option value="<%= type %>"><%= type %></option>
          <% end %>
        </select>
      </label>
    
      <label>
        <span>Select minutes</span>
    
        <select name="minutes" size="1" required>
          <option value="5">5 minutes</option>
          <!-- ... -->
        </select>
      </label>
    
      <label>
        <span>Select date</span>
        <input name="date" type="date" required>
      </label>
    </form>
    

    That’s it for our application. Give it a whirl, and create a few workouts.

    Step 6: Build and Deploy

    The last step is to build our application to disk, and deploy it. We can do that using Hem:

    hem build
    

    This will serialize all your JavaScript/CoffeeScript to one file (public/application.js), and all your CSS/Stylus (public/application.css). You’ll need to do this before pushing your site to a remote server, so it can be served statically.

    We’re going to use Heroku to serve our application, a great option for serving Node.js and Rails applications, and they have a generous free plan. You’ll need to signup for an account with them if you haven’t got one already, as well as install the Heroku gem.

    Now, all we need to deploy our app is run a few Heroku commands to get our application deployed.

    heroku create my-spine-app --stack cedar
    git add .
    git commit -m "first commit"
    git push heroku master
    heroku open
    

    Voila! You’ve now got a slick mobile application written in CoffeeScript, HTML5 and CSS3. We’ve got tons of possibilities now, such as wrapping it PhoneGap to access the phone’s APIs, customizing the theme for Android phones or adding offline support.

    Next Steps

    It may feel like a lot to learn, but we’ve actually covered most of Spine’s API in this tutorial. Why not check out the extensive documentation, and learn a bit more about the framework?

    I’m sure you have lots of questions so feel free to ask away in the comments and thank you so much for reading! Otherwise, be sure to refer to our sister-site, Mobiletuts+, for the best Mobile-focused tutorials on the web!


  • Permalink for 'How to Work with GitHub and Multiple Accounts'

    How to Work with GitHub and Multiple Accounts

    Posted: November 2nd, 2011, 2:39pm MDT by Jeffrey Way

    So you have a personal GitHub account; everything is working perfectly. But then, you get a new job, and now need to have the ability to push and pull to multiple accounts. How do you do that? I’ll show you how!

    Prefer a Screencast?

    Choose 720p for the best picture. Step 1 – Create a New SSH Key

    We need to generate a unique SSH key for our second GitHub account.

    ssh-keygen -t rsa -C "your-email-address"
    

    Be careful that you don’t over-write your existing key for your personal account. Instead, when prompted, save the file as id_rsa_COMPANY. In my case, I’ve saved the file to ~/.ssh/id_rsa_nettuts.

    Step 2 – Attach the New Key

    Next, login to your second GitHub account, browse to “Account Overview,” and attach the new key, within the “SSH Public Keys” section. To retrieve the value of the key that you just created, return to the Terminal, and type: vim ~/.ssh/id_rsa_COMPANY.pub. Copy the entire string that is displayed, and paste this into the GitHub textarea. Feel free to give it any title you wish.

    Next, because we saved our key with a unique name, we need to tell SSH about it. Within the Terminal, type: ssh-add ~/.ssh/id_rsa_COMPANY. If successful, you’ll see a response of “Identity Added.”

    Step 3 – Create a Config File

    We’ve done the bulk of the workload; but now we need a way to specify when we wish to push to our personal account, and when we should instead push to our company account. To do so, let’s create a config file.

    touch ~/.ssh/config
    vim config
    

    If you’re not comfortable with Vim, feel free to open it within any editor of your choice. Paste in the following snippet.

    #Default GitHub
    Host github.com
      HostName github.com
      User git
      IdentityFile ~/.ssh/id_rsa
    

    This is the default setup for pushing to our personal GitHub account. Notice that we’re able to attach an identity file to the host. Let’s add another one for the company account. Directly below the code above, add:

    Host github-COMPANY
      HostName github.com
      User git
      IdentityFile ~/.ssh/id_rsa_COMPANY
    

    This time, rather than setting the host to github.com, we’ve named it as github-COMPANY. The difference is that we’re now attaching the new identity file that we created previously: id_rsa_COMPANY. Save the page and exit!

    Step 4 – Try it Out

    It’s time to see if our efforts were successful. Create a test directory, initialize git, and create your first commit.

    git init
    git commit -am "first commit'
    

    Login to your company account, create a new repository, give it a name of “Test,” and then return to the Terminal and push your git repo to GitHub.

    git remote add origin git@github-COMPANY:Company/testing.git
    git push origin master
    

    Note that, this time, rather than pushing to git@github.com, we’re using the custom host that we create in the
    config file: git@github-COMPANY.

    Return to GitHub, and you should now see your repository. Remember:

    • When pushing to your personal account, proceed as you always have.
    • For your company account, make sure that you use git!github-COMPANY as the host.

    Be sure to refer to the screencast if you need a more visual overview of the steps above!


  • Permalink for 'Zend Framework from Scratch'

    Zend Framework from Scratch

    Posted: November 2nd, 2011, 12:05pm MDT by Nikko Bautista

    Ready to take your PHP skills to the next level? In this new “From Scratch” series, we’ll focus exclusively on Zend Framework, a full-stack PHP framework created by Zend Technologies. First in our tutorial series, is “Getting Started with Zend Framework.”

    Introduction: What is Zend Framework?

    Zend Framework is a full-stack PHP framework created by Zend Technologies. For those who aren’t familiar with the company, Zend Technologies provides web developers with various tools to help them in their work. Notable examples are Zend Server, a web application server for running and managing PHP applications, and Zend Studio, a full-featured IDE for PHP. Needless to say, Zend is very invested in PHP, which is why Zend Framework is a great tool to add to any developer’s arsenal.

    The PHP Company

    Zend: The PHP Company

    Zend Framework is made up of many different libraries and classes. This is a double-edged sword — for one, it makes it easier for developers to cherry-pick libraries if they only need some. The downside is that setting up the framework isn’t very easy in the beginning since it’s just a bunch of classes. That being said, Zend does have a scaffolding tool and a recommended way of setting up your application structure, which we’re going to discuss in this particular tutorial.

    In this series of tutorials, we’ll be diving into how Zend Framework works and learning how to use its different components. By the end of the series, we’ll have built a brand new social networking site — complete with basic profile, networking, status updates, and even API functionality. And now, without further ado, let’s begin!

    Step 1: Download Zend Framework

    First and foremost, we need to download Zend Framework. Currently, the latest version is 1.11.11. To begin, go to the Zend Framework website [framework.zend.com] and click on the Download Now button.

    Zend Framework Download Now link

    Zend Framework Download Now link

    This should bring you to a screen with a list of different downloads for Zend Framework. In the future, when you update the Zend Framework library, you should download the Minimal version, which contains just the ZF files. For now, let’s download Zend Framework 1.11.11 Full, which contains the library with all the demos and tests. It also includes the scaffolding tool that we’ll be using later on in the tutorial.

    Zend Framework download list

    Zend Framework download list Step 2: Set up your Zend Framework Environment

    After the download has completed, extract the files to your desktop in order to get a clear view of the contents. Inside, there are a lot of folders, but for the purposes of this tutorial, we will only need two — the bin folder and the library folder.

    Zend Framework 1.11.11 Full contents

    For organization’s sake, put the bin folder inside your PHP folder and rename it to zend-bin. Mine is D:\Development\PHP, so the end result should be D:\Development\PHP\zend-bin.

    bin folder location

    Go into the library folder and you should find a Zend folder. Place this inside your PHP's include_path. For me, that’s D:\Development\PHP\includes, so moving it there should result in D:\Development\PHP\includes\Zend. Remember to copy the Zend folder inside the library folder, not the library folder itself.

    Zend folder location

    Lastly, we need to configure the Zend CLI tool inside the zend-bin folder to work in any directory. To do this, we have to add the directory to the Path System variable, so we can call it via the command prompt.

    Right click the Computer link under Start to open the System Information window. Here, click on Advanced System Settings.

    Windows System Information

    In the window that opens, click on the Environment Variables button. In the new window, look for the Path variable in the System variables list. Click on Edit and add your zend-bin directory location at the end.

    Windows System Variables

    When you’re done, just click OK to save it.

    To ensure that our configuration is working, open a command prompt and run the zf --help command. This should output the commands we can use with the Zend CLI tool. If it doesn’t, try restarting your machine to make sure the System variables are implemented.

    Testing the ZF CLI tool

    Additionally, there is a zf.sh file inside the zend-bin folder. This is for Unix-based operating systems like OSX or Linux. Just set up the environment variables accordingly to get the same result.

    Step 3: Create your First Zend Framework Project

    Now, we begin actual development work on our Zend Framework project. In the command prompt, go to the directory where you want to put your project files (ideally this should be the directory where your local web server points to). For me, it’s D:\Development\htdocs\nettuts, so I’ll run the cd D:\Development\htdocs\nettuts command on my prompt.

    Go to your htdocs directory

    Type in the following command to create our base Zend Framework project: zf create project thenextsocial. In the command, thenextsocial is the name of our project. When you start creating your own ZF projects, replace this with the appropriate project name.

    Create your Zend Framework project

    Check out the contents of the folder now — you should see a new thenextsocial folder. Inside the folder, you should see multiple project files. Most importantly, you should see a public folder, which should be the only publicly accessible folder via browser. To make this accessible, we now need to set up a VirtualHost for the project.

    The Next Social contents

    To set up a VirtualHost, open your Apache’s httpd.conf file. Inside, add the following code:

    <VirtualHost *:80>
        ServerName thenextsocial.local
    	DocumentRoot "D:/Development/htdocs/nettuts/thenextsocial/public/"
    	<Directory "D:/Development/htdocs/nettuts/thenextsocial/public/">
    	</Directory>
    </VirtualHost>
    

    You’ll also need to add the domain to your local hosts file. For Windows users, it should be in C:\Windows\System32\Drivers\etc. For Unix-based OS users, it should be in /etc/hosts. Open it up and add thenextsocial.local and point it to 127.0.0.1

    Hosts file location Editing the local hosts file

    Restart your web server. When you open [thenextsocial.local] on your browser, it should already point to your Zend Framework project.

    The Next Social home page

    Congratulations You’ve successfully created your first Zend Framework project!

    Step 4: Learn about Zend Framework’s MVC Structure What exactly is this MVC pattern?

    From Zend Framework’s quickstart introduction:

    The model-view-controller pattern

    The model-view-controller (MVC) pattern

    Image courtesy of [framework.zend.com]

    The MVC pattern models this separation of concerns well.

    So what exactly is this MVC pattern everyone keeps talking about, and why should you care? MVC is much more than just a three-letter acronym (TLA) that you can whip out anytime you want to sound smart; it has become something of a standard in the design of modern web applications. And for good reason. Most web application code falls under one of the following three categories: presentation, business logic, and data access. The MVC pattern models this separation of concerns well. The end result is that your presentation code can be consolidated in one part of your application with your business logic in another and your data access code in yet another. Many developers have found this well-defined separation indispensable for keeping their code organized, especially when more than one developer is working on the same application.

    The gist of it is this: models contain our business logic, views contain our HTML, and controllers keep everything in line and tell both the views and models what to do.

    MVC in a Zend Framework-powered application

    The good thing about using the ZF CLI tool is that it automatically sets up your application to make use of Zend Framework’s MVC classes, which allows you to begin working on your projects more quickly.

    Going back to our project, open the thenextsocial/application folder and you should see — you guessed it — models, views, and controllers folders.

    MVC Folders

    Inside these folders, open controllers/IndexController.php and views/scripts/index/index.phtml. When you look at both of these files closely, you’ll see that the home page we saw above (Welcome to Zend Framework) is actually executed by both of these files. So how does Zend Framework call these?

    Explaining Zend Framework’s default application routing

    By default, all URLs on your Zend Framework project will follow a certain format:

    [url]/[controller]/[action]/[GET parameter 1 value]/.../[GET parameter x]/[GET parameter x value]

    Another default is that if a controller and/or action is not provided, they both default to index. So calling http://thenextsocial.local is actually the same as calling http://thenextsocial.local/index/index or even http://thenextsocial.local/index.

    Zend Framework default routing cycle

    Zend Framework default routing cycle

    Zend Framework then takes the controller value and looks for it in the controllers folder, namely, our IndexController.php file. Inside the controller file, it takes our action value and executes that method, which is indexAction. After the action has been executed in the controller, ZF then automatically renders the view file inside the views folder in the following format:

    ../application/views/scripts/[controller]/[action].phtml

    Which is why we see the Welcome to Zend Framework page, since index.phtml contains the HTML code for this page.

    Step 5: Pass Data From a Controller to its View

    It’s relatively simple to pass data from a controller to its view. Each controller object is created, by default, to have a view object instantiate with it. Access to this view object is done via the $this->view accessor.

    To send data to the view, we simply assign variables to the view object and give them values, like so:

    $this->view->variable_name = "variable value";
    

    Returning to our project, open IndexController.php in the controllers folder, and in the indexAction method, let’s pass the current date and time to our view.

    public function indexAction()
    {
    	//action body
    	$this->view->current_date_and_time = date('M d, Y - H:i:s');
    }
    

    We then need to edit our view to output this variable. To do so, open index.phtml in the view folder, and add the following code:

    ...
    ...
    ...
    <div id="welcome">
        <h1>Welcome to the <span id="zf-name">Zend Framework!</span></h1>
    
    	<hr /><h2>It is now <?php echo $this->current_date_and_time; ?></h2>
    
        <h3>This is your project's main page</h3>
    ...
    ...
    ...
    

    As you can see, accessing the variable from inside the view file is as simple as echoing the variable via the echo PHP command, echo $this->variable_name;.

    Now, refresh your browser, and you should see the current date and time on the page.

    Passing data from a Controller to the View Step 6: Create a Layout in Zend Framework

    You might have noticed that the html scripts in our project are just fragments and not complete HTML pages, so they lack html, head, and body tags. This is actually not a flaw but was done by design — this way, all actions return content relative only to the action itself, not the whole application. By creating a global layout for our site, we’ll be able to implement a consistent HTML container for all our HTML scripts.

    To get started, we again open our command prompt and issue the following command. Make sure you’re inside the thenextsocial folder.

    zf enable layout
    Enabling a layout in our Zend Framework project

    Enabling a layout in our Zend Framework project

    The output after running the command suggests that a layout file called layout.phtml has been created inside the application/layouts/scripts folder. Let’s open it up and take a look at what’s inside:

    layout.phtml contents

    layout.phtml contents

    The command echo $this->layout()->content; is actually the layout file echoing all of the content from the view. To create our global layout then, we need to wrap this command with our HTML:

    <!DOCTYPE html>
    <html>
    	<head>
    		<title>The Next Social</title>
    		<!-- Load Twitter Bootstrap and jQuery -->
    		<link rel="stylesheet" href=" [twitter.github.com] 		<script src=" [https:] 	</head>
    	<body>
    		<div id="site_container">
    			<div id="header">
    				<p>This is the header!</p>
    			</div>
    			<div id="content">
    				<!-- Echo our content here! -->
    				<?php echo $this->layout()->content; ?>
    			</div>
    			<div id="footer">
    				<p>This is the footer!</p>
    			</div>
    		</div>
    	</body>
    </html>
    

    Now, refresh your browser again and you should see the changes:

    Our index action with accompanying layout

    Our index action with accompanying layout Step 7: Create New Controllers and Actions

    By using the ZF CLI tool, we can create new controllers and actions very quickly. To do so, simply run the following command:

    zf create controller About

    About is our new controller’s name. If you check inside the controllers folder, you should see an AboutController.php file, indicating that our controller generation was successful. You can also check the contents of the views folder and see that a new about/index.phtml file has been created for our About controller!

    Creating our About controller

    Creating our About controller

    We should then be able to access this controller by going to [thenextsocial.local]

    By default, the ZF CLI tool creates one action for our controller, the indexAction. But what if we wanted to add other actions to the controller?

    Creating a new action

    Creating a new action is as is easy creating a new controller. To do so, just run the following command:

    zf create action us About

    This effectively creates a new action called us inside the About controller. Checking the AboutController.php file, you should see a new usAction() method, as well as a new us.phtml file inside the about view folder.

    Creating our us action in the About controller

    Creating our us action in the About controller

    As you can see, we rely heavily on the ZF CLI tool to generate actions and controllers. Manually creating them works the same way; the ZF CLI tool just makes it simpler and automatically does the heavy lifting for us.

    Conclusion

    After reading this tutorial, you should already know the following:

    • Where to download the latest Zend Framework files
    • Where and how to set it up locally
    • Creating your first Zend Framework project and setting up a VirtualHost on your web server
    • How exactly Zend Framework implements the MVC pattern and its default application routing
    • Passing data from a controller to its view
    • Creating a site-wide layout for your Zend Framework application
    • Creating new controllers and actions

    From this knowledge, you should easily be able to create static web pages. But we all know this isn’t enough!

    In our next tutorial, we’ll learn all about creating the most crucial part of any web application, the model, and making The Next Social a dynamic site!

    Until then, stay tuned!

    P.S. I’ve registered thenextsocial.com for the purposes of this project. Just visit the site regularly and you’ll see it transform from a simple site to the full-featured social networking site we intend to have at the end of this series. Additionally, all the source code created in the series will be available on this GitHub repository as well!


  • Permalink for 'Quick Tip: How to Keep the Count with CSS'

    Quick Tip: How to Keep the Count with CSS

    Posted: November 1st, 2011, 6:17pm MDT by Jeffrey Way

    Did you know that, with CSS, you can create a counter? This can be especially useful for instances where the count is purely needed for presentational purposes. I’ll show you how to use counter-increment in this useful quick tip.

    Screencast

    Choose 720p for the best picture. How Does it Work?

    It’s really quite simple. We’re not even talking CSS3 here; the counter-increment property has been around for a while now. It’s just that many of us aren’t familiar with it, or haven’t found a use for it.

    We begin by applying the counter-increment property. Let’s imagine that we have a set of boxes, and each box should display a number that corresponds to the order that the box occurs it its sequence.

    .box {
      counter-increment: boxes;
    }
    

    The counter-increment property can accept either one or two properties. The first is an id that you will later use to reference this specific counter. You may also pass a second parameter that refers to the increment. For example, instead of 1, 2, 3, 4, you could switch to 5, 10, 15, 20 by applying: counter-increment: boxes 5.

    This code will now store a unique number for each element that has a class of box. But of course, we want to get this number on the page. Hopefully, we’ll, at some point in the future, be able to use the content property within standard selectors, but not quite yet. Instead, we’ll use pseudo elements to apply the content.

    .box:after {
      content: counter(boxes);
    }
    

    This will apply a unique number – again, based on the element’s order in the sequence – to the .box element. Should we need to reset this order back to 1 at some point, we could usethe counter-reset: boxes property.

    Why Do This, Again?

    Now, you still might be thinking: “Why would I ever use this?” There’s lots of situations when it might be handy. For example, consider a comments section of a blog. If you wanted to provide
    a number for each comment in the set – possibly slightly transparent – you could use this technique. The number isn’t vital to the markup, and is only used for presentation. In these cases, CSS
    counters will do the trick nicely!


  • Permalink for 'Best of Tuts+ in October'

    Best of Tuts+ in October

    Posted: November 1st, 2011, 10:10am MDT by David Appleyard

    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
    • Create a Fantasy Miniature World in Photoshop Photo Effects Week: Create a Fantasy Miniature World in Photoshop

      This week we are celebrating the launch of PhotoDune, Envato’s new stock photography website with a series of photo effect and photo manipulation tutorials that showcase the images from our new marketplace. In this tutorial we’ll demonstrate how to create a miniature world using some interesting techniques. Many of the photos used in this tutorial are available for free for Psd Premium Members. Let’s get started!

      Visit Article

    • Create a Cutout Photograph in Photoshop Photo Effects Week: Create a Cutout Photograph in Photoshop

      This week we are celebrating the launch of PhotoDune, Envato’s new stock photography website with a series of photo effect and photo manipulation tutorials that showcase the images from our new marketplace. In this tutorial we will demonstrate how to create a cutout photo using simple selections and advanced transformations. The photos used in this tutorial are available for free for Psd Premium Members. Let’s get started!

      Visit Article

    • Create a Stitched Text Effect for an iPad Wallpaper Create a Stitched Text Effect for an iPad Wallpaper

      In this tutorial we will show you how to create a custom stitched text effect for an iPad Wallpaper. Let’s get started!

      Visit Article

    • Nettuts+ — Web Development Tutorials
    • Stop Nesting Functions! (But Not All of Them) Stop Nesting Functions! (But Not All of Them)

      JavaScript is over fifteen years old; nevertheless, the language is still misunderstood by what is perhaps the majority of developers and designers using the language. One of the most powerful, yet misunderstood, aspects of JavaScript are functions. While terribly vital to JavaScript, their misuse can introduce inefficiency and hinder an application’s performance.

      Visit Article

    • The Intro to Rails Screencast I Wish I Had The Intro to Rails Screencast I Wish I Had

      Isn’t it funny how most “introduction to Ruby on Rails” screencasts are overly simplistic, and rely on generators like scaffolding? The teacher typically follows up the tutorial by stating that most Rails developer don’t use scaffolding generators. Well that’s not much help then! I’d like to give you the tutorial I wish I had. Along the way, we’ll also rely heavily on test-driven development to build a simple app.

      Visit Article

    • The Best Way to Learn PHP The Best Way to Learn PHP

      Learning something from scratch is almost always an arduous affair — you simply have no idea as to where to start, or not to start, to kick things off. I loathed learning about the idiosyncrasies of C++’s syntax when all I wanted to learn were some darn programming concepts. As I’m sure you can agree, this is a less than ideal situation.

      Visit Article

    • Vectortuts+ — Illustrator Tutorials
    • 250+ Free, Vintage Graphics: Flourish Vector Ornaments Free, Vintage Graphics: Flourish Vector Ornaments

      Wow, if you’re looking for high quality free vector graphics, then you’ve landed on the right article. We’ve roundup up a massive collection of free vector flourishes. These graphics are composed of a wonderful mix of vintage elements, floral ornaments, swirly design mixes, and are all made of beautifully curved vector art.

      Visit Article

    • Beginners Guides to InDesign Beginners Guides to InDesign

      InDesign is a powerful design program with so many tools and features it can a bit tricky to find a topic to begin with. With this in mind, we’ve put together a collection of beginner guides on various InDesign topics like the best way to create a new document, how to import text and images and even useful advice on what to do when a document is corrupted and how to make comments and track changes.

      Visit Article

    • How to Color a Cute Character using Graphic Styles How to Color a Cute Character using Graphic Styles

      Coloring a character sketch can sometimes take much longer than anyone expects. With a few layer tricks and Graphic Styles, I will show you how to create a character that is quick to ink, easy to edit and a breeze to re-color. Let’s get started!

      Visit Article

    • Webdesigntuts+ — Web Design Tutorials
    • Design a Static Admin Bar in Photoshop Design a Static Admin Bar in Photoshop

      Let’s whip up a simple, yet effective ‘static admin bar’ in Photoshop. We’ll take a selection of UI elements, and design their various states, ready for building in HTML and CSS.

      Visit Article

    • A Smarter Twitter Page in Under 15 Minutes A Smarter Twitter Page in Under 15 Minutes

      Today we’ll design a smart, vintage modern background to welcome visitors to your Twitter page. We’ll go over some layout considerations, then dive into Photoshop. Have fifteen minutes spare? Let’s go then!

      Visit Article

    • Build An Innovative Portfolio Site Using Alternative UI/UX Build An Innovative Portfolio Site Using Alternative UI/UX

      Paul J Noble’s awwward winning, uniquely designed portfolio site has caught the eye of many people, and not just clients either. Today he’s going to follow up on the design stage of this tutorial, and demonstrate how it’s coded up.

      Visit Article

    • Phototuts+ — Photography Tutorials
    • A Look at Camera Straps Strapping Up: A Look at Camera Straps

      Ever stop to think about what is holding your camera when your hands aren’t? Lots of photography tutorials focus on cameras, lenses, and lighting. Even bags and filters get a lot of press. However, there is one important piece of equipment that gets neglected and choosing the wrong one can be a literal pain in the neck. So, we’re going to take a look at various camera straps and how they indirectly impact your photography.

      Visit Article

    • 100 Fantastic Photos of Reptiles and Amphibians Fantastic Photos of Reptiles and Amphibians

      Today’s photo collection is a tribute to all things scaly, slimy, or perhaps even both. We have gathered one hundred impeccable examples of reptile and amphibian photography. Whether these creatures are swimming in ponds or slithering underfoot, numerous talented photographers have found them to be the perfect subjects for many beautiful compositions.

      Visit Article

    • Picking Your Medium Finishing Your Photographs: Picking Your Medium

      Photographers spend a great deal of energy capturing the best image possible and ensuring the image or print is faithfully reproduced. We may not, however, spend as much energy thinking about how to finish a photograph – print, frame or store it – and archive the image.

      Visit Article

    • Cgtuts+ — Computer Graphics Tutorials
    • The Making Of “Yuki Machi” The Making Of “Yuki Machi”

      This is a walk through from start to finish of how I made my “Yuki Machi” scene. This tutorial is intended for beginners and students who are making the switch from creating and building assets to creating whole scenes and environments. Ill take you through the processes and techniques I use and show you the challenges l face when making larger sets.

      Visit Article

    • An Amazingly Detailed Dodge Tire Model Freebie: An Amazingly Detailed Dodge Tire Model

      Need some sweet rims for your next vehicle model? Well you’re in luck! Because Ivan Momchilov is giving away this epic Dodge tire model, complete with a set of highly detailed brakes. For you 3d Studio Max users out there, Ivan has included scene files for 2010,2011 and 2012! And for the non Max users, we have it available in .obj format as well, making it super easy to import it into your software package of choice. This model’s free to all, so download it today!

      Visit Article

    • Modeling and Animating An Xpresso Driven Clock In Cinema 4D Modeling and Animating An Xpresso Driven Clock In Cinema 4D

      Today we’ll take some time (did you get it?) to model and animate a clock in Cinema 4D using only Xpresso. We’ll model the clock from a basic cylinder and add some simple materials and lighting to the scene. Once we have the model complete, we’ll begin animating the clock with Xpresso and add some user data to have more control over our final animation.

      Visit Article

    • Aetuts+ — After Effects Tutorials
    • How To Create And Rig A Realistic Puppet Overview How To Create And Rig A Realistic Puppet Overview

      This is a quick overview of Aetuts+’s “How To Create And Rig A Realistic Puppet” Series. We will be posting a new chapter every day or so for the entire month of October. There are 17 parts total so check it regularly!

      Visit Article

    • Use Real Lights To Motivate Simulated Lights in After Effects – AE Premium Use Real Lights To Motivate Simulated Lights in After Effects – AE Premium

      This demonstration is about shooting a translucent object, in this case a crystal illuminated by a match, and compositing that object with stock footage of dramatic fire. Finally, we’ll be simulating similar lighting effects in After Effects to reveal a logo.

      Visit Article

    • Create And Composite A Mobile Phone App Demo Template Create And Composite A Mobile Phone App Demo Template

      In this tutorial you will learn the workflow on how to set up a scene for an animated pack shot of a phone in CINEMA 4D and composite it in After Effects. Perhaps you have developed a revolutionary iPhone app that you want to show off to the world, or maybe you just want to learn the basic workflow of compositing 3D passes in After Effects. Either way I hope this tutorial will help you along the way.

      Visit Article

    • Audiotuts+ — Audio & Production Tutorials
    • 5 Of My Current Favourite iOS Apps Of My Current Favourite iOS Apps

      As you may have already realised Im a pretty big fan of all things Apple. Not only do I utilise Apple computers in my production process but I also lean pretty heavily on IOS-based devices in the studio.

      Visit Article

    • Vocal Loop Effect in Reason Vocal Loop Effect in Reason

      In electronic dance music, DJ’s often loop tracks to cheer up the crowd. In your music productions, you can also use this effect to create an uplifting effect for what’s to come. This tutorial shows you how to create such a loop effect on vocals, using Reason 4.0.

      Visit Article

    • Adding Flavor to Chords – Major and Minor 7ths – Basix Adding Flavor to Chords – Major and Minor 7ths – Basix

      Today we are going to cover how to add some flavor to your chords and compositions using 7ths in both major and minor. It is surprising how many people know how to play them but do not really understand how they are built and function (guitarists I am talking to you!).

      Visit Article

    • Activetuts+ — Flash, Flex & ActionScript Tutorials
    • Create a Flexible XMPP Chat for a Member-Based Website With Flash and PHP Create a Flexible XMPP Chat for a Member-Based Website With Flash and PHP

      We’ll be looking at how to create a XMPP chat application that can be used in many different scenarios. You’ll learn how to integrate an external database with Ignite Realtime’s Openfire Jabber Server and how to use the XIFF library to create custom XMPP extensions that can be used to send custom data across a network.

      Visit Article

    • Introduction UI Design for Developers: Introduction

      Designers vs. developers – it is an argument as old as computers. The truth is, though, neither can live without the other. A brilliant UI design is as worthless without functionality as is the best piece of code with an ugly, unusable frontend. In this first post on UI Basics for developers, I am going to try and lay out some simple ground rules that devs can follow to make sure their apps, templates and prototypes are as beautiful as the code itself – and usable to boot.

      Visit Article

    • Events – Basix AS3 101: Events – Basix

      For this chapter of AS3 101, we will be diving into the mechanics of the Flash event system. If you’ve been following along so far, you’ll have seen events in use, dating all the way back to the first episode of the series. The editor and I felt that it was time to write up something to be formally included in the curriculum, so if you’ve ever seen those lines of code about adding event listeners or dispatching events, and not quite caught on, then this is the tutorial for you.

      Visit Article

    • Wptuts+ — WordPress Tutorials
    • Theme Anatomy Model WordPress Cheat Sheets: Theme Anatomy Model

      Next in line for our WordPress Cheat Sheet series, The Basic WordPress Theme Anatomy Model! If you haven’t seen the first posts in this series, this is a new batch of these quick pocket guides that you guys n’ gals can download, save to your phones for a fast reference, or even print out and keep next to your desk while you’re working on customizing WordPress to do your bidding.

      Visit Article

    • Day One WordPress Theme Development Training Wheels: Day One

      Ready to learn how to make your first WordPress theme? This tutorial series will take a step by step approach, making use of a "learning theme" affectionately known as WordPress Training Wheels, to help teach the subject. This series will take the absolute WordPress newbie through the basic steps necessary to convert any HTML template into a fully functional WordPress theme.

      Visit Article

    • WordPress 3.3 is On the Horizon! Beta 2 Release Notes WordPress 3.3 is On the Horizon! Beta 2 Release Notes

      WordPress is evolving quite faster than ever, and every update gets all excited (especially those who make a living on it). WordPress has released it’s 3.3, Beta 2 version just 2 days ago for testing. This update is focused on more improvements, refining and making things faster and better. Today, we’re going to round up what’s coming in the next big version.

      Visit Article

    • Mobiletuts+ — Mobile Development Tutorials
    • iOS 5 SDK First Look: iOS 5 SDK

      iOS 5 has been officially released, and iOS developers are eager to begin making use of the many new features available in the iOS 5 SDK. In this article, industry gurus Brandon Trebitowski and Collin Ruffenach reflect on the opportunities, efficiencies, and most exciting features of the latest SDK. This post is a must read for all iOS SDK developers!

      Visit Article

    • Safari Mobile Updates iOS 5 for Web Devs: Safari Mobile Updates

      Native iOS developers aren’t the only ones with something to be excited about when it comes to developing for iOS 5. A new version of Safari Mobile was released alongside the latest operating system, and mobile web developers now have many new features to experiment with. Get up to speed on the changes in this article!

      Visit Article

    • Fixed Positioning and Content Scrolling iOS 5: Fixed Positioning and Content Scrolling

      Two of the most celebrated enhancements to Safari on iOS 5 are fixed positioning and content scrolling support. This tutorial will teach you how to take advantage of this change and what the implications are for stop-gap JavaScript libraries like iScroll.

      Visit Article

    • FreelanceSwitch — Articles and Resources for Freelancers
    • Keys to Setting Your Rate Based on Experience Keys to Setting Your Rate Based on Experience

      There is no one set strategy for setting your rates, which is why the process can be so confusing for freelancers. Basing your rates off regional competitors’ prices is a very smart tactic, but I think many freelancers forget about something important when putting together rates, and that is their value.

      Visit Article

    • 5 Rarely Remembered Rules for Building Your Freelance Brand 5 Rarely Remembered Rules for Building Your Freelance Brand

      Having a strong brand can be a game-changer for your freelance business.
      Good brands command respect and establish a reputation. They establish your presence in the marketplace. When questions arise like “where can I find a good freelance writer” or “where do I go to get my website redesigned” … strong brands immediately come to mind.
      So how do you build your brand? What rules of branding should you follow?

      Visit Article

    • 7 Ways to Tell a Client He’s Wrong

      Telling a client that he is, in fact, wrong can be the hardest thing you ever have to do in your freelance career. It’s not something that we generally consider to be a healthy step: it can lose you a client pretty quickly if not handled properly.
      Even if a client accepts that he is incorrect about something, it may still be harder to work with him in the long run.

      Visit Article


  • Permalink for 'Recently in Web Development (October Edition)'

    Recently in Web Development (October Edition)

    Posted: October 31st, 2011, 12:04pm MDT by Siddharth

    Web development is an industry that’s in a state of constant flux with technologies and jargon changing and mutating in an endless cycle. Not to mention the sheer deluge of information one has to process everyday.

    In this series, published monthly, we’ll seek to rectify this by bringing you all the important news, announcements, releases and interesting discussions within the web development industry in a concise package. Join me after the jump!

    News and Releases

    All of the important news in a single place: releases, announcements, companies bickering, security issues and all related hoopla.

    The World Loses a Few Luminaries

    October, overall, was quite a sad month for techies everywhere. In case, you missed it, here are a few of the fine people we lost over the month.

    Nettuts image Dennis Ritchie

    Dennis MacAlistair Ritchie was an American computer scientist who “helped shape the digital era”. He created the C programming language and, with long-time colleague Ken Thompson, the UNIX operating system. Everything digital probably runs on was created using the language this splendid mind created.

    Nettuts image John McCarthy

    John McCarthy was the inventor of the LISP programming language, an American computer scientist and cognitive scientist who received the Turing Award in 1971 for his major contributions to the field of Artificial Intelligence (AI). He was responsible for the coining of the term “Artificial Intelligence”.

    Nettuts image Steve Jobs

    Last, but not least, Steve Jobs passed away earlier this month. For those that have been living under a rock, Jobs was the co-founder of Apple and one of the creative minds behind a lot of the popular gadgets we use today. If you’re even the tiniest bit interested about him, I highly recommend picking up his biography — it’s an excellent read.

    A moment in honor of these great men, if you will.

    Nettuts image Google Introduces the Dart Programming Language

    Google, in their quest to make development easier, released a new programming language targeted at web developers. Called Dart, this language should feel familiar to most Java/C# programmers. I’m sure you have lots more questions so feel free to hit the link below for the official announcement post.

    Read more

    Nettuts image Heroku Adopts for Python and Django

    Heroku, one of the most well known platform-as-a-service providers, recently announced that they’re adding Python to their list of supported languages. The list now includes Ruby, Java, PHP, Scala and Clojure along with Python. Hit the link below to glean more on how to use Python on Heroku.

    Read more

    Nettuts image Mozilla Shows off Aurora 9

    Mozilla released Aurora 9, slated to be the upcoming Firefox 9. The build includes a lot of niceties for developers including new mouse events, improved JavaScript performance as well as user oriented features such as support for ‘Do Not Track’.

    Read more

    Nettuts image Sinatra 1.3 Released

    Quite probably the most fun framework ever just got updated to version 1.3. This version ships with a lot of nice new features about which you can read about in the link below.

    Read more

    Nettuts image Apache Releases Version 1.7 of Subversion

    Amongst all the talk about Git, it’s easy to forget that there are plenty of similarly abled version control solutions out there. One such fine alternative is Subversion and Apache just released a bit update to the software with plenty of bug fixes, performance improvements and new features.

    Read more

    Nettuts image Google Releases the Google JS Test

    Google JS Test is a JavaScript unit testing framework that runs on the V8 JavaScript Engine, the same open source project that is responsible for Google Chrome’s super-fast JS execution speed.

    Read more

    Nettuts image Google Unleashes ScriptCover

    ScriptCover is a Chrome extension that provides line-by-line Javascript code coverage statistics for web pages in real time without user modification of the site. Results are collected when the page loads and continue to be updated as users interact with the page. These results can be viewed in real time through a reporting tool which highlights the executed lines of code for detailed analysis. ScriptCover is useful when performing manual and automated testing and in understanding and debugging complex code.

    Read more

    New Kids on the Block

    As web developers, the sheer amount of resources we can tap into increases exponentially with time. Here is just a quick look at some recently created resources that deserve your attention — everything from new books to scripts and frameworks.

    Nettuts image money.js

    JavaScript currency conversion library, done right – with no dependencies, in just over 1 kb.

    Read more

    Nettuts image AliceJS

    AliceJS is a micro JavaScript library focused on using hardware-accelerated capabilities (in particular CSS3 features) in modern browsers for generating high-quality, high-end visual effects.

    Read more

    Nettuts image validate.js

    Lightweight JavaScript form validation library inspired by CodeIgniter.
    No dependencies, just over 1kb gzipped, and customizable!

    Read more

    Nettuts image List.js

    List.JS is a 7 KB cross-browser native JavaScript that makes your plain HTML lists super flexible, searchable, sortable and filterable? You can also add, edit and remove items by dead simple templating?

    Read more

    Nettuts image Tangle

    Tangle is a JavaScript library for creating reactive documents. Your readers can interactively explore possibilities, play with parameters, and see the document update immediately. Tangle is super-simple and easy to learn.

    Read more

    Nettuts image JSZip

    The easiest way to deliver multiple files to your users is in a zip file. Instead of wasting server resources and bandwidth you can get the client to do it for you.

    Read more

    Nettuts image Zynga Scroller

    A pure logic component for scrolling/zooming. It is independent of any specific kind of rendering or event system.

    Read more

    Nettuts image Raptor

    Raptor is a unique framework that’s Ruby powered, Rack compatible, controller-free amongst lot others. If you’re a Ruby-ist, I strongly recommend taking a look at the framework.

    Read more

    Nettuts image Raphael

    While not really a new utility, Dmitry just pushed out a new version of his much acclaimed Raphael vector library. Make sure to check it out!

    Read more

    Nettuts image Donatello

    Donatello is a pure-CSS drawing library for the browser. The API is inspired in part by Raphael.js. All graphical elements are rendered using HTML DOM and CSS. The idea came together from various code snippets I had lying around for drawing circles and lines in other projects. I decided to make an attempt at a drawing API using these ideas after using Raphael.js in my Node Knockout team project.

    Read more

    Best of the Internet

    Often, you’re not really looking for a tutorial as much as you’re looking for a rant, an opinion or the musings of a tired developer or just something cool with absolutely zero real world use. This sections contains links to precisely those — interesting and cool stuff from the developer community.

    Nettuts image Ryan Dahl on Software

    An excellent, little rant-ish post on Unix, software development and abstraction. An excellent read indeed!

    Read more

    Nettuts image ‘Algorithm’ is Not a Four Letter Word

    Jamis Buck from 37Signals talk about algorithms and why they should be a part of your programming training regimen.

    Read more

    Nettuts image Node.js is Cancer

    Ted Dziuba explains why he thinks Node.JS is a disaster waiting to happen. Contains a few expletives so be warned.

    Read more

    Nettuts image repl.it

    repl.it is an online environment for interactively exploring programming languages. The name comes from the read-eval-print loop, the interactive toplevel used by languages like Lisp and Python. An excellent tool if you merely want to mess around with a language.

    Read more

    Nettuts image Node.js Cures Cancer

    As it often happens in our field, an incendiary article often results in numerous counter articles. In this example, Brian Beck counters Ted’s post about Node.JS.

    Read more

    Nettuts image JavaScript Face Detection

    Title says it all. Face detection using canvas and the video element along with a bit of JavaScript. Really cool stuff!

    Read more

    Nettuts image Noise with JavaScript

    Cool little script that generates noise using the canvas element.

    Read more

    Wrapping Up

    Well, that’s about all the major changes that happened in our industry lately. Since this is the first time we’re doing something along these lines, everything is still up in the air — future editions will be shaped by your feedback.

    Do you want us to cover more standard news? A focus on upcoming scripts maybe? Or just more interesting posts and discussions from the community? Let us know in the comments and thank you so much for reading!


  • Permalink for 'How to Scrape Web Pages with Node.js and jQuery'

    How to Scrape Web Pages with Node.js and jQuery

    Posted: October 28th, 2011, 8:34am MDT by Jaime Tanori

    Node.js is growing rapidly; one of the biggest reasons for this is thanks to the developers who create amazing tools that significantly improve productivity with Node. In this article, we will go through the basic installation of Express, a development framework, and creating a basic project with it.

    What We’re Going to Build Today

    Node is similar in design to, and influenced by, systems like Ruby’s Event Machine or Python’s Twisted. Node takes the event model a bit further – it presents the event loop as a language construct instead of as a library.

    In this tutorial, we will scrape the YouTube home page, get all the regular sized thumbnails from the page as well as links and video duration time, send all those elements to a jQueryMobile template, and play the videos using YouTube embed (which does a nice job of detecting device media support (flash/html5-video).

    We will also learn how to begin using npm and Express, npm’s module installation process, basic Express routing and the usage of two modules of Node: request and jsdom.

    For those of you who aren’t yet familiar with Node.js is and how to install it, please refer to the node.js home page
    and the npm GitHub project page.

    You should also refer to our “Node.js: Step by Step” series.

    Note: This tutorial requires and assumes that you understand what Node.js is and that you already have node.js and npm installed.

    Step 1: Setting Up Express

    So what exactly is Express? According to its developers, it’s an..

    Insanely fast (and small) server-side JavaScript web development framework built on Node and Connect.

    Sounds cool, right? Let’s use npm to install express. Open a Terminal window and type the following command:

    npm install express -g
    

    By passing -g as a parameter to the install command, we’re telling npm to make a global installation of the module.

    I’m using /home/node-server/nettuts for this example, but you can use whatever you feel comfortable with.

    After creating our express project, we need to isntruct npm to install express’ dependencies.

    cd nodetube
    npm install -d
    

    If it ends with, “ok,” then you’re good to go. You can now run your project:

    node app.js
    

    In your browser, go to http://localhost:3000.

    Step 2: Installing Needed Modules JSDOM

    A JavaScript implementation of the W3C DOM.

    Go back to your Terminal and, after stopping your current server (ctr + c), install jsdom:

    npm install jsdom
    
    Request

    Simplified HTTP request method.

    Type the following into the Terminal:

    npm install request
    

    Everything should be setup now. Now, it’s time to get into some actual code!

    Step 3: Creating a Simple Scraper app.js

    First, let’s include all our dependencies. Open your app.js file, and, in the very first lines, append the following code:

    /**
     * Module dependencies.
     */
    
    var express = require('express')
    , jsdom = require('jsdom')
    , request = require('request')
    , url = require('url')
    , app = module.exports = express.createServer();
    

    You will notice that Express has created some code for us. What you see in app.js is the most basic structure for a Node server using Express. In our previous code block, we told Express to include our recently installed modules: jsdom and request. Also, we’re including the URL module, which will help us parse the video URL we will scrape from YouTube later.

    Scraping Youtube.com

    Within app.js, search for the “Routes” section (around line 40) and add the following code (read through the comments to understand what is going on):

    app.get('/nodetube', function(req, res){
    	//Tell the request that we want to fetch youtube.com, send the results to a callback function
            request({uri: 'http://youtube.com'}, function(err, response, body){
                    var self = this;
    		self.items = new Array();//I feel like I want to save my results in an array
    
    		//Just a basic error check
                    if(err && response.statusCode !== 200){console.log('Request error.');}
                    //Send the body param as the HTML code we will parse in jsdom
    		//also tell jsdom to attach jQuery in the scripts and loaded from jQuery.com
    		jsdom.env({
                            html: body,
                            scripts: ['http://code.jquery.com/jquery-1.6.min.js']
                    }, function(err, window){
    			//Use jQuery just as in a regular HTML page
                            var $ = window.jQuery;
    
                            console.log($('title').text());
                            res.end($('title').text());
                    });
            });
    });
    

    In this case, we’re fetching the content from the YouTube home page. Once complete, we’re printing the text contained in the page’s title tag (<title>). Return to the Terminal and run your server again.

    node app.js
    

    In your browser, go to: http://localhost:3000/nodetube

    You should see, “YouTube – Broadcast Yourself,” which is YouTube’s title.

    Now that we have everything set up and running, it is time to get some video URLs. Go to the YouTube homepage and right click on any thumbnail from the “recommended videos” section. If you have Firebug installed, (which is highly recommended) you should see something like the following:

    There’s a pattern we can identify and which is present in almost all other regular video links:

    div.vide-entry
    span.clip
    

    Let’s focus on those elements. Go back to your editor, and in app.js, add the following code to the /nodetube route:

    app.get('/nodetube', function (req, res) {
        //Tell the request that we want to fetch youtube.com, send the results to a callback function
        request({
            uri: 'http://youtube.com'
        }, function (err, response, body) {
            var self = this;
            self.items = new Array(); //I feel like I want to save my results in an array
    
    		  //Just a basic error check
            if (err && response.statusCode !== 200) {
                console.log('Request error.');
            }
    
    		  //Send the body param as the HTML code we will parse in jsdom
            //also tell jsdom to attach jQuery in the scripts
            jsdom.env({
                html: body,
                scripts: ['http://code.jquery.com/jquery-1.6.min.js']
            }, function (err, window) {
                //Use jQuery just as in any regular HTML page
                var $ = window.jQuery,
                    $body = $('body'),
                    $videos = $body.find('.video-entry');
    
    				//I know .video-entry elements contain the regular sized thumbnails
                //for each one of the .video-entry elements found
                $videos.each(function (i, item) {
    
    					 //I will use regular jQuery selectors
                    var $a = $(item).children('a'),
    
    						  //first anchor element which is children of our .video-entry item
                        $title = $(item).find('.video-title .video-long-title').text(),
    
    						  //video title
                        $time = $a.find('.video-time').text(),
    
    						  //video duration time
                        $img = $a.find('span.clip img'); //thumbnail
    
    					 //and add all that data to my items array
                    self.items[i] = {
                        href: $a.attr('href'),
                        title: $title.trim(),
                        time: $time,
    
    						  //there are some things with youtube video thumbnails, those images whose data-thumb attribute
                        //is defined use the url in the previously mentioned attribute as src for the thumbnail, otheriwse
                        //it will use the default served src attribute.
                        thumbnail: $img.attr('data-thumb') ? $img.attr('data-thumb') : $img.attr('src'),
                        urlObj: url.parse($a.attr('href'), true) //parse our URL and the query string as well
                    };
                });
    
    				//let's see what we've got
                console.log(self.items);
                res.end('Done');
            });
        });
    });
    

    It’s time to restart our server one more time and reload the page in our browser [localhost:3000] In your Terminal, you should see something like the following:

    This looks good, but we need a way to display our results in the browser. For this, I will use the Jade template engine:

    Jade is a high performance template engine heavily influenced by Haml, but implemented with JavaScript for Node.

    In your editor, open views/layout.jade, which is the basic layout structure used when rendering a page with Express. It is nice but we need to modify it a bit.

    views/layout.jade
    !!! 5
    html(lang='en')
      head
        meta(charset='utf-8')
        meta(name='viewport', content='initial-scale=1, maximum-scale=1')
        title= title
        link(rel='stylesheet', href='http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min.css')
        script(src='http://code.jquery.com/jquery-1.6.2.min.js')
        script(src='http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min.js')
      body!= body
    

    If you compare the code above with the default code in layout.jade, you will notice that a few things have changed – doctype, the viewport meta tag, the style and script tags served from jquery.com. Let’s create our list view:

    views/list.jade

    Before we start, please browse through jQuery Mobile’s (JQM from now on) documentation on page layouts and anatomy.

    The basic idea is to use a JQM listview, a thumbnail, title and video duration label for each item inside the listview along with a link to a video page for each one of the listed elements.

    Note: Be careful with the indentation you use in your Jade documents, as it only accepts spaces or tabs – but not both in the same document.

    div(data-role='page')
        header(data-role='header')
            h1= title
        div(data-role='content')
        	//just basic check, we will always have items from youtube though
            - if(items.length)
                //create a listview wrapper
                ul(data-role='listview')
                    //foreach of the collected elements
                    - items.forEach(function(item){
                        //create a li
                        li
                            //and a link using our passed urlObj Object
                            a(href='/watch/' + item['urlObj'].query.v, title=item['title'])
                                //and a thumbnail
                                img(src=item['thumbnail'], alt='Thumbnail')
                                //title and time label
                                h3= item['title']
                                h5= item['time']
                    - })
    

    That is all we need to create our listing. Return to app.js and replace the following code:

                            //let's see what we've got
                            console.log(self.items);
                            res.end('Done');
    

    with this:

                            //We have all we came for, now let's render our view
    			res.render('list', {
                            	title: 'NodeTube',
    				               items: self.items
                            });
    

    Restart your server one more time and reload your browser:

    Note: Because we’re using jQuery Mobile , I recommend using a Webkit based browser or an iPhone/Android cellphone (simulator) for better results.

    Step 4: Viewing Videos

    Let’s create a view for our /watch route. Create views/video.jade and add the following code:

    div(data-role='page')
        header(data-role='header')
            h1= title
        div(data-role='content')
        	//Our video div
            div#video
                //Iframe from  youtube which serves the right media object for the device in use
                iframe(width="100%", height=215, src=" [www.youtube.com] + vid, frameborder="0", allowfullscreen)
    

    Again, go back to your Terminal, restart your server, reload your page, and click on any of the listed items. This time a video page will be displayed and you will be able to play the embed video!

    Bonus: Using Forever to Run Your Server

    There are ways we can keep our server running in the background, but there’s one that I prefer, called Forever, a node module we can easily install using npm:

    npm install forever -g
    

    This will globally install Forever. Let’s start our nodeTube application:

    forever start app.js
    

    You can also restart your server, use custom log files, pass environment variables among other useful things:

    //run your application in production mode
    NODE_ENV=production forever start app.js
    
    Final Thoughts

    I hope I’ve demonstrated how easy it is to begin using Node.js, Express and npm. In addition, you’ve learned how to install Node modules, add routes to Express, fetch remote pages using the Request module, and plenty of other helpful techniques.

    If you have any comments or questions, please let me know in the comments section below!


  • Permalink for 'Fantastic Prizes Up for Grabs in the Tuts+ Survey!'

    Fantastic Prizes Up for Grabs in the Tuts+ Survey!

    Posted: October 27th, 2011, 8:04am MDT by David Appleyard

    We love the community of readers we have at Tuts+ and your opinion is incredibly valuable. This week, we’re giving you the chance to have your say about Tuts+, and win a few fantastic prizes at the same time! Read on to find out how to get involved and stand a chance of winning a copy of Adobe Creative Suite…

    Survey Now Closed — Thank you to everyone who entered!

    The Prizes!

    We have a few fantastic prizes up for grabs, and the winning entries will be chosen at random when the survey closes in one week. Here’s what you stand a chance of winning:

    1st Prize: 1 x Adobe Creative Suite 5.5 Web Premium

    This prize has been kindly donated by Business Catalyst. Adobe Creative Suite 5.5 Web Premium software provides everything you need to create and deliver standards-based websites with HTML5, jQuery Mobile, and CSS3 support. Design immersive digital experiences and apps across desktops, smartphones, tablets, and televisions.

    You’ll find plenty of incredible software inside, including Photoshop CS5 Extended, Illustrator CS5, Flash Professional CS5.5, Dreamweaver CS5.5, and Fireworks CS5. It’s the perfect accompaniment to everything we teach at Tuts+!

    Runner-Up Prize: 4 x Six Month Tuts+ Premium Memberships

    Four lucky runners up will receive a six month subscription to our Tuts+ Premium membership programme, completely free of charge! This is a brilliant way to expand your knowledge in different creative areas, and access a regular selection of incredibly high-quality tutorials and resources. You’ll be a pro in no time!

    Competition Sponsored by Business Catalyst

    Business Catalyst is a Adobe’s new hosted service for building business websites, replacing 5+ separate tools with one integrated solution.

    Incorporating web hosting, content management, eCommerce features, email marketing and built in customer management tools, Business Catalyst can help you accelerate your projects and increase your profit margins. Try it out for free at businesscatalyst.com. Complete the Survey

    It just takes a few minutes to complete the survey, and we really value your opinion. We’ll be using the information from our readers to make the Tuts+ network better than ever, so this is your opportunity to let us know what you’d like to see change on the sites!

    Survey Now Closed — Thank you to everyone who entered!

    Competition Rules
    • Please don’t enter more than once – if you do, none of your entries will count.
    • The winners will be picked randomly and contacted by email.
    • The competition closes in exactly one week. Any entries after that time period won’t count.
    • We’d love to hear your honest feedback, so feel free to say exactly what you think!

    Thanks for taking the time to share your thoughts about the Tuts+ network. We really appreciate it, and look forward to hearing what you have to say!


  • Permalink for 'Are TextMate and Coda Yesterday’s Editors?'

    Are TextMate and Coda Yesterday’s Editors?

    Posted: October 26th, 2011, 8:00am MDT by Jeffrey Way

    Based on the title alone, many of you might cry, “blasphemy.” TextMate particularly has been a cornerstone for Mac-based web developers for years and years. However, things change, and, recently, better editors, like Sublime Text 2, have surfaced. With TextMate 2 and Coda 2 on the near horizon, can they compete, or are they too late to the next inning? The editor wars have begun.

    Competition is Good

    Competition is always most beneficial to the consumer.

    Competition is always most beneficial to the consumer. There were the gas wars, then soda wars, and now – in our little world – editor wars.

    Okay, okay, it’s not quite as dramatic as that, but if you don’t think the creators of Coda are keeping a close eye on the beta of TextMate 2 – scheduled for release by Christmas – then you’re surely mistaken. Of course, the same is true vice versa.

    Sublime Text 2, still in beta, has quickly gathered a faithful following, including yours truly. Undoubtedly, the creators of Coda and TextMate have paid attention. After years of waiting, both Coda and TextMate are prepping their respective Version 2 Betas. We’re certainly in for exciting times.

    But the question is: are they too late?

    In Order to Switch Back…

    What would I need in order to switch back to Coda or TextMate?

    I’d love to be blown away by version two of either of these upcoming releases, and, while I think it’s a possibility, I’m still cautious. Sublime Text 2 has been executed so well (while still being in beta); it would be very tough to sway me at this point.

    All of this talk about new code editors, though, has lead me to pause and think: what would I need in order to switch back to Coda or TextMate – both of which I’ve used at different points in my career?

    1 - Multiple Cursors

    This is a requirement for me at this stage. For those unfamiliar with the idea of multiple cursors, it allows you to designate more than one cursor in your document. This is incredibly helpful. Imagine, rather than performing a search and replace to update a word, simply selecting the words, creating the necessary extra cursors, and typing away.

    2 - iCloud?

    Apple’s iCloud works amazingly well. I love downloading an iTunes song on my laptop, and seeing it immediately show up on my phone. What if the same idea could be applied to my local projects and demos?

    • I create a new demo project on my desktop.
    • This then immediately syncs to my other applicable devices.
    • When I open the editor on my laptop at home, it immediately shows up.

    Sure, this can be accomplished with something like Dropbox, but it still requires a bit of effort on my part to organize.

    The winner of the editor wars will provide the most flexibility and simplicity.

    3 - Vi Mode

    It’s not like developers prefer the aesthetics of Vim…

    Many of you laugh at those of us who depend on Vi(m). Huh? I have to type ciw to change this word? Why not just select the text with your mouse?

    Yes, yes, we get it; you prefer the mouse over the keyboard. But the bottom line is: if you put in the necessary time to learn the keybindings, I can promise you that you’ll be significantly faster when browsing and editing your files.

    There needs to be an optional command-esque mode in these editors. Certainly, it should be disabled by default, but give me the option. Think of it this way; if the editor makers themselves don’t add support, a user will create a less-than-ideal plugin. Let’s cut out the middle-man.

    It’s not like developers prefer the uglier Vim; we, too, salivate when looking at screenshots of Espresso 2. But, aesthetics aren’t enough. We need to have the option of continuing to use the shortcuts that have ingrained themselves in our fingers.

    4 - Seamless FTP Support FTP Support

    This is one that Coda got right from the start (Espresso is quite excellent as well). Give us built-in support for browsing and editing files on our servers. Many argue that it’s better to use a thirty party app, like Transmit, for this purpose. They may be right, but it sure is convenient to have that sidebar always available to you. Convenience is key. I’m amazed that more editors don’t support this functionality out of the box.

    When I speak to Coda lovers, this is the first feature they mention.

    5 - Snippet Manager

    Most editors these days offer some form of baked-in snippet manager. While I tend to use third party apps for this purpose, if done right, it makes a lot of sense to store your snippets catalog directly in your editor of choice.

    The problem is that, thus far, it hasn’t been executed well enough. TextMate works well; I can create a snippet, add multiple tab stops, and assign a shortcut quite easily. But, it still requires too much effort on my part. Give me a seamless pop-up panel, where I can create a snippet – based on the currently selected text – and assign a shortcut sequence to it in less than five seconds.

    6 - Crazy-Fast File Switching

    Sublime Text has spoiled me; quickly switching from file to file is lightning fast.

    Perhaps this one is implied, but it should never be disregarded. It’s the core reason why many developers don’t use bloated IDEs, like Aptana. I should click on the app icon, and be coding within seconds. If I need to browse to a different file, let me type a shortcut, and type the name of the file I wish to view. The quicker the better.

    7 - Code Folding

    Code folding is nothing new or special, but it’s absent in some of these editors, or not implemented well enough. I’d like to see smart code folding in place for both versions.

    8 - Terminal Cloud9

    Cloud9, a web-based editor, has a Terminal-like panel built-in, placed at the bottom of the page at all times. While most developers will likely have Terminal open while coding, it’s still something I’d like to see.

    If I need to clone a GitHub repo, let me do so right in the editor: git clone url. If I need to create three files, let me type, touch file1.html file2.thml file3.html, and be done with it.

    It’s a simple idea, but could be a tremendous help: a built-in Terminal-like panel that defaults to the working directory of the current project.

    9 - Preview Window Preview panel in Espresso

    If not built-in, most editors have a plugin that provides support for quickly previewing an HTML page. Espresso does this beautifully. Particularly for web designers, this is a vital feature to have.

    10 - Syntax Highlighting Syntax Highlighting

    Okay, this is a small one; but it’s irritating when you try a new editor, and are provided with only the base syntax highlighter theme. Why? Give me twenty options built-in. I hate wasting time, as I Google for additional themes. This is an easy one, folks.

    11 - Context-Specific Search and Replace

    My golden boy, Sublime Text, offers a nifty way to perform context-specific search and replace. This means that I can select a few paragraphs of text, and then run a search-and-replace command specifically on that selection.

    This way, I can often refrain from resorting to regular expressions to update my documents. It’s a small, but very helpful feature to have.

    12 - Split-Screen Editing Split-Screen Editing

    This is where Vim leads the pack. All on the same screen, I can be editing four different files at once. This is certainly preferred to switching from file to file. Imagine seeing your model, controller, and view file all on the same screen. In the words of Borat, “it’ssa nice!”

    This feature must be baked in for me to switch back.

    13 - Downloads

    We often begin projects by either downloading a framework, or cloning a repository from GitHub. Wouldn’t it be nice if the editor made this as easy as possible – even for those who hate the command line?

    What if, when I create a new project, it gives me the option of pasting in a url.

    • If it’s a link to a .zip file, the editor downloads the file, and unzips its contents into the current directory.
    • If it’s a GitHub link, it clones or downloads the referenced files.

    This is a common gripe, and is specifically why we made Nettuts+ Structurer.

    14 - Auto-Format

    Visual Studio provides the best auto-formatting.

    I’ve yet to find an editor that performs automatic code formatting as well as Visual Studio. Microsoft implemented that feature perfectly. Of the other editors that attempted something similar, I’ve generally found that they fall far short – almost to the point of being unusable.

    15 - Auto-Completion

    If you add too many bells and whistles, you end up with the bloated IDE that many of us try to avoid.

    Here’s the thing: if you add too many bells and whistles, you end up with the bloated IDE that many of us try to avoid. The core appeal of TextMate was that it wasn’t the kitchen sink.

    That said, if they could keep the editor as fast as possible, and still provide a nice auto-completion option, that would be huge. Espresso does this quite well when writing CSS. I’d like to see this across the board. Komodo’s implementation comes to mind.

    16 - Zen Coding Support

    I want to see Zen Coding built into the editor.

    Zen Coding is usually the first plugin I install for a code editor. This is time consuming, and requires me to research exactly how to install it.

    In the same way that Ruby on Rails provides support for the most commonly used tools and preprocessors, a code editor should do the same. I want to see Zen Coding built into the editor. While you’re at it, also provide syntax highlighting for the most popular template languages and preprocessors, like HAML, Slim, Mustache, Sass, and CoffeeScript. Don’t make me hunt these down on GitHub.

    17 - Bookmarks

    Taking another page from the Vim toolkit, bookmarks give us a way to quickly return to a specific line in our project.

    For instance, let’s say that you’re working on a particular view, but have forgotten the name of some variable that was created in your controller. In Vim, you can set a bookmark, switch over to the controller file where the variable was declared, and then instantly return to the exact line you were on in your view with a keyboard shortcut.

    I’d love to see this in the new crop of editors.

    18 - Built-in Compilers Sass

    Sometimes, it’s better to designate specific actions to third party tools and apps. At the same time, though, my decision when choosing a new code editor comes down to convenience. Which editor requires me to perform the least amount of work?

    What if, in my code editor, I could right-click on, say, a Sass file, and choose “compile.” It would then, based on my settings, create the applicable stylesheet. Or, the same thing for a CoffeeScript file.

    This way, I don’t need to bother with the command line if I’m not familiar with it, and I don’t need to use apps that are made specifically to watch and compile Sass and/or CoffeeScript files. It’s important to remember that not everyone is comfortable with the Terminal. As a result, they know nothing about build scripts, and generally stray from using these awesome preprocessors. A “right-click” solution would fix this!

    I’d love to see an editor provide support for the most common preprocessors. Maybe it’s not the job of the code editor, but it sure would provide me with more convenience. Isn’t that the goal?

    19 - Inline Error Checking

    This is a scary one; in my experiences, real-time error checking can drastically slow down an editor – and that’s not an option. Speed takes precendence over everything else.

    That said, if the creators could find a way to provide some level of error checking without sacrificing performance, that would be a huge help.

    20 - Training

    Train your users.

    Sometimes, as consumers, we’re left with the task of sorting through confusing documentation to figure out how to perform common tasks.

    I want to see a variety of screencasts on how to use the editor like a pro. Show me everything from the basics, all the way up to advanced tips and tricks. Visual training is the preference of many, yet it’s so often not provided.

    As the creator of the editor, you know better than anyone about how to use it to its fullest. Train your users.

    21 - The Holy Grail? A Smart Visual Editor

    If one of these editors could produce the pinnacle visual editor, they could change the landscape entirely.

    Wait…wait…put away the guns. I’m not advocating the use of visual editors – at least not yet. Let’s be straight: we’re not against visual editors because we’re code obsessed snobs. We’re against them because they generate terrible markup. Clean code and markup is an art; when you use a visual editor that produces the opposite of art, you should expect a lashing from your peers.

    But, what if they could get it right? Truthfully, I think this isn’t even a possibility for Coda or TextMate 2, but it’s still fun to consider. If one of these editors could produce the pinnacle visual editor, they could change the landscape entirely. Visual Studio has come the closest of everyone, but even they have fallen short. Maybe it will never happen.

    But Most Importantly…

    I want to see features that I haven’t even thought of. Nintendo continues to change the landscape of videogames by offering new ways to experience and interact with their games. I’d like to see the same from the next round of code editors. What will make my life as a developer or designer easier? What have I not thought of yet? That’s what I’m hoping to see most of all from Coda 2 and TextMate 2.


  • Permalink for 'The Best Way to Learn ASP.NET'

    The Best Way to Learn ASP.NET

    Posted: October 25th, 2011, 12:20pm MDT by Jeremy McPeak

    You’re looking to learn ASP.NET? I can’t blame you. Not only is it an extremely flexible platform, but .NET developers are in high demand and will continue to be. Unfortunately, it can be an intimidating platform to learn — especially if you are brand new to development or have never used Java or C++. However, once over the proverbial hump, you’ll find it to be a rewarding and enjoyable platform to develop for. This syllabus is designed to get you up and running on the ASP.NET stack, being able to write your own applications.

    Assignment 0: Disregard the Naysayers

    Taking a page from Siddharth’s earlier guide to learn PHP, disregard the haters. The majority of ASP.NET’s critics are kids who know nothing about the platform other than it was made by Microsoft; they haven’t spent five minutes with it to come up with any kind of informed opinion.

    While there are certainly valid criticisms of the platform, they are typically made by developers who not only know C# and the .NET Framework, but PHP, Ruby, C++, Java, and other platforms.

    ASP.NET isn’t perfect—there is no such thing. But it is one of the most flexible and powerful server-side technologies available today.

    Assignment 1: Pick a Language

    I fully recommend you pick C#.

    ASP.NET is often incorrectly thought of as a programming language; it is actually a platform built on .NET’s Common Language Runtime (CLR), the component of the .NET Framework responsible for executing .NET applications. Because of this, a .NET developer can use whatever .NET-enabled language they want to write their ASP.NET application. This means you can write an application in C#, Visual Basic.NET, Python, PHP, Perl, and many other languages. As long as there is a .NET compiler for your chosen language, you can write an ASP.NET application with it.

    Keeping that in mind, I fully recommend you pick C#. While it may be tempting to pick another language you might be more familiar with, the bulk of information, both in books and on the Web, are geared towards Microsoft’s officially supported languages: C# and VB.NET. Additionally, C# was specifically designed for the .NET Framework, and thus, is the most intuitive for using .NET’s features. This is one of the reasons why .NET is intimidating; not only do you have to learn the framework, but a new language, too. But it is well worth it in the end.

    Extra Credit
    • Visual C# 2010 Step by Step: After you pick a language, it’s a good idea to get familiar with it. If you want to dig into the C# language before getting into ASP.NET, I recommend Visual C# 2010 Step by Step. It is a very good introduction to the language, and will introduce you to many aspects of the .NET Framework as well. It’s not required reading, but you’ll have an easier time learning ASP.NET with a solid foundation in C#.
    • ASP.NET from Scratch: Nettuts+ has a semi-fast-paced series called ASP.NET from Scratch, presented by yours truly. The beginning lessons are a couple years old, but Lesson 1 and Lesson 2 give you some background of the platform as well as a brief introduction to ASP.NET. You don’t necessarily have to follow along with the examples (they use older tools which you will not want to download),  but watch the first few lessons to get an idea of what you’re getting into. The later lessons work with the MVC framework, which  you should wait on learning until a later time. The series was designed to get you up and running with ASP.NET, so it is not as comprehensive as a book might be, but that’ll be taken care of with…
    Assignment 2: Read Some Books

    Two to be exact. There is no shortage of ASP.NET books in the world, but there are bad books, good books, and excellent books. The two listed here are excellent, and I want you to read them in order.

    Nettuts image Beginning ASP.NET 4 in C# and VB

    Author: Imar Spaanjaars

    Beginning ASP.NET 4 in C# and VB starts at the very beginning by walking you through downloading and installing a free version of Visual Studio called Visual Web Developer Express. You’ll then embark on your ASP.NET journey, learning syntax, controls, themes, and other features of the platform. Just as Visual C# 2010 Step by Step gives you solid foundation in C#, Spaanjaars’ Beginning ASP.NET 4 in C# and VB gives you a solid foundation in ASP.NET fundamentals.

    Nettuts image Professional ASP.NET 4 in C# and VB

    Author: Bill Evjen, Scott Hanselman and Devin Rader

    This book dives deeper into ASP.NET to give you a more complete understanding of the platform. It will not only expand upon the topics covered in Spaanjaars’ book, but it will introduce you to other features of ASP.NET and the .NET Framework: sessions, the provider model, membership (authentication and user roles), security, state management, caching, and the list goes on. There is not much this book does not cover, and it will be an invaluable resource you can return to when you need a refresher on a particular feature or topic.

    By the time you finish these two books, you’ll have a very good understanding of the platform. So it’s time to branch out and…

    Assignment 3: Create Something

    Reading is one thing; doing is another.

    Reading is one thing; doing is another. While you undoubtedly followed along with the examples in the previous listed books, doing something on your own is one of the best ways to learn. So for this assignment, write something. Building your own blogging engine, forums, or to-do list will put what you’ve learned into practice. Start small and add more to your project as you finish a piece. Make sure you include the following features:

    • Database-Driven: It should be database driven. Use Microsoft’s SQL Server Express as your data store, and design the tables you’ll need for your application. If you’re new to designing databases, it’s typically a good idea to think of your data as logical objects. For example, a blog app could have a table called BlogPosts where the table’s fields describe blog posts (title, posting, date of post, etc). Keep it simple and logical.
    • UI: It should have a "front-end." By this, I mean the portion of the app that visitors would see; it’s the content that your project is supposed to display. If you build a blog, it’s the blog posts, archives, etc. If you’re building a forum, it’s the threads and posts contained within the forum. If it’s a to-do, list, it’s the tasks you (or other users) are to keep track of.
    • Admin: It should have a "back-end." This is the administrative portion of the project, where you maintain the blog posts, forum, or to-do list. Make sure you protect it by requiring administrators to authenticate.

    Never fear to crack open a book or ask questions on the Web. Sites like www.stackoverflow.com and forums.asp.net are valuable resources where you can ask questions and get tips from pros who have used the platform for years.

    Extra Credit

    For extra credit, add in users and roles.

    • For a blog, add the ability to have multiple authors post blog posts, and give them roles that determine what privileges they have.
    • If a forum, add the capability for users to sign-up for an account and start and add to topics. Also use roles to determine what users can and cannot do. Add moderators and super-admins for extra extra credit.
    • If a to-do list, make it multi-user capable, where users can have their own unique and private to-do list.

    Naturally, you’ll need some way to administer these users and roles, so be sure to add that capability to your "back-end."

    Assignment 4: Watch the ASP.NET from Scratch MVC Screencasts

    The WebForms technology you have been using up to this point is just one of the programming patterns you can use to create ASP.NET applications. A second programming model is ASP.NET MVC. It’s still ASP.NET but uses a different programming pattern called Model-View-Controller (MVC), and it is noticeably different than WebForms.

    To get started with the MVC Framework, watch the following ASP.NET from Scratch lessons:

    These lessons will get you up and running on the MVC path quickly.

    Assignment 5: Read Some MVC Books Nettuts image Professional ASP.NET MVC 3

    Author: Jon Galloway, Phil Haack, Brad Wilson, K. Scott Allen

    Parts of this book will be reviewed from the ASP.NET from Scratch screencasts, but it does cover other topics such as Test Driven Development (TDD), security, and extending MVC, as well as dive deeper into topics covered in the ASP.NET from Scratch videos. This is a must have resource for any ASP.NET developer wanting to grasp the MVC Framework.

    Nettuts image Pro ASP.NET MVC 3 Framework

    Author: Steven Sanderson, Adam Freeman

    Once again, there will be review material, as many topics are covered in ASP.NET from Scratch and Professional ASP.NET MVC 3, but this is an excellent resource to give you other developers’ perspective on the MVC framework.

    Assignment 6: Rewrite Something using the MVC Framework

    Just as writing something for Assignment 3 helped solidify your understanding of ASP.NET WebForms, you need to write something using the MVC Framework. When I learn a new language or pattern, I like to rewrite an existing project using my newfound knowledge. So for this assignment, rewrite the app you wrote for Assignment 3, but use the MVC Framework instead of WebForms. This rewrite should adhere to the same requirements as Assignment 3, and it has the same extra credit.

    Once again, don’t forget that you’re not alone; use your book or visit www.stackoverflow.com and forums.asp.net if you get stuck.

    Assignment 7: Follow the Masters

    Many Microsoft employees involved with ASP.NET blog and tweet regularly, but not every ASP.NET master works for Microsoft. Be sure to follow these guys and subscribe to their blogs:

    • Scott Guthrie (@scottgu, weblogs.asp.net/scottgu/) is one of the original architects of ASP.NET and offers informational tweets and blog posts on the subject (particularly new stuff).
    • Scott Hanselman (@shanselman, hanselman.com/) tweets a lot, but he provides a ton of information on .NET and technology in general.
    • Phil Haack (@haacked, haacked.com/) also works for Microsoft in the MVC team, and his information blog posts cover a wide array of ASP.NET topics. He’s also responsible for NuGet, a package management utility for Visual Studio and .NET apps.
    • ASP.NET Team (@aspnet, www.asp.net) is the ASP.NET website, featuring community spotlights, forums, and tutorials.
    Assignment 8: Keep up to Date

    Microsoft releases several Community Technical Previews (CTP) before every major release.

    Computer technology is a fast-paced industry, and ASP.NET is no exception. Since its release in 2002, ASP.NET has gone through five major versions (and one point release), with a new version coming in 2012, and ASP.NET MVC has seen three versions since its 2009 release. Things move rather quickly, and keeping up with the changes and improvements of new versions are a necessity.

    Thankfully, it is relatively easy to stay current with ASP.NET. Microsoft releases several Community Technical Previews (CTP) before every major release. Not only do you get to play with the new features in the upcoming version, but you have documentation, including a thorough "what’s new/changed", with every CTP release.

    Conclusion

    This lesson plan will get you on the road to ASP.NET goodness. It’s a fantastic platform, and it gets better with every new version and point release. If you have any questions, feel free to ask them in the comments or tweet me. If you have anything to add, please share it with the rest of us in the comments. Thanks, and I hope you enjoy ASP.NET!


  • Permalink for 'Enhancing Web Apps with AmplifyJS'

    Enhancing Web Apps with AmplifyJS

    Posted: October 24th, 2011, 7:57pm MDT by Andrew Burgess

    There seems to be a new crop of special-purpose JavaScript libraries every week. Gone, it seems, are the days of using only one library per project. Today I’ll introduce you to a very cool component library, AmplifyJS, that offers just a few very specialized components.

    Devs, Meet AmplifyJS

    According to the website:

    AmplifyJS is a set of components designed to solve common web application problems.

    Sounds prestigious, but what’s actually in this library?

    AmplifyJS has three main pieces:

    • An AJAX API
    • A PubSub Event System
    • A Client-side Storage API

    Join me now for a tour of the incredible AmplifyJS library! We’re going to build a super-simple employee tracker; really, it’s just a table with a few app-like features, courtesy (partly) of AmplifyJS.

    We don’t really need to concern ourselves with styling and layout issues today so I’m going to use the Twitter Bootstrap library. It’s incredibly simple: just include the link to the CSS file—which they let you hotlink from Github—and you’re in business.

    Step 1: Setting it Up

    So, make yourself a project directory. Start with the index.html file, and a js folder. Now, head over to the AmplifyJS website and click that huge, red “download” button. Once, you’ve got the library zip, extract it, and move it into the js folder. We’re going to need a few other things as well:

    • jQuery: Amplify’s AJAX component uses jQuery’s AJAX feature underneath it’s API, at least by default. But we’ll be using jQuery for other stuff, so bring it on in.
    • bootstrap-modal.js: The Twitter Bootstrap library includes a few scripts for getting all interactive. And we’re going to use one: the modal window jQuery plugin. Download it, and add it to that js folder.
    • There are two other scripts that I’ll mention along the way, but these we’ll write ourselves.

    Then, start off our index.html file like this:

    <!DOCTYPE HTML>
    <html>
      <head>
        <title>AmplifyJS</title>
        <link rel='stylesheet' href='http://twitter.github.com/bootstrap/1.3.0/bootstrap.min.css' />
      </head>
      <body>
        <div class='container'>
          <div class='row'>
            <div class='span16' id='alert-area'>
            </div>
          </div>
          <div class='row'>
            <div class='span4'>
                <h2>Commands</h2>
            </div>
            <div class='span12'>
            	<h1>Employees</h1>
            </div>
          </div>
        </div>
        <script src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js'></script>
        <script src='js/amplify/amplify.min.js'></script>
        <script src='js/bootstrap-modal.js'></script>
      </body>
    </html>

    If you aren’t familiar with using Twitter Bootstrap, you’ll see it’s no sweat to use. We’ve got a container that is 940px wide. Then, we have two rows. The first has one column, that covers all 16 columns. The other has two columns: one is 4 columns wide, and one is 12 columns wide.

    One more thing, before we get to some real coding: we’re going to pop up a modal window that allows up to input employees. Under the <div class='container'>, add this modal window HTML. Yes, it seems like a lot code, but it’s mainly Bootstrap stuff:

    <div id='add-employee-modal' class='modal fade'>
      <div class='modal-header'>
        <a href='#' class='close'>x</a>
        <h3>Add an Employee</h3>
      </div>
      <div class='modal-body'>
        <form id='employee-form'>
          <div class='clearfix'>
            <label for='firstName'>First Name:</label>
            <div class='input'><input type='text' name='firstName' placeholder='John' /></div>
          </div>
          <div class='clearfix'>
            <label for='lastName'>Last Name:</label>
            <div class='input'><input type='text' name='lastName' placeholder='Doe' /></div>
          </div>
          <div class='clearfix'>
            <label for='role'>First Name:</label>
            <div class='input'><input type='text' name='role' placeholder='Designer' /></div>
          </div>
        </form>
      </div>
      <div class='modal-footer'>
        <button id='create-employee' class='btn primary'>Add</button>
      </div>
    </div>

    All right, we’re ready to go! Let’s code.

    Step 2: Wiring the Modal Window

    Open up a script tag at the bottom of index.html (I’m just doing this inline, but feel to put it in a new JS file). start this way:

    	(function () {
    		var employeeModal = $('#add-employee-modal').modal({ backdrop: 'static' });
    
    	}());

    We’re using the Bootstrap modal plugin here; this just “instantiates” the modal window. Now, we want the window to appear when we click the “Add Employee” button. Of course, we’ll have to add the button first: put this in the <div class='span4'>, right under the <h2>.

    	<p><button id='add-employee' data-controls-modal='add-employee-modal' class='btn'>Add Employee</button></p>

    That data-controls-modal='add-employee-modal' attribute will display the modal with said ID when the button is clicked.

    So, the user will need to fill in the form, click the “Add” button which has an id of create-employee. So, let’s wire up a click event handler for the button:

    $('#create-employee').click(function () {
        var form = $('#employee-form');
        employeeModal.modal('hide');
        EMPLOYEE.create(
            form.find('[name=firstName]').val(),
            form.find('[name=lastName]').val(),
            form.find('[name=role]').val()
        );
        form.find('input').val('');
    });

    We get the form, and then hide the modal window. Then, we’re going to call an EMPLOYEE.create method, passing the first name, last name, and role as the three parameters. Finally, we clear the form.

    amplify.publish

    But wait, you say, what’s EMPLOYEE.create? Well, it’s a micro-“class” that I’ve put in js/employee.js. Check it out:

    var EMPLOYEE = {
        create : function (firstName, lastName, role) {
           var employee = {
                firstName: firstName,
                lastName: lastName,
                role: role,
                dateEmployed: new Date()
           };
           amplify.publish('employee-created', employee );
           return employee;
        }
    };

    You’ll want to throw a script tag for it up with the others.

    Pretty simple, right? We just create an object literal with our parameters, and add a dateEmployed property. But, then—and finally!—we have the first entrance of the AmplifyJS framework. Here, we’re using the pub/sub events component. This is great for doing loose coupling between parts of your app.

    This method doesn’t have to know if another part of our code wants to do something with each new employee we create; Our “Add” button event handler doesn’t have to worry about it. We’ll just publish it as an “employee-created” event for any part that is interested to take. We pass our new employee object as data for anyone interested. Then, we return the employee object (even though we don’t keep track of it in our event handler).

    Step 3: Reacting with amplify.subscribe

    So, is any other part of our app interested in the “employee-created”? Yes, in fact. We want to do two things. First, add this employee to a table on our page. Second, we want to store the employee in localStorage. Here’s the first part of that:

      amplify.subscribe('employee-created', function (employee) {
        employeeTable.add([employee.firstName, employee.lastName, employee.role, employee.dateEmployed]);
        newAlert('success', 'New Employee Added');
      });

    To subscribe to an event, we call amplify.subscribe. We want subscribe to the “employee-created”; when that events occurs, we want to add it to the employeeTable; notice that instead of just passing it the employee object, we “convert” it to an array; this is because we need to be sure the elements will be in the right order. Then, we want to display an message, letting our user know that the employee was added successfully.

    What’s up with this employeeTable variable? Well, first, we have to add the <table> to our document. So, underneath our “Employees” <h1>, add this:

    <table id='employee-table' class='zebra-striped'>
        <thead>
            <tr>
                <th> First Name </th>
                <th> Last Name </th>
                <th> Role </th>
                <th> Date Employed </th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>

    Now, we have to capture this table as a variable up in our var statement at the top:

    employeeTable = TABLE.create($('#employee-table')),

    And TABLE? That’s the last piece of JS for this puzzle. Put this in js/table.js and don’t forget the script tag:

    var TABLE = {
        proto : {
            init : function (el) {
                this.element = $(el).find('tbody');
            },
            add: function (arr) {
                var row = $('<tr>').html(function () {
                    return $.map(arr, function (value) {
                        return '<td>' + value + '</td>';
                    }).join('');
                });
                this.element.append(row);
            },
            load: function (rows, order) {
                for (var i = 0; rows[i]; i++ ) {
                    this.add(rows[i]);
                }
                var fields = [];
                for (var j = 0; order[j]; j++) {
                    fields.push(rows[i][order[j]]);
                }
                    this.add(fields);
            },
            clear: function () {
                this.element.empty();
            }
        },
        create : function (el) {
            var table = Object.create(this.proto);
            table.init(el);
            return table;
        }
    };

    It’s a bit complicated, but you should have no problem grokking it. We’ve got a proto property that is the prototype for our table instances. Then, when we call create, we use Object.create to create an object that inherits from this.proto. After that, we call the init method to set any properties. Finally, we return the table instance.

    This micro-API makes it easy for us to work with our table. You should be able to see how passing an array to the add method will add a row to our table. Notice also that we can pass an array of rows to load and fill the table up; we’ll use this soon.

    Oh, then there’s the newAlert method we called:

    function newAlert (type, message) {
        $('#alert-area').append($('<div class='alert-message ' + type + ' fade in' data-alert><p> ' + message + ' </p></div>'));
    
        setTimeout(function () {
            $('.alert-message').fadeOut('slow', function () { this.parentNode.removeChild(this); });
        }, 2000);
    }

    As you can see, this just simply adds a div inside out <div id='alert-area'>; the new div takes advantage of the Twitter Bootstrap alert styling; after two seconds, we fade the alert out and remove it.

    amplify.store

    But that’s not the only think we want to do when the “employee-created” event occurs:

    employeeStore = amplify.store('employees') || [];

    At the top, with our two other variables, make the third and final one: employeeStore. If amplify.store('employees') returns something, we’ll use that; otherwise, we’ll use an empty array.

    amplify.subscribe('employee-created', function (employee) {
        employeeStore.push(employee);
        amplify.store('employees', employeeStore);
    });

    Now we’re using the storage component of AmplifyJS. It really couldn’t be simpler: to store a value, pass amplify.store a key and the value. To retrieve the value, hand it the key. Underneath, AmplifyJS is storing that key and value in whatever storage type is available on that browser.

    So here, we add a new employee to the array and store the array in the “employees” key. I should note that since we’re storing an array, AmplifyJS is using JSON serialization to convert that array to a string. Therefore, if you’re trying to support browsers without native JSON support (IE 5 and down, Firefox 3 and down), you’ll want to include the json2.js library.

    Step 4: Saving to the Server (with amplify.request)

    In our little app-example, we’re saying that by default, the data you put into the app is kept only on your computer (in that one browser). However, if the user wants, we’ll allow them to put it up on the server (hypothetically, this is private information they might not want to share; however, if they want to access it from other devices, they could do this.).

    We’ll start by adding a button for uploading the data.

    <p><button id='push-data' class='btn'>Push Data to Server</button></p>

    Now, of course, your brilliant minds have already figured out that we’ll be using AmplifyJS’s AJAX component. amplify.request is an incredibly flexible API, and we won’t be looking at everything it can do. However, you’ll get a good feel for how it works here.

    Doing AJAX with AmplifyJS is a bit different than with other libraries: the idea is that first you define a connection to the server; then, you can use that connection any number of times after that. Let’s begin by defining a connection, called a “resource” by AmplifyJS:

    amplify.request.define('pushData', 'ajax', {
        url: 'data.php',
        type: 'POST'
    });

    The first parameter here is resourceId, which we’re setting as “pushData”; this is how we’ll refer to our connection when we’re using it. The second parameter is the request type; in this case, “ajax.” This is the only request type built into AmplifyJS; you can add your own, but this is suitable for our needs today.

    Finally, we have an options object. According to the documentation, your settings options are anything you would set in jQuery.ajax, as well as cache (which allows you to set up a custom memory cache) and decoder (for parsing the AJAX response). In our case, only two options are necessary: the url, and the type of request we’re making.

    Of course, we’ll need some simple PHP on the back end; make sure the data folder is writable.

    data.php
     <?php
       $employees = json_encode($_POST['employees']);
       $file      = fopen('data/data.json','w+');
       fwrite($file, $employees);
       fclose($file);
    
       echo 'success';
    ?>

    Now, how about using the connection, the resource, we’ve defined? Well, let’s do this in a click handler for that <button id='push-data'>:

    $('#push-data').click(function () {
        amplify.request('pushData', { employees: amplify.store('employees') }, function (data) {
            amplify.publish('data-pushed', data);
        });
    });

    When using the resource, the first parameter is the resource ID; it’s the same resource ID we have the resource we defined, so AmplifyJS knows which to use. Second, we pass data hash. In this case, we pass the content in our store, under the key “employees.” The final parameter is a function that’s called when we get a response.

    Once we get a response, we’ll publish the “data-pushed” event. Then, we’ll just alert the user that it worked:

    amplify.subscribe('data-pushed', function () {
        newAlert('success', 'Data successfully sent to server');
    });
    Taking it a Step Further

    Well, that’s our little example app. We’ve looked at using all three of AmplifyJS components: amplify.publish / amplify.subscribe, amplify.store, and amplify.request. We’ve covered pretty much all there is to know about the pubsub and store parts (there is a bit more!), but there’s a lot more you can do with the request API. So, go check out the website to learn more!

    So, what are your thoughts on AmplifyJS? Like it? Find it too redundant? Let’s hear it in the comments!


  • Permalink for 'The Increasing Importance of APIs in Web Development'

    The Increasing Importance of APIs in Web Development

    Posted: October 21st, 2011, 12:34pm MDT by Janet Wagner

    Web APIs have experienced an exponential increase in popularity and usage in the past few years. These days, they’re an important tool for web developers; however, they are also even becoming an effective marketing tool for many types of businesses. This article covers Web API statistics, their benefits, and a list of some of the most useful APIs currently available.

    What is an API?

    All of the Charts in this post are powered by the Google Charts API!

    An API, or “Application Program Interface”, is a set of routines and protocols that provide building blocks for computer programmers and web developers to build software applications. In the past, APIs were largely associated with computer operating systems and desktop applications. In recent years though, we have seen the emergence of Web APIs (Web Services).

    Web API (Web Service)

    Web APIs allow developers to build web pages and web based applications (known as “mashups”) using data from multiple online sources. Although there are Web APIs available for many different types of industries, some of the most popular and widely used ones are in the categories of social networking, mapping, shopping and music.

    Increase in Popularity and Usage of Web APIs
    • In the Summer of 2005, ProgrammableWeb, one of the largest online API directories and resources, had only thirty-two APIs listed in their directory.
    • On March 8th, 2011, they announced that they had reached a major milestone: the 3,000th Web API had been added.
    • On October 3rd, 2011, ProgrammableWeb announced another major milestone, their API directory now listed 4,000 Web APIs. The news came only six months after they had reached the 3,000th milestone.
    Popular Web APIs

    Social media APIs have seen an incredible increase in usage in recent years.

    Among the most popular Web APIs are those related to social media. Social media APIs have seen an incredible increase in usage in recent years, which can be directly linked to the rise of the companies Twitter and Facebook.

    Google has also recently introduced its own Social Networking Platform Google+, and, in September 2011, they released the Google+ API. The API is currently read-only and only supports public data; however, this may change in the future.

    Web API Protocols

    REST (Representational State Transfer) is widely considered the standard protocol for web APIs. Other protocols used for Web APIs include Soap and JavaScript.

    Web API Data Formats

    By far the most popular data format for Web APIs is XML, although JSON has been growing steadily in popularity and usage. Many developers prefer the JSON format for a number of reasons:

    • Data can be read without a complex parser for most modern programming languages
    • Parsers for JSON exist in nearly every programming language
    • JSON parsers are fast, small and not complicated.
    • JSON output is much smaller than XML because JSON does not include namespaces, attributes, etc like XML does

    Many API providers offer both XML and JSON data formats. However, JSON has become so popular among web developers to the point that some providers offer the JSON data format exclusively.

    A few examples of “JSON only” Web APIs include Twitter’s Streaming API, the StackExchange API and Foursquare’s APIv2. Foursquare states on their API page that one of the reasons the data is only available in JSON format is because “behind the scenes, it allows us to significantly improve performance.”

    Benefits of Web APIs

    Although the target audience for for a web API is usually the web development community, they can also be beneficial to end users as well as the API providers themselves.

    • Web Developers: Web APIs allow advanced functionality and features to be integrated into the websites that they create. There is also greater customization and flexibility with Web APIs than standard “copy and paste” widgets.
    • End Users: A good Web API can help increase the usefulness of a website and make the site interactive and more enjoyable.
    • API Providers: A well built API that is widely used by the web development community can be a powerful marketing tool because it can:

      • Help build brand loyalty
      • Increase interest in the company’s products and services
      • Increase website traffic
      • Provide useful tools to consumers
      • Convey company messaging.
    List of Useful Web APIs

    There are thousands of Web APIs available, so this is not a comprehensive list. In addition, not all APIs are useful or practical for the average Web Developer.

    At the time of this writing, all of the APIs in this list are free to use, provided that you follow the API’s terms of service. Please note that some of the APIs available at Google, Yahoo!, etc are not free and have fees associated with their usage.

    This is not a comprehensive list, but a list of Web APIs that could be useful to most web developers.

    Amazon Product Advertising API

    The Amazon Product Advertising API allows developers to access and display Amazon’s catalog of products in web based applications and web pages. Also, developers can earn income through Amazon’s Affiliate Program using the API.

    Bing API

    At this time, Bing offers two APIs that can be used to add Bing Search and/or Bing Maps functionality to your website or application.

    Envato Marketplace API

    You can use the Envato Marketplace API to access and display Marketplace data including new files, popular files, item details and much more.

    Facebook

    Facebook offers social plugins that display Facebook posts and “Like” buttons to your website. Facebook offers several APIs including
    Internationalization, Ads and Chat.

    Google Chart Tools and API

    With Google Chart Tools (used to create the graphs in this post), you can create many different sorts of charts to display your data, including (but not limited to):

    Google Feed API

    The Google Feed API makes it possible to mash up public Atom, RSS or Media RSS feeds using only JavaScript. You can then integrate and display feeds on your website.

    Google Maps API Family

    Google offers a group of Map related APIs that allow you to add maps functionality to your website. There are a variety of map functions and features that you can add to your web pages including:

    Google Libraries API

    This is a content distribution network for the most popular and widely used JavaScript libraries, which includes (but is not limited to):

    • Dojo
    • jQuery
    • jQuery UI
    • Mootools
    • Prototype
    • SWFObject
    Google+ Platform API

    This is the API for the Google+ Social Networking Platform. It allows you to add Google+ features to your website or application. Currently, this API is read-only, and can only access public data.

    All Google APIs and Tools

    Google offers a wide range of tools and APIs that allow you to add advanced functionality to your websites. You can view the complete list here.

    Note: APIs offered in Google Code Labs are experimental. Some of these APIs may remain in Google Code Labs permanently, may graduate and receive long term support by Google, or may even be shut down at some point in the future. If you are looking for APIs that Google intends to support for the long term, then it is best to choose APIs that have graduated from Google Code Labs.

    LinkedIn API

    LinkedIn provides their APIs in two different protocol formats: JavaScript and REST. You can use the LinkedIn APIs to display detailed company information, jobs information by company or industry and more.

    StackExchange API

    The StackExchange API responses are currently only available in JSON format. You can use this API to display questions, answers, comments and more from any of the StackExchange websites.

    Twitter API

    Twitter provides an API for nearly every feature available on the official Twitter website. The Twitter API can be used to create applications, websites and widgets that interact with Twitter. You can also use the API to display your latest Twitter posts, public Twitter lists, and much more.

    YouTube API

    YouTube offers several APIs and tools to integrate YouTube functionality into your website including the Data API and Player APIs. The Player APIs are especially useful as they allow you to control the look and feel of YouTube videos displayed on your website.

    YUI Charts

    The YUI Charts API allows you to add combinations of line, column, pie, bar and other types of charts to your web pages. The API uses SVG, HTML Canvas and VML to render the graphical elements of the charts.

    API Testing Tools

    Google has hundreds of APIs that you can experiment with in their Code Playground. The Apigee Console lets you test a number of different APIs including Twitter, Facebook, LinkedIn, Foursquare, Twilio and more.

    Conclusion

    Companies like Twitter, Facebook and Google have been fueling the rising popularity of Web APIs. These companies use web APIs to make their products and services more popular and create a loyal fan base. As more and more businesses and web developers discover the potential benefits of Web APIs, the popularity and usage of Web APIs will continue to skyrocket for the long term!

    References / Citations

    Live Charts Data

    ProgrammableWeb

    Wikipedia

    Webopedia

    google.load("visualization", "1", {packages:["corechart"]}); google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(); data.addColumn('string', 'API Name'); data.addColumn('number', 'Mashups Number'); data.addRows(8); data.setValue(0, 0, 'Social'); data.setValue(0, 1, 264); data.setValue(1, 0, 'Shopping'); data.setValue(1, 1, 173); data.setValue(2, 0, 'Mapping'); data.setValue(2, 1, 171); data.setValue(3, 0, 'Telephony'); data.setValue(3, 1, 159); data.setValue(4, 0, 'Music'); data.setValue(4, 1, 122); data.setValue(5, 0, 'Search'); data.setValue(5, 1, 121); data.setValue(6, 0, 'Photos'); data.setValue(6, 1, 113); data.setValue(7, 0, 'Video'); data.setValue(7, 1, 113); var chart = new google.visualization.PieChart(document.getElementById('chart_div_1')); chart.draw(data, {width: 590, height: 370, backgroundColor: 'white', fontSize: '18', title: 'Popular Web API Categories'}); } google.load("visualization", "1", {packages:["corechart"]}); google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(); data.addColumn('string', 'Year'); data.addColumn('number', 'Number of APIs'); data.addRows(5); data.setValue(0, 0, 'Jun 2005'); data.setValue(0, 1, 32); data.setValue(1, 0, 'Nov 2008'); data.setValue(1, 1, 1000); data.setValue(2, 0, 'Jul 2010'); data.setValue(2, 1, 2000); data.setValue(3, 0, 'Mar 2011'); data.setValue(3, 1, 3000); data.setValue(4, 0, 'Oct 2011'); data.setValue(4, 1, 4000); var chart = new google.visualization.ColumnChart(document.getElementById('chart_div_2')); chart.draw(data, {width: 590, height: 350, backgroundColor: 'white', fontSize: '18', title: 'Total APIs Over Time - ProgrammableWeb'}); } google.load("visualization", "1", {packages:["corechart"]}); google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(); data.addColumn('string', 'API Name'); data.addColumn('number', 'Mashups Number'); data.addRows(10); data.setValue(0, 0, 'Google Maps'); data.setValue(0, 1, 2279); data.setValue(1, 0, 'Twitter'); data.setValue(1, 1, 631); data.setValue(2, 0, 'YouTube'); data.setValue(2, 1, 586); data.setValue(3, 0, 'Flickr'); data.setValue(3, 1, 584); data.setValue(4, 0, 'Amazon'); data.setValue(4, 1, 396); data.setValue(5, 0, 'Twilio'); data.setValue(5, 1, 307); data.setValue(6, 0, 'Facebook'); data.setValue(6, 1, 303); data.setValue(7, 0, 'eBay'); data.setValue(7, 1, 213); data.setValue(8, 0, 'Last.fm'); data.setValue(8, 1, 202); data.setValue(9, 0, 'Google Search'); data.setValue(9, 1, 175); var chart = new google.visualization.PieChart(document.getElementById('chart_div_3')); chart.draw(data, {width: 598, height: 300, backgroundColor: 'white', fontSize: '16', title: 'Top 10 Most Popular Web APIs'}); } google.load("visualization", "1", {packages:["corechart"]}); google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(); data.addColumn('string', 'Protocol'); data.addColumn('number', 'APIs Number'); data.addRows(4); data.setValue(0, 0, 'REST'); data.setValue(0, 1, 2839); data.setValue(1, 0, 'SOAP'); data.setValue(1, 1, 663); data.setValue(2, 0, 'JavaScript'); data.setValue(2, 1, 261); data.setValue(3, 0, 'XML-RPC'); data.setValue(3, 1, 134); var chart = new google.visualization.PieChart(document.getElementById('chart_div_4')); chart.draw(data, {width: 590, height: 350, backgroundColor: 'white', fontSize: '18', title: 'Protocol Usage by Web APIs'}); }
    google.load("visualization", "1", {packages:["corechart"]}); google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(); data.addColumn('string', 'Data Formats'); data.addColumn('number', 'APIs Number'); data.addRows(7); data.setValue(0, 0, 'XML'); data.setValue(0, 1, 2629); data.setValue(1, 0, 'JSON'); data.setValue(1, 1, 1723); data.setValue(2, 0, 'RSS'); data.setValue(2, 1, 156); data.setValue(3, 0, 'HTML'); data.setValue(3, 1, 106); data.setValue(4, 0, 'PHP'); data.setValue(4, 1, 100); data.setValue(5, 0, 'Text'); data.setValue(5, 1, 57); data.setValue(6, 0, 'CSV'); data.setValue(6, 1, 87); var chart = new google.visualization.PieChart(document.getElementById('chart_div_5')); chart.draw(data, {width: 590, height: 350, backgroundColor: 'white', fontSize: '18', title: 'Popular Data Formats by Web APIs'}); }


  • Permalink for 'Nettuts+ Quiz #6: How Well do you Know HTML5?'

    Nettuts+ Quiz #6: How Well do you Know HTML5?

    Posted: October 20th, 2011, 9:00am MDT by Siddharth

    HTML5 has been the buzzword with the web development community for a while now. In accordance with many a request from our readers, today I’m happy to present you with a quiz on HTML5.

    This beginner friendly Stormtrooper edition is a great place to test your knowledge of the basics of HTML5. Don’t get too cocky though! The upcoming ones will make you cry! Use the force, Luke!



    $(document).ready(function(){ $('#quiz-container').jquizzy({ questions: init.questions, resultComments: init.resultComments, twitterStatus: 'Woo! I scored {score} on the Nettuts HTML5 quiz. Give it a shot!', twitterImage: 'http://d2o0t5hpnwv4c1.cloudfront.net/jquizzy-1.0/img/share.png', twitterUsername: 'envatowebdev', splashImage: 'http://d2o0t5hpnwv4c1.cloudfront.net/1068_quiz6/nettuts.png', }); });


  • Permalink for 'Marketplaces Exceed 1,000,000 Members: Infographic!'

    Marketplaces Exceed 1,000,000 Members: Infographic!

    Posted: October 20th, 2011, 4:13am MDT by Jordan McNamara

    Hey folks! I’m Jordan McNamara, the Community Manager for Envato and I wanted to share some exciting news with you about the Envato Marketplaces.

    The 12th of September was an exciting day for me as a member of our thriving Marketplace community. I along with everyone here at Envato HQ watched eagerly as the global Marketplace member count steadily grew higher and higher and higher…

    We were close, very close to the 1,000,000 member milestone. With every page refresh the count grew higher and I began to reflect on just how staggering having 1,000,000 members really is and on just what a fantastic community everyone has helped to build here.

    I remember starting at Envato in 2009 and being blown away by the 250,000 or so accounts that were registered at the time. I bragged to all of my friends “Can you believe there’s a quarter of a million members!?”. Little did I know in just under two and a half years I would be writing this post!

    View the Infographic!

    To celebrate this exciting occasion we wanted to do something interesting and fun that celebrates the Marketplace community and the sites themselves. So with that in mind, we are proud to present the 1,000,000 Members Infographic! We’ve packed it full of fascinating facts and data about our members and our nine Marketplaces.

    Click to Jump to the Infographic!

    Every day we continue to be amazed at the astonishing speed our community of creative members grows. We’ve enjoyed every minute of the journey and are proud and thankful of the achievements our members have made. Here’s to the next million!

    View the Infographic!


  • Permalink for 'The Magic of WordPress Custom Post Types: New on Premium'

    The Magic of WordPress Custom Post Types: New on Premium

    Posted: October 19th, 2011, 1:14pm MDT by Jeffrey Way

    In this in depth Premium video tutorial, I’ll teach you how to use custom post types, taxonomies, and meta boxes to extend your WordPress application into CMS-like territory.

    Become a Premium member to read this tutorial/screencast, as well as hundreds of other advanced tutorials and screencasts from the Tuts+ network.

    You’ll Learn About…
    • What are custom post types, and why would you want to use them?
    • How to take advantage of custom taxonomies to provide additional grouping and filtering functionality
    • How to use custom meta boxes to save and display custom meta information for a specific post type.
    • Implement nonces to provide additional security.
    • New PHP 5.3 features, such as anonymous functions and closures.
    • Plenty more…

    Become a Premium member to read this tutorial/screencast, as well as hundreds of other advanced tutorials and screencasts from the Tuts+ network. For more WordPress tutorials every day, be sure to subscribe to our sister-site, WPtuts+!


  • Permalink for 'Stop Nesting Functions! (But Not All of Them)'

    Stop Nesting Functions! (But Not All of Them)

    Posted: October 18th, 2011, 10:11pm MDT by Jeremy McPeak

    JavaScript is over fifteen years old; nevertheless, the language is still misunderstood by what is perhaps the majority of developers and designers using the language. One of the most powerful, yet misunderstood, aspects of JavaScript are functions. While terribly vital to JavaScript, their misuse can introduce inefficiency and hinder an application’s performance.

    Prefer a Video Tutorial? Performance is Important

    In the Web’s infancy, performance wasn’t very important.

    In the Web’s infancy, performance wasn’t very important. From the 56K (or worse) dial-up connections to an end-user’s 133MHz Pentium computer with 8MB of RAM, the Web was expected to be slow (although that didn’t stop everyone from complaining about it). It was for this reason JavaScript was created to begin with, to offload simple processing, such as form validation, to the browser—making certain tasks easier and quicker for the end-user. Instead of filling out a form, clicking submit, and waiting at least thirty seconds to be told you entered incorrect data in a field, JavaScript enabled Web authors to validate your input and alert you to any errors prior to the form’s submission.

    Fast forward to today. End users enjoy multi-core & multi-GHz computers, an abundance of RAM, and fast connection speeds. JavaScript is no longer relegated to menial form validation, but it can process large amounts of data, change any part of a page on the fly, send and receive data from the server, and add interactivity to an otherwise static page—all in the name of enhancing the user’s experience. It’s a pattern quite well known throughout the computer industry: a growing amount of system resources enable developers to write more sophisticated and resource dependent operating systems and software. But even with this abundant and ever growing amount of resources, developers must be mindful of the amount of resources their app consumes—especially on the web.

    Today’s JavaScript engines are light-years ahead of the engines of ten years ago, but they do not optimize everything. What they don’t optimize is left to developers.

    There is also a whole new set of web-enabled devices, smart phones and tablets, running on a limited set of resources. Their trimmed down operating systems and apps are certainly a hit, but the major mobile OS vendors (and even desktop OS vendors) are looking towards Web technologies as their developer platform of choice, pushing JavaScript developers to ensure their code is efficient and performant.

    A poor performing application will trash a good experience.

    Most importantly, the user’s experience depends on good performance. Pretty and natural UIs certainly add to a user’s experience, but a poor performing application will trash a good experience. If users do not want to use your software, then what is the point of writing it? So, it is absolutely vital that, in this day and age of Web-centric development, JavaScript developers write the best code possible.

    So what does all this have to do with functions?

    Where you define your functions has an impact on your application’s performance.

    There are many JavaScript anti-patterns, but one involving functions has become somewhat popular—especially in the crowd that strives to coerce JavaScript to emulate features in other languages (features like privacy). It is nesting functions in other functions, and if done incorrectly, it can have an adverse affect on your application.

    It’s important to note that this anti-pattern does not apply to all instances of nested functions, but it is typically defined by two characteristics. First, the creation of the function in question is usually deferred—meaning that the nested function is not created by the JavaScript engine at load-time. That in and of itself isn’t a bad thing, but it’s the second characteristic that hinders performance: the nested function is repeatedly created due to repeated calls to the outer function. So while it may be easy to say "all nested functions are bad," that is certainly not the case, and you will be able to identify problematic nested functions and fix them to speed up your application.

    Nesting Functions in Normal Functions

    The first example of this anti-pattern is nesting a function inside a normal function. Here is an oversimplified example:

    function foo(a, b) {
        function bar() {
            return a + b;
        }
    
        return bar();
    }
    
    foo(1, 2);

    You may not write this exact code, but it’s important to recognize the pattern. An outer function, foo(), contains an inner function, bar(), and calls that inner function to do work. Many developers forget that functions are values in JavaScript. When you declare a function in your code, the JavaScript engine creates a corresponding function object—a value that can be assigned to a variable or passed to another function. The act of creating a function object resembles that of any other type of value; the JavaScript engine doesn’t create it until it needs to. So in the case of the above code, the JavaScript engine doesn’t create the inner bar() function until foo() executes. When foo() exits, the bar() function object is destroyed.

    The fact that foo() has a name implies it will be called multiple times throughout the application. While one execution of foo() would be considered OK, subsequent calls cause unnecessary work for the JavaScript engine because it has to recreate a bar() function object for every foo() execution. So, if you call foo() 100 times in an application, the JavaScript engine has to create and destroy 100 bar() function objects. Big deal, right? The engine has to create other local variables within a function every time it’s called, so why care about functions?

    Unlike other types of values, functions typically don’t change; a function is created to perform a specific task. So it doesn’t make much sense to waste CPU cycles recreating a somewhat static value over and over again.

    Ideally, the bar() function object in this example should only be created once, and that’s easy to achieve—although naturally, more complex functions may require extensive refactoring. The idea is to move the bar() declaration outside of foo() so that the function object is only created once, like this:

    function foo(a, b) {
        return bar(a, b);
    }
    
    function bar(a, b) {
        return a + b;
    }
    
    foo(1, 2);

    Notice that the new bar() function isn’t exactly as it was inside of foo(). Because the old bar() function used the a and b parameters in foo(), the new version needed refactoring to accept those arguments in order to do its work.

    Depending upon the browser, this optimized code is anywhere from 10% to 99% faster than the nested version. You can view and run the test for yourself at jsperf.com/nested-named-functions. Do keep in mind the simplicity of this example. A 10% (at the lowest end of the performance spectrum) performance gain doesn’t seem like a lot, but it would be higher as more nested and complex functions are involved.

    To perhaps confuse the issue, wrap this code in an anonymous, self-executing function, like this:

    (function() {
    
    function foo(a, b) {
        return bar(a, b);
    }
    
    function bar(a, b) {
        return a + b;
    }
    
    foo(1, 2);
    
    }());

    Wrapping code in an anonymous function is a common pattern, and at first glance it might appear this code replicates the aforementioned performance issue by wrapping the optimized code in an anonymous function. While there is a slight performance hit by executing the anonymous function, this code is perfectly acceptable. The self-executing function serves only to contain and protect the foo() and bar() functions, but more importantly, the anonymous function executes only once—thus the inner foo() and bar() functions are created only once. However, there are some cases where anonymous functions are just as (or more so) problematic as named functions.

    Anonymous Functions

    As far as this topic of performance is concerned, anonymous functions have the potential to be more dangerous than named functions.

    It’s not the anonymity of the function that is dangerous, but it’s how developers use them. It’s quite common to use anonymous functions when setting up event handlers, callback functions, or iterator functions. For example, the following code assigns a click event listener on the document:

    document.addEventListener("click", function(evt) {
        alert("You clicked the page.");
    });

    Here, an anonymous function is passed to the addEventListener() method to wire-up the click event on the document; so, the function executes every time the user clicks anywhere on the page. To demonstrate another common use of anonymous functions, consider this example that uses the jQuery library to select all <a /> elements in the document and iterate over them with the each() method:

    $("a").each(function(index) {
        this.style.color = "red";
    });

    In this code, the anonymous function passed to the jQuery object’s each() method executes for each <a /> element found in the document. Unlike named functions, where they are implied to be repeatedly called, the repeated execution of a large number of anonymous functions are rather explicit. It is imperative, for performance sake, that they are efficient and optimized. Take a look at the follow (yet again oversimplified) jQuery plugin:

    $.fn.myPlugin = function(options) {
    
        return this.each(function() {
            var $this = $(this);
    
            function changeColor() {
                $this.css({color : options.color});
            } 
    
            changeColor();
        });
    };

    This code defines an extremely simple plugin called myPlugin; it’s so simple that many common plugin traits are absent. Normally, plugin definitions are wrapped inside self-executing anonymous functions, and usually default values are supplied for options to ensure valid data is available to use. These things have been removed for the sake of clarity.

    This plugin’s purpose is to change the selected elements’ color to whatever is specified in the options object passed to the myPlugin() method. It does so by passing an anonymous function to the each() iterator, making this function execute for every element in the jQuery object. Inside the anonymous function, an inner function called changeColor() does the actual work of changing the element’s color. As written, this code is inefficient because, you guessed it, the changeColor() function is defined inside the iterating function… making the JavaScript engine recreate changeColor() with each iteration.

    Making this code more efficient is rather simple and follows the same pattern as before: refactor the changeColor() function to be defined outside of any containing functions, and allow it to receive the information it needs to do its work. In this case, changeColor() needs the jQuery object and the new color value. The improved code looks like this:

    function changeColor($obj, color) {
        $obj.css({color : color});
    }
    
    $.fn.myPlugin = function(options) {
    
        return this.each(function() {
            var $this = $(this);
    
            changeColor($this, options.color);
        });
    };

    Interestingly, this optimized code increases performance by a much smaller margin than the foo() and bar() example, with Chrome leading the pack with a 15% performance gain (jsperf.com/function-nesting-with-jquery-plugin). The truth is, accessing the DOM and using jQuery’s API add their own hit to performance—especially jQuery’s each(), which is notoriously slow compared to JavaScript’s native loops. But as before, keep in mind the simplicity of this example. The more nested functions, the greater the performance gain from optimization.

    Nesting Functions in Constructor Functions

    Another variation of this anti-pattern is nesting functions within constructors, as shown below:

    function Person(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    
        this.getFullName = function() {
            return this.firstName + " " + this.lastName;
        };
    }
    
    var jeremy = new Person("Jeremy", "McPeak"),
        jeffrey = new Person("Jeffrey", "Way");

    This code defines a constructor function called Person(), and it represents (if it wasn’t obvious) a person. It accepts arguments containing a person’s first and last name and stores those values in firstName and lastName properties, respectively. The constructor also creates a method called getFullName(); it concatenates the firstName and lastName properties and returns the resulting string value.

    When you create any object in JavaScript, the object is stored in memory

    This pattern has become quite common in today’s JavaScript community because it can emulate privacy, a feature that JavaScript isn’t currently designed for (note that privacy isn’t in the above example; you’ll look at that later). But in using this pattern, developers create inefficiency not only in execution time, but in memory usage. When you create any object in JavaScript, the object is stored in memory. It stays in memory until all references to it are either set to null or are out of scope. In the case of the jeremy object in the above code, the function assigned to getFullName is typically stored in memory for as long as the jeremy object is in memory. When the jeffrey object is created, a new function object is created and assigned to jeffrey‘s getFullName member, and it too consumes memory for as long as jeffrey is in memory. The problem here is that jeremy.getFullName is a different function object than jeffrey.getFullName (jeremy.getFullName === jeffrey.getFullName results in false; run this code at [jsfiddle.net] ). They both have the same behavior, but they are two completely different function objects (and thus each consume memory). For clarity, take a look at Figure 1:

    Figure 1

    Here, you see the jeremy and jeffrey objects, each of which have their own getFullName() method. So, each Person object created has its own unique getFullName() method—each of which consumes its own chunk of memory. Imagine creating 100 Person objects: if each getFullName() method consumes 4KB of memory, then 100 Person objects would consume at least 400KB of memory. That can add up, but it can be drastically reduced by using the prototype object.

    Use the Prototype

    As mentioned earlier, functions are objects in JavaScript. All function objects have a prototype property, but it is only useful for constructor functions. In short, the prototype property is quite literally a prototype for creating objects; whatever is defined on a constructor function’s prototype is shared among all objects created by that constructor function.

    Unfortunately, prototypes are not stressed enough in JavaScript education.

    Unfortunately, prototypes are not stressed enough in JavaScript education, yet they are absolutely essential to JavaScript because it’s based on and built with prototypes—it’s a prototypal language. Even if you never typed the word prototype in your code, they are being used behind the scenes. For example, every native string-based method, like split(), substr(), or replace(), are defined on String()‘s prototype. Prototypes are so important to the JavaScript language that if you do not embrace JavaScript’s prototypal nature, you’re writing inefficient code. Consider the above implementation of the Person data type: creating a Person object requires the JavaScript engine to do more work and allocate more memory.

    So, how can using the prototype property make this code more efficient? Well, first take a look at the refactored code:

    function Person(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    
    Person.prototype.getFullName = function() {
        return this.firstName + " " + this.lastName;
    };
    
    var jeremy = new Person("Jeremy", "McPeak"),
        jeffrey = new Person("Jeffrey", "Way");

    Here, the getFullName() method definition is moved out of the constructor and onto the prototype. This simple change has the following effects:

    • The constructor performs less work, and thus, executes faster (18%-96% faster). Run the test in your browser if you’d like.
    • The getFullName() method is created only once and shared among all Person objects (jeremy.getFullName === jeffrey.getFullName results in true; run this code at [jsfiddle.net] ). Because of this, each Person object uses less memory.

    Refer back to Figure 1 and note how each object has its own getFullName() method. Now that getFullName() is defined on the prototype, the object diagram changes and is shown in Figure 2:

    Figure 2

    The jeremy and jeffrey objects no longer have their own getFullName() method, but the JavaScript engine will find it on Person()‘s prototype. In older JavaScript engines, the process of finding a method on the prototype could incur a performance hit, but not so in today’s JavaScript engines. The speed at which modern engines find prototyped methods is extremely fast.

    Privacy

    But what about privacy? After all, this anti-pattern was birthed out of a perceived need for private object members. If you’re not familiar with the pattern, take a look at the following code:

    function Foo(paramOne) {
        var thisIsPrivate = paramOne;
    
        this.bar = function() {
            return thisIsPrivate;
        };
    }
    
    var foo = new Foo("Hello, Privacy!");
    alert(foo.bar()); // alerts "Hello, Privacy!"

    This code defines a constructor function called Foo(), and it has one parameter called paramOne. The value passed to Foo() is stored in a local variable called thisIsPrivate. Note that thisIsPrivate is a variable, not a property; so, it is inaccessible outside of Foo(). There’s also a method defined inside the constructor, and it’s called bar(). Because bar() is defined within Foo(), it has access to the thisIsPrivate variable. So when you create a Foo object and call bar(), the value assigned to thisIsPrivate is returned.

    The value assigned to thisIsPrivate is preserved. It cannot be accessed outside of Foo(), and thus, it is protected from outside modification. That’s great, right? Well, yes and no. It’s understandable why some developers want to emulate privacy in JavaScript: you can ensure that an object’s data is secured from outside tampering. But at the same time, you introduce inefficiency to your code by not using the prototype.

    So again, what about privacy? Well that’s simple: don’t do it. The language currently does not officially support private object members—although that may change in a future revision of the language. Instead of using closures to create private members, the convention to denote "private members" is to prepend the identifier with an underscore (ie: _thisIsPrivate). The following code rewrites the previous example using the convention:

    function Foo(paramOne) {
        this._thisIsPrivate = paramOne;
    }
    
    Foo.prototype.bar = function() {
        return this._thisIsPrivate;
    };
    
    var foo = new Foo("Hello, Convention to Denote Privacy!");
    alert(foo.bar()); // alerts "Hello, Convention to Denote Privacy!"

    No, it’s not private, but the underscore convention basically says "don’t touch me." Until JavaScript fully supports private properties and methods,  wouldn’t you rather have more efficient and performant code than privacy? The correct answer is: yes!

    Summary

    Where you define functions in your code impacts your application’s performance; keep that in mind as you write your code. Don’t nest functions inside a frequently called function. Doing so wastes CPU cycles. As for constructor functions, embrace the prototype; failure to do so results in inefficient code. After all, developers write software for users to use, and an application’s performance is just as important to the user’s experience as the UI.


  • Permalink for 'How to Build an RSS Reader with jQuery Mobile'

    How to Build an RSS Reader with jQuery Mobile

    Posted: October 17th, 2011, 12:00pm MDT by Jeffrey Way

    Twice a month, we revisit some of our readers’ favorite posts from through out the history of Nettuts+. This tutorial was first published in October 2010.

    Today, we’ll dive into jQuery Mobile, which, at the time of this writing, is in a RC1 state. We’ll build a simple Tuts+ RSS reader, using PHP and jQuery Mobile. When we’re finished, you’ll have the ability to add this simple project to your iPhone or Android phone with the click of a button, as well as the skills to build your own custom mobile web apps!

    Step 1: Outline the Project

    It’s always helpful to first outline what you want your project to do/achieve.

    • Display a list of every Tuts+ site, along with its square logo
    • Display the feed for each site, when clicked on
    • Create a basic *article* stylesheet for rendering each posting
    • Create an Apple-touch icon for the users who add the “app” to their phone
    • Use YQL to retrieve the desired RSS feed
    • Implement a basic form of “text file” caching every three hours
    Step 2: Begin

    The next step is to begin creating our project. Go ahead and make a new folder — name it how you wish — and add a new header.php file. *Note that this project uses PHP. If you’re not familiar with this language, feel free to skip the PHP parts! Within this file, we’ll reference jQuery mobile, its stylesheet, and any other assets that we require. If only to stay organized, I’ve placed my header.php file within an includes/ folder.

    <!DOCTYPE html>
    <html>
       <head>
       <meta charset="utf-8">
       <meta [http-equiv="X-UA-Compatible"] content="IE=edge,chrome=1" />
    
       <title> Tuts+ </title> 
    
       <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a1/jquery.mobile-1.0a1.min.css" />
       <link rel="apple-touch-icon" href="img/tutsTouchIcon.png" />
    
       <script src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
       <script src="http://code.jquery.com/mobile/1.0a1/jquery.mobile-1.0a1.min.js"></script>
    </head>
    

    There are a handful of things worth noting here.

    1. An HTML5 doctype is required. But you should be using that anyways!
    2. The X-UA-Compatible tag forces IE to use it most current rendering engine
    3. We need to reference jQuery Mobile’s stylesheet. You can use their CDN, and save on bandwidth!
    4. If you want to designate an icon for when users add your webpage to their iPhone (or Android) home screen, add a link tag, with a rel attribute of apple-touch-icon.
    5. We’re referencing the most recent version of jQuery: 1.4.3
    6. Finally, we’re loading the jQuery mobile script file (currently in Alpha 1)
    The Basic Structure

    The jQuery Mobile framework can be activated by applying unique data-* attributes to your code. The basic structure for most sites will look similar to:

    <!-- Let's include the header file that we created above -->
    <?php include('includes/header.php'); ?>
    <body>
     <div data-role="page">
    
       <header data-role="header">
    
       </header>
    
       <div data-role="content">
    
       </div>
    
       <footer data-role="footer">
    
       </footer>
    
     </div>
    
    </body>
    </html>
    

    Add the code above to a new index.php file, within the root of your project.

    We have to tell jQuery about our project. For example, try not to think of each file as a page. Technically, you can create multiple pages at a time, by adding additional wrapping data-role="page" attributes. These are referred to as inner pages.

    Further, the framework has specific settings and stylings in place for the header, main content area, and footer. To inform jQuery Mobile about the locations of these elements, we add the following attributes.

    • data-role="header"
    • data-role="content"
    • data-role="footer"
    No Data Attributes Applied

    No data-role attributes have been applied.

    Data Applied

    Data-role attributes applied.

    Step 3: Listing the Tutorial Sites

    Now that the structure of our index.php page is complete, we can populate each section with our Tuts+ specific mark-up.

    <body>
     	<div>
    	    <header data-role="header">
    	    	<h1> <img src="img/TLogo.png" alt="Tuts+"/> </h1>
    	    </header>
    
    	    <div data-role="content">
    			<ul>
    				<li>
    					<img src="img/ntLogo.jpg" alt="Nettuts" class="ui-li-icon"/>
    					<a href="site.php?siteName=nettuts"> Nettuts+ </a>
    				</li>
    				<li>
    					<img src="img/psdLogo.jpg" alt="Psdtuts" class="ui-li-icon"/>
    					<a href="site.php?siteName=psdtuts"> Psdtuts+ </a>
    				</li>
    				<li>
    					<img src="img/vectorLogo.jpg" alt="Vectortuts+" class="ui-li-icon"/>
    					<a href="site.php?siteName=vectortuts"> Vectortuts+ </a>
    				</li>
    				<li>
    					<img src="img/mobileLogo.png" alt="Mobiletuts+" class="ui-li-icon"/>
    					<a href="site.php?siteName=mobiletuts"> Mobiletuts+ </a>
    				</li>
    				<li>
    					<img src="img/aeLogo.jpg" alt="Aetuts+" class="ui-li-icon"/>
    					<a href="site.php?siteName=aetuts"> Aetuts+ </a>
    				</li>
    				<li>
    					<img src="img/photoLogo.jpg" alt="Phototuts+" class="ui-li-icon"/>
    					<a href="site.php?siteName=phototuts"> Phototuts+ </a>
    				</li>
    				<li>
    					<img src="img/cgLogo.jpg" alt="Cgtuts+" class="ui-li-icon"/>
    					<a href="site.php?siteName=cgtuts"> Cgtuts+ </a>
    				</li>
    				<li>
    					<img src="img/audioLogo.jpg" alt="Audiotuts+" class="ui-li-icon"/>
    					<a href="site.php?siteName=audiotuts"> Audiotuts+ </a>
    				</li>
    				<li>
    					<img src="img/wdLogo.jpg" alt="Webdesigntuts+" class="ui-li-icon"/>
    					<a href="site.php?siteName=webdesigntutsplus"> Webdesigntuts+ </a>
    				</li>
    			</ul>
    	    </div>
    
    	    <footer data-role="footer">
    			<h4> www.tutsplus.com </h4>
    	    </footer>
    
    	</div>
    
    </body>
    </html>
    
    • Header: In this section, we’re simply inserting the Tuts+ graphic, and providing alternate text if images are turned off.
    • Content: In the content area, we need to list all of the tutorial sites, and apply a unique icon next to each heading. We also link to a new page, site.php that will handle the process of retrieving the RSS feed. For convenience, when we link to site.php, we also pass through the name of the selected site, via the querystring: siteName=nettuts.
    • Footer: At the bottom, for now, we’ll simply add a link to Tuts+.

    jQuery Mobile offers a plethora of helpful CSS classes, including ui-li-icon. When applied to an image, it’ll float it to the left, and apply 10px worth of margin-right.

    Our project so far

    At this point, our site should look like the above image.

    Page Transitions

    As jQuery will load local pages asynchronously with AJAX, we can specify any number of cool page transitions. The default is the basic slide-left or slide-right effect that most touch-phone users are aware of. To override the default, use the data-transition attribute on the anchor tag.

    <a href="site.php?siteName=nettuts" data-transition="pop"> Nettuts+ </a>
    
    Available Transitions
    • slide
    • slideup
    • slidedown
    • pop
    • flip
    • fade
    Step 4: ListViews

    Ehh – the image, shown above, still looks like a website. We need to make things a bit more phone-like. The answer is to use the data-role="listview" attribute. Watch what happens when we do nothing more than apply this attribute to the wrapping unordered list.

    Using the listview data-role attribute

    Wow – what an improvement! Even better, we have access to theme-roller, which allows us, with the change of a single letter, to switch color themes.

    <ul data-role="listview" data-theme="a">
    
    Theme A
    <ul data-role="listview" data-theme="b">
    
    Theme B
    <ul data-role="listview" data-theme="e">
    
    Theme E List Dividers

    Now, what if we wanted to divide this list of tutorial sites? In these situations, we can take advantage of data-role="list-divider", which can be applied to the <li> element.

    List Divider

    These, too, can receive lettered theme roller stylings. They can be set within the parent <ul>.

    <ul data-role="listview" data-dividertheme="d">
    
    Divider Theme
    Learn more about list dividers.

    Note that we won’t be using dividers for this particular application.

    Step 5: CSS

    jQuery Mobile takes care of a great deal of the formatting, however, we still, of course, need our own stylesheet for tweaking. For example, looking at the images above, we can see that the tutorial icons need to be pushed up a bit. Additionally, I’d like to use the Tuts+ red for the background color of the heading and footer, rather than the default black.

    Create a new folder, CSS, and add a new stylesheet — I’ll call mine: mobile.css. Within this file, we’ll first fix the icon positioning:

     .ui-li-icon {
       top:  9px;
    }
    

    Next, we’ll create a handful of classes, named after their respective tutorial sites. These classes will contain any specific formatting/colors for the site. For example, Nettuts+ has a darker green color, while MobileTuts+ is yellow.

    .tuts { background: #c24e00; }
    .nettuts { background: #2d6b61; }
    .psdtuts { background: #af1c00; }
    .vectortuts { background: #1e468e; }
    .aetuts { background: #4a3c59; }
    .phototuts { background: #3798aa; }
    .cgtuts { background: #723b4a; }
    .audiotuts { background: #4b7e00; }
    .webdesigntutsplus { background: #0d533f; }
    .mobiletuts { background: #dba600; }
    

    That should be fine for now. The last step for index.php is to apply the .tuts class to the header and footer elements. That way, the header and footer will render the correct background color.

    <header data-role="header" class="tuts">
    ...
    <footer data-role="footer" class="tuts">
    
    Added the Tuts Color Step 6: YQL, PHP, and Caching

    Now, it’s time to step away from the layout, and work on the functionality. Each of the links we created directed to site.php?siteName="siteName". Let’s go ahead and create that file now.

    Even though this is a relatively tiny app, we should still strive to follow best practices. In this case, it means that we should keep as little PHP in our document as possible. Instead, we’ll use site.php as a controller of sorts. This file will handle the initial logic, and will then, at the bottom, load in our HTML template.

    Assigning the Site Name

    In order to retrieve the desired RSS feed, we first need to capture the name of the site that the user clicked on initially. If you’ll refer to a previous step, when we linked to site.php, we also passed the name of the site through the querystring. With PHP, this can easily be retrieved, with $_GET['siteName']. However, what if, for some odd reason, this value doesn’t exist? Maybe site.php was accessed directly?? We should set a default site to compensate for these situations.

    $siteName = empty($_GET['siteName']) ? 'nettuts' : $_GET['siteName'];
    

    If $_GET['siteName'] is empty, we’ll set “nettuts” to the variable, $siteName. Otherwise, it’ll be equal to the name of the respective site.

    Security

    Even though this is a small project, let’s also try to set some security in place. To prevent the user from automatically assigning a potentially dangerous value to the siteName key, let’s ensure that the value is in fact the name of one of our tutorial sites.

    // Prepare array of tutorial sites
    $siteList = array(
       'nettuts',
       'flashtuts',
       'webdesigntutsplus',
       'psdtuts',
       'vectortuts',
       'phototuts',
       'mobiletuts',
       'cgtuts',
       'audiotuts',
       'aetuts'
    );
    
    // If the string isn't a site name, just change to nettuts instead.
    if ( !in_array($siteName, $siteList) ) {
       $siteName = 'nettuts';
    }
    

    The in_array() function allows us to determine if a value — in our case, the value of $siteName — is equal to one of the items in the $siteList array.

    Caching

    Ultimately, we’ll be using the excellent YQL to perform our queries. Think of YQL as an API for APIs. Rather than having to learn twenty different APIs, YQL’s SQL-like syntax allows you to only learn one. However, though YQL does perform a bit of caching on its own, let’s also save the RSS feeds to a text file on our server. That way, we can improve performance a fair bit.

    We begin by creating a new variable, $cache, and making it equal to the location of where the cached file will be stored.

    $cache = dirname(__FILE__) . "/cache/$siteName";
    

    The code above points to the current directory of the file, and then into a cache folder, and, finally, the name of the selected site.

    I’ve decided that this cached file should be updated every three hours. As such, we can run a quick if statement, and determine the last time that the file was updated. If the file does not exist, or the update was longer than three hours ago, we query YQL.

    $cache = dirname(__FILE__) . "/cache/$siteName";
    // Re-cache every three hours
    if( filemtime($cache) 
    

    YQL is ridiculously easy to work with. In our case, we'll use it for a very simple purpose: grab the RSS feed, in JSON form, of the site that was passed through the querystring, via siteName. You can experiment with the various commands by using the YQL console.


    YQL Console

    To query an RSS feed, we using the command: SELECT * FROM feed WHERE url="path/to/rss/feed".

    Building the Path

    For the sake of readability, we'll build up our YQL query in sections.

     // YQL query (SELECT * from feed ... ) // Split for readability
     $path = "http://query.yahooapis.com/v1/public/yql?q=";
     $path .= urlencode("SELECT * FROM feed WHERE url='http://feeds.feedburner.com/$siteName'");
     $path .= "&format=json";
    

    The key is the second part above; when the page loaded, we grabbed the name of the site from the querystring. Now, we only need to insert it into the SELECT query. Luckily, all of the tutorial sites use Feedburner! Make sure that you urlencode the query to replace any special characters.

    Okay, the path is ready; let's use file_get_contents() to grab the feed!

    $feed = file_get_contents($path, true);
    

    Assuming that $feed is now equal to the returned JSON, we can store the results in a text file. However, let's first ensure that data was returned. As long as something is returned from the query, $feed->query->count will be equal to a value greater than zero. If it is, we'll open the cached file, write the data to the file, and finally close it.

    // If something was returned, cache
    if ( is_object($feed) && $feed->query->count ) {
       $cachefile = fopen($cache, 'w');
       fwrite($cachefile, $feed);
       fclose($cachefile);
    }
    

    It seems confusing, but it's really not. The function fopen() accepts two parameters:

    • The file to open: We stored this path in the $cache variable at the top of the page. Note that, if this file doesn't exist, it will create the file for you.
    • Access privileges: Here, we can specify which privileges are available. w stands for "write."

    Next, we open that file, and write the contents of $feed (the returned RSS JSON data) to the file, and close it.

    Using the Cached File

    Above, we first checked whether the cached file was greater than three hours old.

    if( filemtime($cache) 
    

    But what if it wasn't? In that case, we run an else statement, and grab the contents of the text file, rather than using YQL.

    if( filemtime($cache) 
    

    Lastly, we can't do much with the JSON RSS feed until we decode it with PHP.

    // Decode that shizzle
    $feed = json_decode($feed);
    

    And that should do it for our controller! With the logic out of the way, let's include our HTML template.

    // Include the view
    include('views/site.tmpl.php');
    

    Here's our final site.php. Click on the expand icon to view it.

    <?php
    // If "siteName" isn't in the querystring, set the default site name to 'nettuts'
    $siteName = empty($_GET['siteName']) ? 'nettuts' : $_GET['siteName'];
    
    $siteList = array(
       'nettuts',
       'flashtuts',
       'webdesigntutsplus',
       'psdtuts',
       'vectortuts',
       'phototuts',
       'mobiletuts',
       'cgtuts',
       'audiotuts',
       'aetuts'
    );
    
    // For security reasons. If the string isn't a site name, just change to
    // nettuts instead.
    if ( !in_array($siteName, $siteList) ) {
       $siteName = 'nettuts';
    }
    
    $cache = dirname(__FILE__) . "/cache/$siteName";
    // Re-cache every three hours
    if(filemtime($cache) query->count ) {
          $cachefile = fopen($cache, 'wb');
          fwrite($cachefile, $feed);
          fclose($cachefile);
       }
    }
    else
    {
       // We already have local cache. Use that instead.
       $feed = file_get_contents($cache);
    }
    
    // Decode that shizzle
    $feed = json_decode($feed);
    
    // Include the view
    include('views/site.tmpl.php');
    
    Step 7: The Site Template

    At the end of the previous step, we loaded in our template (or view). Go ahead and create that views folder, and site.tmpl.php file. Feel free to name it how you wish. Next, we'll insert our HTML.

    <?php include('includes/header.php'); ?>
    <body> 
    
    <div data-role="page">
    
       <header data-role="header" class="<?php echo $siteName; ?>">
          <h1><?php echo ucwords($siteName).'+'; ?></h1>
       </header>
    
       <div data-role="content">
          <ul data-role="listview" data-theme="c" data-dividertheme="d" data-counttheme="e">
    
          </ul>
       </div>
    
       <footer data-role="footer" class="<?php echo $siteName; ?>">
          <h4> www.tutsplus.com</h4>
       </footer>
    </div>
    
    </body>
    </html>
    
    Points of Interest Above
    • Notice how we follow the same basic layout: header, content area, footer.
    • As this template will be used for every Tuts+ tutorial site, we need to set the title dynamically. Luckily, if you remember, the site name was passed through the querystring, and stored in the $siteName variable (like, "nettuts"). To capitalize the first letter, and apply the signature + after the name, we'll run the variable through ucwords() (uppercases the first letter of each word in the string), and append a "+": <h1><?php echo ucwords($siteName).'+'; ?></h1>
    • We'll soon be displaying the number of comments for each posting next to the title. We can, again, use ThemeRoller to style it, via the data-counttheme="e" attribute.
    Site Template Thus Far Filtering Through the Feed

    At this point, we have access to the $feed object that contains our RSS feed. To dissect this object, you can either print_r($feed), or use the YQL console for a prettier view. We'll use the latter in this case. Check">[http%3A] it out.

    ">[http%3A]
    Dissecting the feed

    To grab the data for each posting, we need to filter through: $feed->query->results->item. PHP makes this a cinch with foreach().

    Within the foreach() statement, we can now access the desired values with $item->title, or $item->comments, which will display the title, and the comment number, respectively. Add the following within the <ul> tags.

    <ul data-role="listview" data-theme="c" data-dividertheme="d" data-counttheme="e">
    <?php
        foreach($feed->query->results->item as $item) { ?>
    
        <li>
          <h2>
             <a href="article.php?siteName=<?php echo $siteName;?>&origLink=<?php echo urlencode($item->guid->content); ?>">
                   <?php echo $item->title; ?>
             </a>
          </h2>
          <span class="ui-li-count"><?php echo $item->comments; ?> </span>
       </li>
    
    <?php  } ?>
    </ul>
    

    In the code above, we build up a list item, containing the title of the posting, the number of comments, and a link to article.php that also contains the site name and the permanent link (to the original article on the Tuts+ site) in the query-string.

    When we view the updated page in the browser, tada!

    Recent article list

    Notice how the comment count is in a yellow bubble, and is floated to the right? That's because we applied the data-counttheme="e" attribute to the wrapping unordered list. How convenient.

    Hmm...I think the text is too large for these long titles. A quick visit to Firebug shows that I can target the h2 tags with a class of .ui-li-heading. Let's return to our stylesheet (mobile.css), and add a new rule:

    .ui-li-heading { font-size: 12px; }
    

    That's better.

    Applying a smaller heading size Step 8: Displaying the Full Posting

    The final step is to build article.php, which will display the entire posting. As with site.php, article.php will serve as our controller, and will query the selected article with YQL, and load the appropriate view.

    <?php
    
    $siteName = $_GET['siteName'];
    $origLink = $_GET['origLink'];
    
    // YQL query (SELECT * from feed ... ) // Split for readability
    $path = "http://query.yahooapis.com/v1/public/yql?q=";
    $path .= urlencode("SELECT * FROM feed WHERE url='http://feeds.feedburner.com/$siteName' AND guid='$origLink'");
    $path .= "&format=json";
    
    $feed = json_decode(file_get_contents($path));
    $feed = $feed->query->results->item;
    
    include('views/article.tmpl.php');
    

    If you've been following along, the code above should look a bit more familiar to you. When we loaded this page, from site.php, we passed through two items, via the query string:

    • Site Name: Contains the name of the currently selected tutorial site
    • Orig Link: A link to the original posting on the tutorial site

    The difference with the YQL query, this time, is that we match the guid (orig link) with the posting that the user clicked on (or pressed). This way, exactly one posting will be returned. Check">[http%3A] out this sample YQL query to gain a better idea of what I mean.

    New YQL query Article Template

    At the bottom of the code above, we loaded the template file for the article page: views/article.tmpl.php. We'll create that file now.

    <?php include('includes/header.php'); ?>
    <body> 
    
    <div data-role="page">
    
       <header data-role="header" class="<?php echo $siteName; ?>">
          <h1> <?php echo ucWords($siteName).'+'; ?> </h1>
       </header>
    
       <div data-role="content">
            <h1> <?php echo $feed->title; ?> </h1>
            <div> <?php echo $feed->description; ?> </div>
       </div>
    
       <footer data-role="footer" class="<?php echo $siteName; ?>">
          <h4> <a href="<?php echo $feed->guid->content;?>"> Read on <?php echo ucWords($siteName); ?>+</a></h4>
       </footer>
    </div>
    
    </body>
    </html>
    

    Ah - so familiar. We've already gone over this template. The only difference is that, this time, because there's only one posting from the YQL query to display, we don't need to bother with a foreach() statement.

    Unstyled Article Page
    Unstyled article page

    At this point, on your own, the next step would be to begin applying your desired styling to the article. I don't see a need to go over it in this tutorial, as it all comes down to personal taste. Here's my super-minimal version.

    Minimally styled article page
    Applying a font-size, line-height, padding, and image formatting. Locked Footers

    One last thing: in the footer section of the article, we link to the original posting on Nettuts+. In its current state, the reader will only see that when they reach the bottom of the article. Let's lock the footer to the bottom of the current view-point at all times. We can use the data-position attribute to achieve this.

       <footer data-role="footer" data-position="fixed">
          <h4> <a href="<?php echo $feed->guid->content;?>"> Read on <?php echo ucWords($siteName); ?>+</a></h4>
       </footer>
    

    That's better!

    We're Done!

    And, with relatively little work, we've successfully built a mobile RSS reader for the Tuts+ sites. It can certainly be expanded to provide additional features, error checking, and performance improvements, but this will hopefully get you started! If you'd like to fork the project and make it better, by all means...do! Thanks for reading, and be sure to refer to the jQuery Mobile documentation for more details. I've no doubt that you'll come across more jQuery mobile tutorials on our sister site, Mobiletuts+.

    Add the Reader to your iPhone Home Screen Add to Home Screen
    View the Demo or Make it Better!


  • Permalink for 'The Best Way to Learn PHP'

    The Best Way to Learn PHP

    Posted: October 14th, 2011, 4:36pm MDT by Siddharth

    Learning something from scratch is almost always an arduous affair — you simply have no idea as to where to start, or not to start, to kick things off. I loathed learning about the idiosyncrasies of C++’s syntax when all I wanted to learn were some darn programming concepts. As I’m sure you can agree, this is a less than ideal situation.

    This is where the Nettuts+ “The Best Way to Learn” series comes into the picture. This series is intended to be your blueprint, your road map, your plan of action for learning your topic of choice! You don’t have to worry about finding the best resources, sorting out the bad ones, and figuring out what to learn next. It’s all here. Just follow it, step by step.

    Today, we’re going to figure out the best way to learn PHP.

    Assignment #1: Disregard the Naysayers

    If you’re reading this, chances are that you’ve googled a lot to decide which language to learn and how. And without a doubt, you must have run into a ton of articles about how language X is so much better than PHP and PHP is going to die through obscurity soon.

    Haters gonna hate!

    As the popular saying goes, haters gonna hate! PHP has been at the helm of the web as you know it and that’s for a very good reason. It’s a mature language, has excellent documentation and a massive number of learning resources along with a great variety of utilities built around it.

    And let’s not forget the sheer proliferation of hosts and frameworks PHP has spawned. Like Heroku like hosting? Don’t worry, there are a number of excellent options for PHP as well!

    Assignment #2: Install PHP through [X]AMP Tut image

    You could just install PHP but it gets quite boring without a server and some sort of database to play around with. And as a beginner, it’s not really trivial work to get all of these installed and configure each to work with the others without issue.

    This is where you grab a package such as XAMPP. These life savers typically install Apache, your web server, along with mySQL, a database system along with PHP significantly cutting down on set up time.

    Bonus points if you’re the code monkey type and install everything by hand.

    Assignment #3: Dive into PHP!

    Before I send you off to alternate sources for PHP enlightenment, let me first refer you to our very own series for absolute beginners from none other than your favorite editor, Jeffrey Way.*

    In this series, everything from installing PHP to variables, from functions to working with SQL are covered. They maybe more than two years old but gosh darnit!, they’re still extremely relevant.

    *who is also painfully humble so shoosh and stop making him blush!

    Assignment #4: Sign up with Khan Academy and Lynda Tut image

    Khan Academy may sound like an odd choice since there are no PHP lessons in there but trust me, it’s a good choice. What you can’t find in pure PHP, you can find in the basic of programming. For example, if you’re new to the entire programming hoopla, this is a great place to start.

    Another great place to start is Lynda. Here at Envato we have immense respect for those teaching there — the content is usually top notch and cover their topics well. And they cover a vast range of topics as well. If you need a specific lesson, this is where you should begin.

    Assignment #5: Read a Few, Good Books

    The videos should give you an very good springboard, but, hopefully, hungry for more knowledge. The below books should give you a more elaborate introduction and lots of varied topics for you to devour.

    If you feel bored reading the initial portions, good, just skip ahead to the portions where your head hurts.

    Nettuts image PHP Solutions: Dynamic Web Design Made Easy

    Author: David Powers

    “So why another PHP book? Well, not everyone who uses PHP is a programmer. PHP is the most common dynamic web language used by designers, if their web sites require dynamic functionality, and there are hordes of novice users who want to set up dynamic web sites.”

    Nettuts image PHP for Absolute Beginners

    Author: Jason Lengstorf

    “PHP for Absolute Beginners starts at the very beginning stages of web programming, showing even the most inexperienced web developer, through examples, how to build a basic content management system. The book dives directly into writing web applications with accompanying explanation rather than explaining elements of the language and then showing examples.”

    Nettuts image PHP Cookbook

    Author: Adam Trachtenberg

    “PHP Cookbook has a wealth of solutions for problems that you’ll face regularly. With topics that range from beginner questions to advanced web programming techniques, this guide contains practical examples — or “recipes” — for anyone who uses this scripting language to generate dynamic web content.”

    Assignment #6: Create Something Simple

    This is the perfect time to build something simple with your new found knowledge.

    Alright! With all those information swirling inside, you should feel like a rockstar. If not, don’t worry, it’s completely normal. Talk to me later so we can share notes about how daft we feel.

    This is the perfect time to try and build something simple with your new found knowledge. It’s best to not try to build something too complicated and fail though — it’s a lot more disheartening than you’d think. Imagine being rejected for the first time. Now multiply it by a few hundred and you’ll be close.

    Since you’re just starting out, play it safe and build something absolutely basic like a CRUD app. Nothing major — a few inputs and an ‘uncool’ table to display saved results. This tiny exercise will test your knowledge of a lot of PHP basics including the much vaunted ‘interfacing with a database’ skill.

    Assignment #7: Create Something a Little More Complicated

    Feeling better now? You should! You gazed upon where there was naught and said ‘This won’t do!’ and created something from scratch. If it were me, I’d be pumped. Let’s use it to extend our knowledge a little more.

    While a simple CRUD app is a great start, you’d ideally need more complicated. A simple login/user system is absolutely great for this.

    You get to learn how sessions work, how basic authentication is done, how to implement basic security measure and a ton more.

    Note: If you’re in need of a little guidance, start here.

    Assignment #8: Try out a Lean, Lightweight Framework Tut image

    At this point, after creating a non-trivial system, you probably have noticed how repetitive some of the work is. Why the heck do you need to write your own sessions class or work on hashing passwords yourself? The answer, my friends, is to go with a lightweight framework.

    A framework abstracts a lot of the repetitive, boilerplate features in your typical application thus freeing up your brain to actually getting things done.

    Note: Not to toot our own horn but we have an immensely thorough session that covers almost all of the important parts of CodeIgnier, a very lightweight, yet powerful framework. If you prefer Kohana, we do that too!

    Assignment #9: Try out a Full Stack Framework Tut image

    Now that you’ve been with a lightweight framework, you can now check out the alternate path — a full stack framework. A full stack framework typically ships with a lot more features including code generators, ORMs and an inbuilt server. An excellent choice would be CakePHP — the PHP equivalent of Rails.

    The reason you need to check these out later is because there is a lot of ‘magic’ going in these frameworks. Without a solid understanding of how lightweight frameworks work, it’s hard to really dig into the better featured ones since you’ll mostly be lost and won’t understand how things work.

    Note: For a quick look on CakePHP, start here.

    Assignment #10: Build Something Awesome

    With all that information behind you, giving you Indiana’s swagger, now is the time to build something truly awesome. This is the final destination for PHP nirvana — and the choice is up to you.

    So what exactly should you be building? Here are a few ideas:

    • A blog is always a safe option. There are a ton of open source solutions for you to get inspiration for the software architecture and the functionality requirements are unambiguous.
    • It’s a little old school but a discussion board is another excellent choice. Moderator rights and post counts, ahoy! If you need a little guidance, this tutorial is a great place to start.
    • Or if you’re too hip for any of these, build yourself a project management application or even just a todo list. They’re always fun to build and you’ll almost always end up using it personally.

    Of course, there are just suggestions. No one is stopping you from building a multi-user, realtime chatroom or a service which receives input from random internet strangers and lights up stuff in your room. No one’s judging, go crazy!

    Assignment #11: Advance into Development Eliteness

    Development is as much about the workflow as much as it is about the code.

    Development is as much about the workflow as much as it is about the code. Recently, a typical developer’s workflow has been massively improved by version control as well as platform as a service solutions.

    Version control, as expected, frees you up from having to manage revisions manually while PaaS solutions save you from having to do a lot of sys admin work just to get your app to scale.

    Resources for the latter are a bit hard to find but here is an excellent screencast on getting started with Git.

    Assignment #12: Get Involved and Be Up to Date

    New techniques and tools are being introduced everyday.

    The web development industry is rarely in a state of equilibrium — everything is changing all the time. New techniques and tools are being introduced everyday and it’s important that you not only read about them but also start contributing.

    Find a little glitch in some framework? Submit a patch. Added some new functionality? Patch away! These not only earn you good karma but also valuable points on your resume.

    And, oh, about the keeping up to date stuff? Subscribe to our feed and follow us on Twitter and I promise you’ll know all you need to know!

    Assignment #13: Keep an Open Mind and Explore Tryruby

    Even though that you are a master of the PHP domain, you can’t afford to, or shouldn’t, rest. PHP is a grand language but that doesn’t mean that it does absolutely everything perfectly.

    There is an ever increasing number of new languages out there each adding their own spin to solving a very specific problem that you simply can’t afford to miss out on. And learning something new something doesn’t really wipe out knowledge gained earlier does it? Well, except Star Wars, of course. Those new movies were a crapshoot.

    Ruby, Python and Clojure are some of the languages that I’m constantly amazed by and I think they deserve your attention as well. Neither of these languages are necessarily ‘better’ than PHP but each of them do things their own unique way and you owe yourself a chance to take a look and find out whether that approach is for you. While we’re a bit low on Clojure related content, we do have excellent tutorials on Ruby and Python right here.

    Conclusion

    Well, this is the end of the road, partner! Hopefully, this plan can help you become a PHP master and, indeed, take over the world.

    If you feel that I’m missing some obvious resources here, feel free to yell at me in the comments section below and I’ll update this article whilst crying silently. Thank you so much for reading!


  • Permalink for 'The Ins and Outs of PHP Exceptions'

    The Ins and Outs of PHP Exceptions

    Posted: October 13th, 2011, 11:38am MDT by Nikko Bautista

    Still returning false whenever a function in your program fails? In this article, we’ll learn about PHP exceptions, and how you can use them to soup up your application’s error handling.

    Introduction What are exceptions? Exceptions
    Catching exceptions as shown by Superman
    Image courtesy of [tvtropes.org]

    Exceptions are special conditions, usually errors, that can occur or be explicitly made by a program. They connote that something entirely different from what was expected has occurred. In most cases, the situation requires that a special instruction set be done in order to mitigate a catastrophic system failure.

    Uncaught Exception in a Nuclear Power plant
    Uncaught exception in a nuclear power plant
    Image courtesy of [phenomenaonbreak.wordpress.com] How do we use exceptions?

    Exceptions can be thrown and caught. When an exception is thrown, it means that something out of the ordinary has happened, and it will require another function to do something else. Catching an exception is the function telling the rest of the program, “Hey, I can handle this exception, let me at it!”

    Come at me bro
    Try-catch function: come at me bro
    Image courtesy of [richlington.blogspot.com]

    Exceptions can be explained by using the analogy of a baseball game.

    • The pitcher (Bowser) throws a baseball to the catcher.
    • The batter (Mario) tries to hit the ball. If he’s not able to do it, he gets a strike. If he’s able to do it, a fielder (either Donkey Kong or Waluigi) has to catch it.
    • If Donkey Kong catches the ball, he then has two choices: if he’s not close enough, he can throw it to another fielder; or if he’s close enough, he can throw it to a baseman and tag Mario to get an out.
    Exceptions are like Mario Baseball. Wait, what?
    Exceptions are like Mario Baseball. Wait, what?
    Image courtesy of [thebreakingstory.com]

    In exceptions, the pitcher throwing a baseball to the catcher is like a function running normally.

    But when the batter hits the ball, something “exceptional” happens, and certain routines need to be done.

    A fielder catching the baseball is like a try-catch function getting the exception. This try-catch function can now either handle the exception, or throw it for another try-catch function to handle. Whichever try-catch function can handle the exception is the one that finally does something.

    Using PHP Exceptions

    It’s really simple to implement exceptions in PHP. Since exceptions are part of the Standard PHP Library or SPL, they’re part of PHP core as long as you’re running PHP 5 and above. Exceptions are already there, just longing and waiting to be used.

    Forever Alone
    “Please use us.” Exceptions: forever alone.
    Image courtesy of [knowyourmeme.com]

    Exceptions are instantiated the same way as objects:

    $exception = new Exception();
    throw $exception;
    

    Much like objects, they also have methods that can be called. These methods make it easier for a try-catch function to react to exceptions. For example, the getMessage() function will let you get an exception’s error message, which you can then log or show on the browser.

    Here’s a list of an exception’s methods:

    • getMessage() – gets the exception’s message
    • getCode() – returns a numerical code that represents the exception
    • getFile() – returns the file where the exception was thrown
    • getLine() – returns the line number in the file where the exception was thrown
    • getTrace() – returns the an array of the backtrace() before the exception was thrown
    • getPrevious() – returns the exception thrown before the current one, if any
    • getTraceAsString() – returns the backtrace() of an exception as a string instead of an array
    • __toString() – returns the whole exception as a string. Is overrideable.

    To better illustrate these methods, let’s create a User class that does basic user record management:

    <?php
    class User
    {
    	protected $_user_id;
    	protected $_user_email;
    	protected $_user_password;
    
    	public function __construct($user_id)
    	{
    		$user_record = self::_getUserRecord($user_id);
    		$this->_user_id = $user_record['id'];
    		$this->_user_email = $user_record['email'];
    		$this->_user_password = $user_record['password'];
    	}
    
    	//we'll fill these in later
    	public function __get($value) {}
    	public function __set($name, $value) {}
    
    	private static function _getUserRecord($user_id)
    	{
    		//For this tutorial, we'll use a mock-up record to represent retrieving the record
    		//from the database and returning the data
    		$user_record = array();
    		switch($user_id) {
    			case 1:
    				$user_record['id'] = 1;
    				$user_record['email'] = 'nikko@example.com';
    				$user_record['password'] = 'i like croissants';
    				break;
    
    			case 2:
    				$user_record['id'] = 2;
    				$user_record['email'] = 'john@example.com';
    				$user_record['password'] = 'me too!';
    				break;
    
    			case 'error':
    				//simulates an unknown exception from whatever SQL library is being used:
    				throw new Exception('An error from the SQL library!');
    				break;
    		}
    
    		return $user_record;
    	}
    }
    ?>
    

    In this example, there are several places where something exceptional could happen. For starters, the $user_id input in our _getUserRecord() function should be an integer. In the event that it’s not, we should throw an exception:

    	...
    	...
    	...
    	private static function _getUserRecord($user_id)
    	{
    		$user_id = self::_validateUserId($user_id);
    		...
    		...
    		...
    	}
    
    	private static function _validateUserId($user_id)
    	{
    		if( !is_numeric($user_id) && $user_id != 'error' ) {
    			throw new Exception('Whoa! I think there\'s something wrong with the user id');
    		}
    		return $user_id;
    	}
    

    Let’s try it out by instantiating our User class with an invalid parameter:

    //First try getting our user numero uno
    $user = new User(1);
    
    //Then, let's try to get the exception
    $user2 = new User('not numeric');
    

    You should get an error like this:

    Forever Alone
    Uncaught exception error message

    Now, let’s have Donkey Kong catch this exception.

    Exception caught
    Exception caught, hell yeah!
    Image courtesy of [3×6.nl]
    try {
    	//First try getting our user numero uno
    	$user = new User(1);
    
    	//Then, let's try to get the exception
    	$user2 = new User('not numeric');
    } catch( Exception $e ) {
    	echo "Donkey Kong has caught an exception: {$e->getMessage()}";
    }
    

    Let’s run it again, this time with our try-catch function:

    Thanks Donkey Kong!
    Thanks Donkey Kong!

    As you can see, with Donkey Kong catching our exceptions, we were able to suppress the awful error messages thrown by PHP when an exception is uncaught.

    One thing to note here is that when an exception is thrown, it only stops when a try-catch function is able to catch it. Otherwise, it will remain uncaught, keep climbing up the trace of the function call, and be displayed as an error on the browser. In our current example, let’s trace where our exception gets thrown:

    • Create a new User object on the $user2 = new User('not numeric'); line
    • Run the __construct() function of the User class
    • Go to the _getUserRecord() function of the User class
    • Validate the $user_id using the _validateUserId function
    • If the $user_id is not numeric, throw a new Exception object

    We can also run the getTraceAsString() function to get the trace of the exception, which will give us the exact same thing:

    ...
    ...
    } catch( Exception $e ) {
    	echo "Donkey Kong has caught an exception: {$e->getMessage()}";
    	echo '<pre>';
    	echo $e->getTraceAsString();
    	echo '</pre>';
    }
    
    getTraceAsString
    getTraceAsString() results

    As you can see, even if the exception is thrown deep inside the trace of $user2 = new User('not numeric'), it keeps climbing up until it gets caught in the try-catch block on the top-most level.

    Now, let’s construct our exception to use a code. Associating a code number with an exception is a good way of hiding the error from the client. By default, the code number of an exception is 0, but we can override this whenever we create a new exception:

    ...
    ...
    ...
    if( !is_numeric($user_id) ) {
    	throw new Exception('Whoa! I think there\'s something wrong with the user id', UserErrors::INVALIDID);
    }
    ...
    ...
    ...
    

    Don’t forget to create our UserErrors class:

    class UserErrors
    {
    	const INVALIDID 		= 10001;
    	const INVALIDEMAIL		= 10002;
    	const INVALIDPW			= 10003;
    	const DOESNOTEXIST		= 10004;
    	const NOTASETTING		= 10005;
    	const UNEXPECTEDERROR	= 10006;
    
    	public static function getErrorMessage($code)
    	{
    		switch($code) {
    			case self::INVALIDID:
    				return 'Whoa! I think there\'s something wrong with the user id';
    				break;
    
    			case self::INVALIDEMAIL:
    				return 'The email is invalid!';
    				break;
    
    			case self::INVALIDPW:
    				return 'The password is shorter than 4 characters!';
    				break;
    
    			case self::DOESNOTEXIST:
    				return 'That user does not exist!';
    				break;
    
    			case self::NOTASETTING:
    				return 'That setting does not exist!';
    				break;
    
    			case self::UNEXPECTEDERROR:
    			default:
    				return 'An unexpected error has occurred';
    				break;
    		}
    	}
    }
    

    We can then modify our exception handler to display the exception code instead of displaying the message:

    ...
    ...
    } catch( Exception $e ) {
    	echo "Donkey Kong has caught an exception with code: #{$e->getCode()}";
    }
    

    It should result in this:

    Exception Error Code

    Now, let’s use all the other methods of an exception by trying to log the exception. First off, let’s create our Logger class:

    class Logger
    {
    	public static function newMessage(
    		Exception $exception,
    		$clear = false,
    		$error_file = 'exceptions_log.html'
    	) {
    		$message = $exception->getMessage();
    		$code = $exception->getCode();
    		$file = $exception->getFile();
    		$line = $exception->getLine();
    		$trace = $exception->getTraceAsString();
    		$date = date('M d, Y h:iA');
    
    		$log_message = "<h3>Exception information:</h3>
    			<p>
    				<strong>Date:</strong> {$date}
    			</p>
    
    			<p>
    				<strong>Message:</strong> {$message}
    			</p>
    
    			<p>
    				<strong>Code:</strong> {$code}
    			</p>
    
    			<p>
    				<strong>File:</strong> {$file}
    			</p>
    
    			<p>
    				<strong>Line:</strong> {$line}
    			</p>
    
    			<h3>Stack trace:</h3>
    			<pre>{$trace}
    			</pre>
    			<br />
    			<hr /><br /><br />";
    
    		if( is_file($error_file) === false ) {
    			file_put_contents($error_file, '');
    		}
    
    		if( $clear ) {
    			$content = '';
    		} else {
    			$content = file_get_contents($error_file);
    		}
    
    		file_put_contents($error_file, $log_message . $content);
    	}
    }
    

    We’ll have to modify our exception handler to use the Logger class:

    ...
    ...
    } catch( Exception $e ) {
    	echo "Donkey Kong has caught an exception with code: #{$e->getCode()}";
    	Logger::newMessage($e);
    }
    

    Now, when we run our program again, it should just display the exception code. We can then open the exceptions_log.html file and we’ll see the log of exceptions we’re getting:

    Exception Log

    Congratulations! You now have working knowledge on how to implement basic PHP Exceptions. Now, let’s move on to more advanced stuff!

    Extending Exceptions

    Even at their most basic level, exceptions are already an essential tool for error handling in applications. By extending exceptions, however, we can create our own customized exceptions and take our application’s exception handling to the next level.

    The Next Level
    The next level is THIS much fun.

    To create a custom exception, we’ll need to create our own exception class, extending the Exception class. Let’s create a custom UserException for our user class:

    class UserException extends Exception
    {
    	public function __construct($error_code)
    	{
    		parent::__construct(UserErrors::getErrorMessage($error_code), $error_code);
    		Logger::newMessage($this);
    	}
    }
    

    As you can see, we overrode the __construct function to implement our own constructor. Since we extended the Exception object, we’re still able to use the default Exception constructor by using the parent keyword. By doing this, we can skip providing an error message every time we throw an exception, and just provide an exception code. We can also skip having to log it ourselves, since the custom constructor is set up to automatically log the exception.

    Let’s update our code to use the new UserException class:

    private static function _validateUserId($user_id)
    {
    	if( !is_numeric($user_id) && $user_id != 'error' ) {
    		throw new UserException(UserErrors::INVALIDID);
    	}
    	return $user_id;
    }
    

    Since the exception already automatically logs itself, we can skip logging it in our try-catch block:

    ...
    ...
    } catch( Exception $e ) {
    	echo "Donkey Kong has caught an exception with code: #{$e->getCode()}";
    	//Logger::newMessage($e);
    }
    

    Let’s also update the other places in our User class where we can expect exceptions.

    User class:

    ...
    ...
    ...
    public function __get($value) {
    	$value = "_{$value}";
    	if( !isset($this->$value) ) {
    		throw new UserException(UserErrors::NOTASETTING);
    	}
    	return $this->$value;
    }
    
    public function __set($name, $value) {
    	switch($name) {
    		case 'user_id':
    			$user_id = self::_validateUserId($value);
    			$this->_user_id = $user_id;
    			break;
    
    		case 'user_email':
    			$user_email = self::_validateUserEmail($value);
    			$this->_user_email = $user_email;
    			break;
    
    		case 'user_password':
    			$user_password = self::_validateUserPassword($value);
    			$this->_user_password = $user_password;
    			break;
    
    		default:
    			throw new UserException(UserErrors::NOTASETTING);
    			break;
    	}
    	return true;
    }
    
    private static function _getUserRecord($user_id)
    {
    	...
    	...
    	...
    	switch($user_id) {
    		...
    		...
    		...
    		default:
    			throw new UserException(UserErrors::DOESNOTEXIST);
    			break;
    	}
    }
    

    Now let’s try triggering these exceptions:

    $user = new User(1);
    try {
    	$user->user_email = 'invalid email';
    } catch( Exception $e ) {
    	echo "Donkey Kong has caught an exception with code: #{$e->getCode()}<br />";
    }
    
    try {
    	echo $user->setting_that_doesnt_exist;
    } catch( Exception $e ) {
    	echo "Donkey Kong has caught an exception with code: #{$e->getCode()}<br />";
    }
    
    try {
    	//user id that doesn't exist
    	$user = new User(3);
    } catch( Exception $e ) {
    	echo "Donkey Kong has caught an exception with code: #{$e->getCode()}<br />";
    }
    

    We should get something like this:

    Multiple exceptions

    You’re probably wondering — besides custom constructors, what benefits can we get from custom exceptions? It would be relatively simple to just use the default Exception class. But by using a custom exception, we can:

    • Override the __construct function and implement our own
    • Organize our exceptions by the type of object they are
    • And the best one of all: Use multiple catch blocks and catch different kinds of exceptions depending on type!
    Multiple Catch Blocks Catch Me If You Can!
    With multiple catch blocks, I will!
    Image courtesy of [movies.yahoo.com]

    By using multiple catch blocks, we are able to catch specific types of exceptions. This can be useful since we can indicate what to do when different kinds of exceptions occur. Currently, our try-catch functions catch the regular Exception type exceptions — this allows us to provide a fail-safe catch block for exceptions of types that have not been planned for.

    With that in mind, let’s create a try-catch function that will catch our custom exception, UserException, and do something different about it. Let’s also use another catch block to make sure that any other unexpected exceptions that are thrown will still be caught.

    try {
    	$user = new User(1);
    	$user->user_password = '123';
    } catch( UserException $e ) {
    	echo "Donkey Kong has caught a User Exception with code: #{$e->getCode()}<br />";
    } catch( Exception $e ) {
    	echo "Donkey Kong has caught a Exception with code: #{$e->getCode()}<br />";
    }
    
    try {
    	//when we use 'error' as the argument, the User class will simulate an
    	//unexpected exception from the SQL library
    	$user = new User('error');
    } catch( UserException $e ) {
    	echo "Donkey Kong has caught a User Exception with code: #{$e->getCode()}<br />";
    } catch( Exception $e ) {
    	echo "Donkey Kong has caught a Exception with code: #{$e->getCode()}<br />";
    }
    

    We should see the following output:

    Multiple Catch Blocks

    We can clearly see that the UserException and the regular Exception were handled differently, since they have different messages. It may not seem useful right now, but imagine being able to log only certain exceptions, or even create a custom exception called DisplayableException, which we can set so that they’re the only ones that users will be able to see.

    Conclusion Yaaaay
    Exceptions: Yaaaay
    Image courtesy of [memegenerator.net]

    With the power of PHP exceptions, we can simply and easily handle different kinds of errors. Hopefully, with the help of this tutorial, you’ll be able to build from our simple example and create an even more effective way of handling your application’s errors through PHP exceptions.

    Do you use exceptions in your applications? What kind of exceptions do you use? Let me know in the comments!


  • Permalink for 'How to Create a Web Service: Start to Finish – New on Premium'

    How to Create a Web Service: Start to Finish – New on Premium

    Posted: October 12th, 2011, 2:13pm MDT by Daniel Pataki

    There’s no two ways about it; putting together a website is hard! You need to know a myriad of programming languages (HTML, PHP, CSS, AJAX, Javascript, MySQL, just to name a few). You also must understand how to combine these tools into one cohesive whole, which is hopefully more than the sum of its parts. These days, we use frameworks, boilerplates and generators, but do you actually – when you get right down to it – know how to build a website from scratch?

    Become a Premium member to read this tutorial/screencast, as well as hundreds of other advanced tutorials and screencasts from the Tuts+ network.

    This tutorial is meant for those who can write a PHP function, know what jQuery is, can handle their CSS well, but would like some insider info on how a web service is built from scratch. How should I organize my files, where should I keep my functions, how should I start planning the thing, how should I connect to the database, how should I handle AJAX calls and how should I manage my 404 pages are just some of the questions I try to shed some light on here.

    Introduction

    The service we will be creating is called Bonsai Writer, a tool which will convert plain text into HTML. It is aimed mostly at writers but it can also be used as a note stash for more general use.

    Wireframe

    Become a Premium member to continue reading this tutorial, as well as hundreds of other advanced tutorials and screencasts from the Tuts+ network.


  • Permalink for 'Do You Suffer From the Dunning-Kruger Effect?'

    Do You Suffer From the Dunning-Kruger Effect?

    Posted: October 12th, 2011, 7:00am MDT by Jeffrey Way

    Charles Darwin once noted, “Ignorance more frequently begets confidence than does knowledge.” We all know the modern man to whom Darwin refers: the unemployed “musician” who must inform all new acquaintences that he is, in fact, a musician (multiple times). The XHTML and jQuery “expert,” who uses XHTML as a selling point.

    And if you don’t know this guy, maybe you are him!

    Dunning-Kruger

    It’s referred to as the Dunning-Kruger effect.

    The Dunning–Kruger effect is a cognitive bias in which unskilled people make poor decisions and reach erroneous conclusions, but their incompetence denies them the metacognitive ability to recognize their mistakes. The unskilled therefore suffer from illusory superiority, rating their ability as above average, much higher than it actually is, while the highly skilled underrate their own abilities, suffering from illusory inferiority.

    You don’t even know enough to realize just how little you know.

    I recently mentioned on Twitter that, from my experiences, those who label themselves as experts, more often than not… aren’t. This isn’t surprising; it stands to reason – to phrase it casually – that those who have the goods…don’t flaunt the goods! Alternatively, if one’s expertise is persistently revealed to you, by said expert, perhaps something is a few clicks off!

    A guitar teacher of mine in college, once – rightly so – informed me: “You don’t even know enough to realize just how little you know.”

    Little did my teacher know that this comment would stick with me for a long time. The irony, of course, is, despite the fact that years and years have passed since my conversation with him, his note still applies.

    Whether the craft be music or web development, I’m not even close to an expert. Or, as Willy Brown might say, I’m not even the beginnings of a pimple on the late great Robert Johnson’s ass.

    “Actual competence may weaken self-confidence, as competent individuals may falsely assume that others have an equivalent understanding. As Kruger and Dunning conclude, “the miscalibration of the incompetent stems from an error about the self, whereas the miscalibration of the highly competent stems from an error about others.”

    How to Detect a Self-Proclaimed Expert

    According to Wikipedia, for a given skill, self-proclaimed experts will:

    • tend to overestimate their own level of skill
    • fail to recognize genuine skill in others
    • fail to recognize the extremity of their inadequacy
    • recognize and acknowledge their own previous lack of skill, if they can be trained to substantially improve.

    Those who genuinely know their stuff are considerably modest, when compared to those who have a fraction of their experience and knowledge.

    Maybe the easiest way to detect a real expert is via that very word: “expert.” Is it inaccurate for me to argue that true experts rarely refer to themselves as such, if ever? There’s that idea again: “the more you know; the more you realize how little you know.”

    Everything’s relative, of course, but I’ve found that those who genuinely know their stuff are considerably modest, when compared to those who have a fraction of their experience and knowledge. Perhaps this is simple human nature. Blissful ignorance and dreams are many times preferable to actual work. It’s easier to brag about your next million dollar web application, than to actually create it. It’s more impressive to use the terms “gig” and “contract,” when you really mean, “freebie website for my sister.”

    So the question remains: why do some represent expertise, while others seemingly avoid the term? I suppose I can’t speak to the former, though I can provide some personal notes on the latter.

    • First and foremost, I know in my heart that I have a long way to go before I can even fathom embracing that label – if ever.
    • The term, “expert” is a vague one, and is entirely relative. Sure, to a high school student, maybe we are experts. To my personal web development heroes, I feel like a hack. I’m sure the chain continues indefinitely. This is precisely why it’s important to refrain from using these sorts of labels in most cases.
    • Particularly in our field, no one is an expert. The industry is too young, and advances at an alarming rate. There’s always new skills to acquire. I’d argue that those who understand this truth also understand that terms like “expert” are inappropriate.
    • On a more casual and social level, you come across as a jerk when you self-diagnose yourself this way. This is similar to continuously retweeting compliments. Let your work/code do the talking, and, if you genuinely deserve the label, others will be more than happy to assign it to you. This is the correct way to achieve “expert” status. It is given…not proclaimed.
    Is It Ever Okay to Call Yourself an Expert?

    Is it in poor taste to designate yourself as an expert? Ultimately, it’s just a word; do what you wish. I’m admittedly being a bit pedantic here.

    Christian Heilmann argues:

    “Sometimes, you need to call yourself an expert to reach people who are badly in need of information.”

    That’s certainly a valid case, and is particularly applicable when considering events like conferences and workshops. When you host a workshop, regardless of whether you label yourself as an expert, you assume that role. When it comes to spreading education, Christian is right: sometimes you must use these terms to attract those in need. And in these teacher-student relationships, you are the expert. No harm done.

    We also must consider simple marketing or SEO. To John Doe, who needs a website for his new business, it’s important to remind him that we are the “experts.” As more and more tools, which allow regular folks to create websites, are released, they should be made aware that others have dedicated their lives to learning this craft. Don’t risk the livelihood of your business, all for the sake of saving X dollars on the website. You are the expert. John Doe must know this. To the Layman, sure, abuse the term!

    However, among your peers, you might think twice before labeling yourself in this way.

    Arrogance is not inspiring.

    This is not to say that you shouldn’t be confident in your worth and abilities. Never devalue your worth to an employer or client. That said, though, unless you are one of the few truly exceptional veterans in our industry, stop patting yourself on the head, and get back to doing what we all must do in our free-time: learning. Whether you’re an industry veteran or a college student, we all share one commonality: we spend as much free time as possible desperately trying to remain relevant in this ever-expanding industry.

    Conclusion

    As a reader of Nettuts+, I think it’s safe to assume that, like me, you’re considerably aware of the skills you don’t yet have. Hopefully, Nettuts+ can help with that! Until next time, I’ll leave you with this quote:

    “One of the painful things about our time is that those who feel certainty are stupid, and those with any imagination and understanding are filled with doubt and indecision.” – Bertrand Russell


  • Permalink for 'Building Static Sites with Jekyll'

    Building Static Sites with Jekyll

    Posted: October 11th, 2011, 1:33pm MDT by Andrew Burgess

    A full-blown CMS is rarely necessary. Sometimes, you only need to create a light, static website … but you have just enough pages to make the process of copying template files and making cross-site markup changes a chore. Today, I’ll demonstrate a simple solution—Jekyll—that will make creating small websites a breeze.

    Step 0: Meeting Jekyll

    Jekyll is a simple, blog aware, static site generator.

    Jekyll is a simple, blog aware, static site generator. That’s what the site says. But, what exactly does this mean? A static site generator is a program that takes a set of files and generates your site with them. As you’ll see, we’ll be able to use a set of templates, create the content files separately, and then use Jekyll to generate our site. The “blog aware” part means that we could use this to create a blog, or any website that has a series of post-like entries (such as a portfolio). Let’s give it a try!

    Step 1: Installing Jekyll

    Refer here for more information on Ruby Gems.

    We’ll begin by installing Jekyll; it’s a Ruby gem, so doing so should be pretty straightforward.

    gem install jekyll # use `sudo` if your setup requires it

    Yep: it’s that easy. There are a few more pieces we could install if we are planning on doing a more complex set-up, however, since we’re not, this will do the trick.

    Step 2: Creating our First Template

    Every file or folder that does not begin with an underscore will be copied to the generated site.

    Next, let’s set up the folders for Jekyll. Create a folder, called example-app for this tutorial; we’ll be creating a little portfolio site for, say, a photographer. This is a great example of where Jekyll shines: it’s a small site that won’t be updated too frequently, but is large enough to the point that you don’t want to open every page when you need to make a markup change.

    Inside example-app, create a folder called _layouts. Notice the underscore at the beginning of this folder: any folder or file that begin with an underscore will not be part of the site that Jekyll generates. If they have a name that Jekyll recognizes (such as _config.yml or _layouts), their contents will be used in the generation of the site, but the files themselves won’t show up in the site. Remember this: every file or folder that does not begin with an underscore will be copied to the generated site (which, by the way, defaults to the _site sub-folder).

    So, let’s create a layout. We’ll start with a general site layout that includes all the “chrome” for our site. Create a new file, called default.html inside the _layouts folder (the name doesn’t matter), and add the following code to it:

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset=utf-8 />
      <title> {% if page.title %} {{ page.title }} | {% endif %} John Doe, Photographer </title>
      <link rel="stylesheet" href="/css/styles.css" />
    </head>
    <body>
    
      <div id="main">
    
        <header>
          <h1> John Doe Photograghy </h1>
        <header>
    
        <nav role="navigation">
          <ul>
            <li><a href="/">Home</a></li>
            <li><a href="/portfolio/">Portfolio</a></li>
            <li><a href="/about">About</a></li>
            <li><a href="/contact">Contact</a></li>
          </ul>
        </nav>
    
        {{ content }}
    
        <footer>
          <p>@copy; John Doe Photography 2011 | All Rights Reserved. </p>
        </footer>
    
      </div>
    </body>
    </html>
    

    A couple of things here to keep in mind…

    Firstly, Jekyll uses the Liquid template system (by default). This means, anything you can do with Liquid, you can do in a template in Jekyll. For example, in the <title> tag, we’re using both types of Liquid markup: output markup and tag markup. Output markup may output text (if the variable referenced exists), while tag markup doesn’t. Output markup is delimited by double curly-braces, while tag markup is delimited by a the curly brace / percent sign duo.

    The next thing to notice above is what is inside the Liquid tags: things like page.title and content. These are variables provided by Jekyll; you can see the list of available template data in the docs. We can also create custom template data, as we’ll review shortly.

    Lastly, notice the CSS we’re linking to: create a css folder in the root of your project and throw this bit of styling into a style.css file:

    body {
      font: 16px/1.5 verdana, helvetica-neue, helvetica, arial, san-serif;
      background: black;
      color: #ececec;
      padding: 0;
      margin: 0;
    }
    ul {
      margin: 0;
      padding: 0;
    }
    a {
      color: #ccc;
      text-decoration: none;
    }
    
    a:hover {
      color: #ececec;
      text-decoration: underline;
    }
    
    #main {
      width: 960px;
      margin: 0 auto;
      background: rgba(255, 255, 255, 0.4);
    }
    header {
      padding: 0 10px;
      overflow: hidden;
    }
    h1 {
      margin: 0;
    }
    
    nav ul, ul.entries {
      list-style-type: none;
    }
    nav li a {
      float: left;
      margin: 5px;
    }
    .content {
      padding: 10px;
    }
    
    ul.entries li {
      position: relative;
      margin: 20px auto;
      padding: 20px;
      background: #ececec;
      width: 600px;
    }
    
    ul.entries img {
      width: 600px;
    }
    
    ul.entries li h3 {
      position: absolute;
      bottom: -18px;
      left: 17px;
      font-size: 2em;
    }
    ul.entries a {
      color: #ececec;
    }
    ul.entries a:hover {
      color: #fff;
    }
    
    footer {
      font-size: 0.65em;
      text-align: center;
    }

    Also, create an img folder and add an image, named banner.jpg; we’ll be using it shortly. Any image will do; just crop it to 960px by 300px;.

    You might be wondering why we’re using the if statement above if the page.title variable just won’t display if it exists? Well, if it does exists, I want to include the vertical bar after it; another way to write that would be like this:

    {{ page.title }}{% if page.title %} | {% endif %}

    So, how we do use this template? Well, we need to create a page that will use this template. In the root directory of our project, create an index.html file. Here’s the content:

    ---
    layout: default
    ---
    <section role="banner">
      <img src="/img/banner.jpg" />
    </section>
    
    <section class="content">
      <p>
      Welcome to John Doe Photography! Please, check out my <a href="/portfolio/">Portfolio</a> to see my work.
      </p>
    </section>

    Here’s the content of our index.html file. Notice what’s at the top of the file: Jekyll calls this YAML front matter. Any file (that doesn’t start with an underscore) that has YAML front matter will be generated by Jekyll before being put in the _site folder (if it has no underscore or YFM, then it will just be copied _site). In this case, the YAML front matter just tells Jekyll what template we want it to use.

    Now, open a terminal, cd into your project directory, and run jekyll. You should see something like this:

    WARNING: Could not read configuration. Using defaults (and options).
    	No such file or directory - /Users/andrew/Desktop/example-app/_config.yml
    Building site: /Users/andrew/Desktop/example-app -> /Users/andrew/Desktop/example-app/_site
    Successfully generated site: /Users/andrew/Desktop/example-app -> /Users/andrew/Desktop/example-app/_site

    Ignore the warning; we’ll come to that shortly. For now, you can see that the site has been built in a freshly-created _site directory. If you open the _site/index.html file in your browser of choice, you should see … a failure. The problem is that our paths (urls and stylesheet) begin with a forward slash. This means we can’t just view them as files, we need to view them on a server. Sure, you could go start up W/MAMP, but why take the trouble? Jekyll has a built in server. So, run jekyll --server, and go to localhost:4000 to see something like image below:

    Tutorial Image

    If the image above isn’t enough, look at the code of _site/index.html. You’ll see that the template we specified was blended with the content we provided and—voila!—we have our page.

    I want to remind you that it’s the YAML front matter that makes this magic happen; if a file doesn’t start with three dashes, one or more lines of properties, and another line of three dashes, the file will just be copied to the _site folder, no generation taking place.

    Step 3: Creating a Portfolio Template

    Now that we’re comfortable with the basics, let’s create a portfolio for our fictional photographer. Remember how I noted that Jekyll is “blog aware”? Well, we’re going to use this blog-awareness feature to our advantage: instead of posts, we’ll have portfolio entries.

    Posts belong in a folder, called _posts, so create that now. The file name pattern for posts must be specific as well: year-month-day-title.ext. Posts — well, any file in your Jekyll site, really — can be either Markdown or HTML.

    So let’s make a few posts: remember, these will actually be entries in our portfolio:

    _posts/2010-03-04-bikes.md
    ---
    layout: portfolio_entry
    image: /img/bikes.jpg
    title: Bikes, Black and White
    ---
    Bikes are used by almost everyone in downtown Amsterdam. These ones are chained to a bike rack.
    _posts/2010-10-01-wing.md
    ---
    layout: portfolio_entry
    title: Wing and a Prayer
    image: /img/wing.jpg
    ---
    The wing of the AirBus I rode to England.
    _posts/2011-06-05-bridge.md
    ---
    layout: portfolio_entry
    title: Stone Bridge
    image: /img/bridge.jpg
    ---
    An old stone bridge in London.
    _posts/2011-07-09-road.md
    ---
    layout: portfolio_entry
    title: Road and Curb
    image: /img/road.jpg
    ---
    Bike lanes here are terribly thin.

    Pretty simple, eh? Notice how we’re creating a custom YAML front matter field: image. This is the URL to the image for that entry. Sure, we could build the whole entry HTML here in this file, but what if we want to change that? We’d have to return and change it in every entry. This way, we can instead use our portfolio_entry template to render them. What’s that template look like? It’s pretty simple too:

    _layouts/portfolio_entry.html
    ---
    layout: default
    ---
    
    <h2 class="content">{{page.title}}</h2>
    
    <img src="{{ page.image }}" />
    
    {{ content }}

    If you looked at the template data page, you’ll know that any custom front matter we add will be available under page; so, here, we can access page.image. We’re also using page.title and content (everything after the last three-dash line).

    I should mention here that, while the post title is supposed to be available on the post object, I’ve only been able to get it to work on the page object. Whatever works!

    Also, notice that we have this template using our default layout. You can nest templates like that, and make your job even easier.

    This gives us our entry (post) pages, but what about the main portfolio page? When writing our navigation in our default layout, I noted that we want it as /portfolio/. So, create a folder, called portfolio in the root directory, and open an index.html file within it.

    ---
    layout: default
    title: Portfolio
    ---
    
    <section class="content">
      <h2>Portfolio</h2>
    
      <p>Check out my images below!</p>
    </section>
    
    <ul class="entries">
      {% for post in site.posts %}
    
      <li>
        <a href="{{ post.url }}">
          <img src="{{ post.image }}" />
          <h3>{{ post.title }}</h3>
        </a>
      </li>
    
      {% endfor %}
    </ul>

    This is our most complicated piece yet. Remember, this isn’t a template: it’s a “normal” file, but it can still include Liquid tags. We start by setting layout to default, and title to “Portfolio.”

    Notice that, in the HTML, we have a Liquid for-in loop. We retrieve all the posts with sites.posts; then, we loop over those posts with for post in site.posts / endfor. If you’ve worked with WordPress, or any other blogging system, you should be familiar with the concept of a loop. That’s all this is! Inside, as you can see, we can get the standard properties, as well as any front matter we defined (like image).

    Now if we run jekyll --server to re-generate the site and start the server, localhost:4000/portfolio/ should show this:

    Tutorial Image

    And here’s an entry page:

    Tutorial Image

    Great! You’ve created a portfolio. I’m sure you see, as well, how this works for a blog. Let’s now move on to look at some configuration options for Jekyll.

    Step 4: Writing a Config File

    There’s a plethora of options for Jekyll. It’s great that all of them have really sensible defaults, but if you want to change them, it’s not hard at all.

    There are two ways to set options.

    • First, when you run the program on the command line, you can pass parameters. We’ve already seen the --server parameter, which starts a server after generating the site.
    • A different way, and the way we’ll use here, is in a config file, called _config.yml; this is a YAML file, so each line is a key: value pair, just like in the YAML front matter. Jekyll will look for this file before generating site.

    So, make an _config.yml file, and let’s check out some of the most common options.

    For a complete list of options, review the configuration documentation.

    • auto: Adding auto: true to your config file will keep Jekyll running, watching your project folder for changes and regenerating the site on the fly.
    • source: If your source files are in a different directory than the one you’re running Jekyll from, you’ll want to set that directory with the source property.
    • destination: By default, the destination for your generated site is ./_site. If you’d like something different, set it here.
    • permalink: The permalink is the path to your posts. By default, that’s /year/month/day/title.html. However, you can customize that if you want. Among others, you can use the variables :year, :month, :day, :title, and :categories. :categories comes from the front matter; all the others come from the post file name. Then, you can set permalink to things like /:year/:month/:title/ or /:categories/:title.html. Bonus tip: if you have a permalink property in the post front matter, it will override the site-wide default.
    • exclude: Like I said above, Jekyll won’t generate files in directories starting with an underscore. But, if you have folders that you want it to ignore, but that don’t start with an underscore, you can do it with exclude in your config file.
    Step 5: Deploying the Site

    So, let’s say you’ve created the site, and want to set it free, out on the world wide web. How do you do that?

    There are several ways to accomplish this. Of course, if it’s a small site that you won’t be updating too often, then simply FTP it up to your server; this might be your only option, if you’re using shared hosting.

    If you’ve got a VPS or dedicated hosting setup, you can run more automatically. Check out the deployment documentation for a list of good ideas. If you aren’t sure what to do, try following the directions for using the git post-receive hook; I’ve tried that, and it’s pretty cool.

    Step 6: Taking it Further

    This is just the tip of Jekyll.

    Conclusion

    Well, that’s your introduction to Jekyll – the simple, blog aware, static site generator. The next time you’re building a brochure-style, business-card-y, micro-portfolio site, think you’ll give Jekyll a try? Let me know in the comments and thank you so much for reading!


  • Permalink for 'The Intro to Rails Screencast I Wish I Had'

    The Intro to Rails Screencast I Wish I Had

    Posted: October 10th, 2011, 4:20pm MDT by Jeffrey Way

    Isn’t it funny how most “introduction to Ruby on Rails” screencasts are overly simplistic, and rely on generators like scaffolding? The teacher typically follows up the tutorial by stating that most Rails developer don’t use scaffolding generators. Well that’s not much help then! I’d like to give you the tutorial I wish I had. Along the way, we’ll also rely heavily on test-driven development to build a simple app.

    Choose HD for the clearest picture. Covered in this Screencast…
    • Create models and generators
    • Use test-driven development to plan and test an application’s features
    • Work with ActiveRecord
    • Autotest with Guard
    • Use Rspec and Capybara to simulate the user.
    • Create partials
    • Take advantage of Flash notices
    • …and plenty more
    Conclusion

    If you watched the entire screencast, I hope you enjoyed it! There’s certainly much more to cover, but we crammed a great deal into thirty minutes or so! What other tricks and techniques have you picked up, if you’re just digging into Rails?


  • Permalink for 'Announcing Windows AppStorm!'

    Announcing Windows AppStorm!

    Posted: October 10th, 2011, 10:13am MDT by David Appleyard

    We’re immensely pleased to announce that, after months of waiting, a new member of the AppStorm network has landed: Windows.AppStorm! Read on to find out more about what this fantastic new site has to offer…

    Complimenting Mac.AppStorm, Web.AppStorm, iPhone.AppStorm, iPad.AppStorm, and Android.AppStorm, our new Windows site will be offering reviews and roundups covering the entire Windows ecosystem, including Windows Phone 7, and games, along with tips and tricks to get the most from Windows.

    We know that many Tuts+ readers use Windows devices every day and want to provide you with a fantastic resource for everything Windows related. We’re incredibly excited to bring you excellent Windows content of the high quality you’ve come to expect from AppStorm – daily reviews, how-to’s, roundups, news, and opinion.

    Subscribe and Stay Up-to-Date!

    We have some absolutely fantastic posts lined up over the coming weeks, and we’d hate for you to miss out… There are a few different ways to subscribe to Windows.AppStorm – hopefully one of the following options will work for you!

    Get Stuck In Windows Reviews

    As a treat for all newcomers to Windows.AppStorm here are a some links to articles published in the interim, you won’t be disappointed!

    Head over to Windows.AppStorm…


  • Permalink for 'Design and Code an Integrated Facebook App'

    Design and Code an Integrated Facebook App

    Posted: October 7th, 2011, 2:54pm MDT by Aaron Lumsden

    Welcome to part three of “Design and Code an Integrated Facebook App.” At this point, I’m assuming that you have created the HTML and CSS for your app. If not, then refer to the first entry in this series. In this part, we’re going to take our app to the next level!

    Catch Up Overview

    In this lesson, we’ll take care of:

    • adding a few cool effects using the awesome jQuery library
    • setting up our app in the new Facebook app configuration panel as well as setting up Facebook’s PHP SDK.
    • Bringing in our data from Feedburner using Yahoos YQL api
    • Pulling data in from Facebooks graph api.

    So stick with me, make yourself a cup of tea, and happy coding!

    Step 1 – jQuery

    Before we begin with converting our HTML to PHP, we need to make a few of our HTML objects functional. We can do this quite easily using the jQuery library. If you haven’t started using the jQuery library yet, then now is definitely an excellent time to start. It’s a great introduction to Javascript and truthfully isn’t too difficult to use. In fact, you can create some great effects with only a few lines of code. In our blog app, we’re going to use jQuery for two things. Firstly, we’re going to use it for our live filter search, and secondly, for our page tabs to allow our users to have a smooth experience as they transition from page to page.

    If you remember from the previous tutorial, we included a JavaScript file into our HTML document header. Now it’s time to create that file. So jump into your favourite code editor, and call the file ‘myjava.js‘. We begin by creating the document ready. This tells jQuery to load everything inside it once the DOM is ready to be manipulated.

    The Tabs Facebook app tabs

    When the DOM is ready, we hide all the tabs. We then fade each page in when the corresponding tab is clicked on or made ‘active.’ We also remove the active class from the tabs and hide all of the other pages content.

    	var tabContent = $('.tab_content'), //Define the tab as a variable
         	tabs = $('ul.tabs li');		//Define the tabs li as a variable
    
    		tabContent.hide(); //On page load hide all the contents of all tabs
    		tabs.eq(0).addClass("active").show(); //Default to the first tab
    		tabContent.eq(0).show(); //Show the default tabs content
    
    	//When the user clicks on the tab
    	tabs.click(function(e) {
    		var li = $(this), //define this li as a variable
    			  activeTab = li.find('a'); //Get the href's attribute value (class) and fade in the corresponding tabs content
    
    		tabs.removeClass("active"); //Remove the active class
    		li.addClass("active"); //Add the active tab to the selected tab
    		tabContent.hide(); //Hide all other tab content
    
    		activeTab.fadeIn(); //Fade the tab in
    
    		e.preventDefault();
    	});
    
    Filter Search

    The next item we will use jQuery for is our filter search. This will allow our users to filter their search results in real time as they type. This is done by taking the live value of the form field and filtering it with anything that matches within our ‘posts’ divs. The filter will then show the ‘posts’ div that contain the value and hide any that don’t.

    	//Filter Search
    
    	$(".search").keyup(function () {
    		var $this = $(this),
    			  filter = $this.val(),
    			  count = 0;
    
    		$(".post").each(function () {
    			var $this = $(this);
    
    			if ($this.text().search(new RegExp(filter, "i")) < 0) {
    			   $this.hide();
    			} else {
    			 $this.show();
    			}
    		});
    
    		$("#filter-count").text(count);
    	});
    
    Step 2 – PHP

    Now it’s time to bring this static file to life and begin pulling in data from Facebook and Feedburner. Now is probably a good time to rename your file from index.html to index.php and download the PHP SDK. You can download the latest copy of Facebook’s PHP SDK from:

    Facebook PHP SDK

    Step 3 – Setting Up our Application Within Facebook Setting up application in Facebook

    Now we now need to setup our Facebook app canvas page. Although this has been covered before, Facebook has recently updated its app setup page; so it’s important to go through the new setup. Firstly, upload the index.php to your own web hosting account. Ive uploaded mine to a subfolder eg. www.yourdomain.com/tut When finished, you can setup your app by visiting [https:]] .

    At this point, click on the ‘create new app’ button in the top right corner. Enter the name of your app and you will then be taken to the setup page. Facebook allows you to create many variations of apps – from desktop to mobile. In our case, we need to choose the ‘App on Facebook’. There are five essential fields that you need to fill in in order for your app to work. They are highlighted in the image above. Once this has been done, if you go to apps.facebook.com, followed by whatever you entered into the ‘app namespace.’ In my case, this was ‘webdesigntuts’ so my app domain is: [apps.facebook.com]

    When you go to your url, you should see your index file within the canvas space on Facebook.

    Step 4 – Facebook PHP SDK Configuration and Setup

    After bringing the app into Facebook, it’s now time to pull in data from the Facebook graph API and allow people to login in and out of our app.

    In the directory for our app, add a new folder and call it ‘fb‘ Open the SDK folder that you downloaded from GitHub. In it, you should find a couple of examples: the src and some tests. Take the contents from the src folder and drag it into your fb folder. This is the bit we need in order to connect to Facebook. In our index.php file, add the code below starting with including the Facebook SDK from our ‘fb‘ folder, and add your unique app id and secret key. In the code below, you can see how this should be setup. We’re essentially connecting to Facebook and retrieving the user id of the person who is using our app. If the user has been authenticated, then we are generating a variable for the logout url or if they haven’t, we are generating one for the login url.

    <?php
    
    require 'fb/facebook.php';
    
    $fbconfig['appUrl'] = "The full url of your app on Facebook goes here"; 
    
    // Create An instance of our Facebook Application.
    $facebook = new Facebook(array(
      'appId'  => 'Your App ID',
      'secret' => 'Your App Secret',
      'cookies' => 'true',
    ));
    
    // Get the app User ID
    $user = $facebook->getUser();
    
    if ($user) {
    	  try {
    		// If the user has been authenticated then proceed
    		$user_profile = $facebook->api('/me');
    	  } catch (FacebookApiException $e) {
    		error_log($e);
    		$user = null;
    	  }
    }
    
    // If the user is authenticated then generate the variable for the logout URL
    if ($user) {
      $logoutUrl = $facebook->getLogoutUrl();
    
    ?>
    
    <!-- Insert Logged in HTML here -->
    
    <?php
    } else {
      $loginUrl = $facebook->getLoginUrl();
    }
    ?>
    

    Step 5 – Logging In and Out

    In between the if and else statement, we want to close and start the PHP tags so that we can insert our html that we created earlier into the PHP page. Now if you upload your page to your web space and refresh the Facebook app canvas, you should now be able to see the app. If you are logged in you will see it; otherwise, you will see a login url like in the image below

    Design and Code an Integrated Facebook App
     <a href="<?php echo $logoutUrl; ?>">Logout</a>
    

    We’ve setup our app within Facebook and have created a login and out for our users. All that’s left is to replace our dummy data with real live data.

    Step 6 – Pulling Data in from YQL using JSON

    Learn more about YQL.

    The first bit of data we’re going to pull into our app is the blog posts. This is pulled in from our Feedburner RSS feed. We collect it using YQL. If you haven’t used YQL before, then you should definitely try it out. It’s super simple to use and the flexibility that it offers is awesome. If you’re not familiar with it you can learn more about it here and here.

    What we’re basically doing is sending a request to YQL using similar syntax that might be used in MYSQL. We then decode the data that is returned into a JSON readable format, and store that in a variable so that we can retrieve specific parts of the array within our blog posts.

    We need to make three requests to YQL. They are as follows:

    • webdesigntuts-summary feed – this contains the majority of the data that we need for our blog posts. It contains the title, url, author, publish date and summary of the article.
    • webdesigntutsplus feed – the only information that we need from this is the comments count. We need to call this one as this data isn’t contained within the webdesigntuts-summary feed.
    • webdesigntuts-summary feed (again) – this time, instead of collecting all the data, we are only collecting the categories for use in the sidebar.

    This needs to be inserted before the closing PHP tag before our HTML starts. You can see this demonstrated in the code below:

    // The YQL query to get the Webdesigntuts+ summary posts from FeedBurner
    
    $yqlurl = " [query.yahooapis.com] $yqlurl .= urlencode("select * from feed where url='http://feeds.feedburner.com/webdesigntuts-summary' LIMIT 10");
    $yqlurl .= "&format=json";
    
    $yqlfeed = file_get_contents($yqlurl, true);
    $yqlfeed = json_decode($yqlfeed);
    
    // The YQL query to get the webdesigntuts+ posts from feedburner - We need this for the comments count only
    $yqlurl2 = " [query.yahooapis.com] $yqlurl2 .= urlencode("select * from feed where url='http://feeds.feedburner.com/webdesigntutsplus' LIMIT 10");
    $yqlurl2 .= "&format=json";
    
    $yqlfeed2 = file_get_contents($yqlurl2, true);
    $yqlfeed2 = json_decode($yqlfeed2);
    
    // The YQL query to get the webdesigntuts+ categories.
    $yqlurl3 = " [query.yahooapis.com] $yqlurl3 .= urlencode("SELECT category FROM feed WHERE url='http://feeds.feedburner.com/webdesigntuts-summary' LIMIT 10");
    $yqlurl3 .= "&format=json";
    
    $yqlfeed3 = file_get_contents($yqlurl3, true);
    $yqlfeed3 = json_decode($yqlfeed3);
    

    Step 7 – Getting the Number of Likes from a Facebook Page

    At this stage, we’re going to make a call to the Facebook graph API. It is similar to how we made the calls to YQL, however, there are a few slight variations between the two. This is really simple to do and should definitely be a section of code that you keep in your snippets folder as I’m sure it will come in handy. We set a variable of likes to = '0', make the call and then say; if the array that is returned contains ‘likes’ then set our likes variable to the number of likes that was returned.

    //Make a call to the facebook graph api and decode the json to collect the number of likes from the webdesigntuts+ facebook page
    
    $json_url ='https://graph.facebook.com/webdesigntutsplus';
    $json = file_get_contents($json_url);
    $json_output = json_decode($json);
    $likes = 0;
    if($json_output->likes){
    $likes = $json_output->likes;
    }
    

    Step 8 – Displaying the Dynamic Data Design and Code an Integrated Facebook App

    Now that we have all our data stored in PHP variables, we need to take that data and display it on our page. For our blog post, we do this by creating a simple for each loop and using $feed as the value. We can then echo out individual values from our JSON array by using the name of the part that we wish to echo. The YQL console should help you find these sections by using the tree mode.

      <?php
    
    //Create a variable that we can use to auto increment
    $i=0;
    
    //Loop out our yql feedburner feed
    
    foreach ($yqlfeed->query->results->item as $item ) { ?>
    	 <div class="post">
                 <h3><a  href="<?php echo $item->link;?>" target="_blank"><?php echo $item->title;?></a></h3>
                <span class="postInfo">by <a href="#"><?php echo $item->creator;?></a> on <?php echo substr($item->pubDate,0,-9);?></span>
                <p><?php echo $item->description;?></p>
                <a class="more" href="<?php echo $item->link;?>" target="_blank">Read More</a>
                <span class="line"></span>
    
                 <span class="blue"><?php echo $yqlfeed2->query->results->item[$i++]->comments[1]; ?> Comments </span>
    
                 <span class="line"></span>
            </div><!--End Blog Post-->
    
    	<?php }?>
    

    In the above block of code, note that we have echoed out the number of comments from ‘$yqlfeed2‘. The comments section has two parts: comment url, and comment number. The comment url is the first part(0), and the number of comments is the second, part[1]. We only require the number of comments. We also auto increment the item by setting ‘$i = 0,’ and then using ‘item[$i++]‘ By doing this, the item number will increment each time the post is looped out and will return the number of comments for each individual post.

    Another point to note is that we have used a built in PHP function, subtrsubstr($item->pubDate,0,-9). The reason why we have done this is due to some strange looking characters at the end of our date and time. This simply removes the last nine characters (-9), and leaves our date and time appearing as expected.

    Step 9 – Displaying the Username, Image and Number of Likes Design and Code an Integrated Facebook App

    Echoing the number of likes is simple; we created the variable, ‘$likes‘ earlier, so we simply need to echo it. The Facebook PHP SDK also automatically creates some variables for us; again it’s a simple case of echoing out. All we need to do is replace our dummy data with the dynamic data.

     <span class="likesCount"><?php echo $likes;?></span>
    <p>People like webdesigntuts+</p>
    
    <div class="tabHeader">Hi <?php echo $user_profile['name']; ?></div>
    
    <img class="profileimage" name="" src=" [https:] echo $user; ?>/picture" width="50" height="50" alt="">
    
    <p>We're glad you stopped by at webdesigntuts+. We hope you enjoy our blog</p>
    

    Step 9 – Displaying the Categories
      <div class="tabHeader">Categories on webdesigntuts+</div>
    
    <ul>
       <?php  foreach($yqlfeed3->query->results->item as $item) { ?>
       <li><a href=" [webdesign.tutsplus.com] echo str_replace(' ','+',$item->category);?>" target="_blank"><?php echo $item->category;?></a></li>
        <?php }?>
    </ul>
    

    In the above code, we simply loop through our YQL query contained in ‘$yqlfeed3‘. We also use another built in PHP function, str_replace. We use this to replace any spaces in our categories with a ‘+‘ sign. This is so that we won’t have broken links when we attempt to redirect the user to the categories on Webdesigntuts+.

    Step 10 – Final Tips and Tricks for Facebook Apps Automatically Resizing the Facebook App Canvas Space

    The first trick I’d like to show you helps us get around a bug in the Facebook canvas iframe. In your Facebook app settings, you can set it so that the iframe automatically resizes to fit your content; however, it also puts a horrible scrollbar next to your app to the right of Facebook’s sidebar. This doesn’t look too great, so we can solve this with a simple bit of JavaScript that can be placed just after our opening body tag. This will resize our canvas to fit the content, and the sidebar will be to the far right of Facebook as opposed to our app.

    <!--Resize Iframe-->
    <script src=" [connect.facebook.net] <script>
    
     FB.Canvas.setAutoResize(7);
    
     </script>
     <!-- End Resize Iframe-->
    
    Facebook App Login Popup Facebook app login popup

    The next trick I’d like to show you is, when a user first visits your app, they will be asked to login/authorize. Rather than simply displaying a link, we can have a Facebook popup authorization. You know the ones I’m talking about, I’m sure you’ve seen them a million times. This can be accomplished by adding another bit of JavaScript after our closing PHP else statement.

     $loginUrl = $facebook->getLoginUrl(array('redirect_uri' => $fbconfig['appUrl']));
      print "&gt;script>top.location.href = '$loginUrl';</script>"; &gt;
    

    Conclusion

    So that’s it folks! This brings our ‘Design and Code an Integrated Facebook App‘ series to a close. I hope you’ve had as much fun creating it as I’ve had writing about it.

    This September, at the annual F8 Conference, Facebook announced that they had just surpassed 800 million annual users. Way to go Facebook! As you can see, this is a great platform to promote yourself, your brand, or your product. What better way to utilise this than by creating your own native look and feel Facebook app. Facebook also announced, on the same day, the reinvention of user profiles, called Timeline. With Timeline comes a whole new additional way for apps to be integrated into a users profile/timeline.

    “The movies you quote. The songs you have on repeat. The activities you love. Now there’s a new class of social apps that let you express who you are through all the things you do.”

    Design and Code an Integrated Facebook App

    This is an exciting time for us app developers! If you have yet jumped in, what are you waiting for? Don’t merely think about building the next app, get off your butt and build it. I’ll look forward to seeing what you come up with and how you can take what you’ve learned, and put your own spin on it. Feel free to leave links to your apps and creations in the comments below.

    Until next time, happy designing and coding!


  • Permalink for 'Quick Tip – jQuery Newbs: Stop Jumping in the Pool'

    Quick Tip – jQuery Newbs: Stop Jumping in the Pool

    Posted: October 7th, 2011, 11:02am MDT by Jeffrey Way

    As editor of Nettuts+, I get to review a lot of code from tutorial submissions. Despite the fact that jQuery has been available for years now, there is still one frequent mistake that I see more than anything else.

    Example #1

    Consider the following bit of code:

    $('.nav a').click(function() {
      $(this).hide();
      $(this).css('color', 'red');
      $(this).show();
    
      alert('something else');
    
      $(this).hide();
    
      return false;
    });
    

    The code above is overly complicated for a variety of reasons. Don’t worry over what the code actually does (it’s gibberish). Instead, I want you to look at all of those references to $(this).

    Think of the DOM as a pool.

    Think of the DOM as a pool. Remember when you were a kid, and would dive into the pool for coins, while your parents acted like they were watching? That will be our real-world comparision.

    Every time you use $('.someClass'), jQuery jumps into the pool (DOM), and searches for that coin (or nodes). So, when you reference it multiple times within a function, that’s a lot of diving. Or, to cut the real-world comparison, it’s wasteful and unncessary. Why call upon jQuery if you don’t require it? You should perform what we call “caching.”

    $('.nav a').click(function(e) {
       var anchor = $(this);
    
       anchor
          .hide()
         .css('color', 'red')
         .show();
    
       alert('something else');
    
       anchor.hide();
    
       e.preventDefault();
    
    });
    

    This is much cleaner. While modern browser engines are incredibly fast these days, and will make up for your poor coding as best as possible, you should still strive to write efficient code, and keep from wasting all that energy jumping in the pool. Now, technically, if you pass jQuery a DOM node, like this, it doesn’t re-query the DOM. It simply returns a jQuery object.

    Just because the performance difference between the two will honestly be negligible, we write clean code for ourselves.

    Example 2

    Let’s consider a slightly more complicated example: tabs.

    $('.tabs li').css('position', 'relative');
    
    $('.tabs li').click(function() {
       $('.tabs li').removeClass('active');
       $(this).addClass('active');
       $(this).load('someHref', function() {} ); // example
       $(this).css('top', '1px');
    });
    

    This code is all over the place. It’s ugly, and inefficient. Fix number one is to get rid of all that CSS. You’d only place styling in your JavaScript if the values were created dynamically. For example, if you need to calculate the precise location an element should be on the screen, you could use .css('left', calculatedValue). In this case, it can all be exported to an external stylesheet. That leaves us with:

    $('.tabs li').click(function() {
       $('.tabs li').removeClass('active');
       $(this).load('someHref', function() {} ); // example
       $(this).addClass('active');
    });
    

    Next, again, why do we keep querying the DOM for .tabs li and $(this)? Stop jumping in the pool. Let’s “cache” the location of .tabs li.

    var tabs = $('.tabs li');
    
    tabs.click(function() {
       tabs.removeClass('active');
       $(this).load('someHref', function() {} ); // example
       $(this).addClass('active');
    });
    

    Better, but we’re still calling $(this) twice, which isn’t a huge deal. But, from my experiences, if you don’t nip it in the bud early, this number quickly increases.

    var tabs = $('.tabs li');
    
    tabs.click(function() {
       var tab = $(this);
       tabs.removeClass('active');
       tab.addClass('active')
         .load('someHref', function() {} ); // example
    });
    
    Filtering

    Another (slightly less optimized) option would be to use filtering.

    var tabs = $('.tabs li');
    
    tabs.click(function() {
       tabs.removeClass('active')
           .filter(this)
           .addClass('active')
           .load('someHref', function() {} ); // example
    });
    

    The difference in this case, is that, rather than referencing $(this), we’re using the filter() method to reduce the collection of list items down to only the one that was clicked.

    What You Should Take Away

    Yes, the world will not end if you reference $('.tabs) several times within a function. JavaScript engines are super fast these days. If you were to test the performance of doing so thousands of times, the difference in execution might be a couple hundred milliseconds. But still, the question remains: why would you?

    Sometimes, when we use massive abstractions like jQuery, it’s easy forget that $('.tabs') is an actual function that runs a good bit of code. It should also be noted that these concepts apply to JavaScript in general – not just jQuery.

    Use the caching techniques described above to write cleaner code…for yourself.


  • Permalink for 'What you Should be Excited About in jQuery UI 1.9'

    What you Should be Excited About in jQuery UI 1.9

    Posted: October 5th, 2011, 1:35pm MDT by Dan Wellman

    jQuery UI 1.8 has been around for a little while now. In fact, it’s currently on version 1.8.16. jQuery UI 1.9 is under active development and brings a number of new widgets to the table, along with the usual improvements in stability and performance.

    The biggest changes are, of course, the new widgets themselves, but there have also been modifications to some of the existing widgets. We’ll look at the new widgets first. The widgets are in the advanced stages of development, but you should be aware that the widget’s APIs are still subject to change until they are fully finalized.

    The Menu Widget

    The menu widget can be used standalone to transform a list of hyperlinks into a themeable, keyboard and mouse navigable menu

    The menu widget, previously part of the autocomplete widget, has been broken out into its own plugin for reuse in other components. It can be used standalone to transform a list of hyperlinks into a themeable, keyboard and mouse navigable menu, but is best used in conjunction with other widgets.

    It features the disabled option, which is shared by all jQuery UI widgets, as well as the position option which uses the position utility to position itself relative to another element. It exposes the standard set of methods; destroy, disable, enable, option and widget, as well as the unique method refresh which is used to update the menu when new items are added to it. It also fires a range of event hooks including create, focus, blur and select. The last three events are passed an object referring to the individual item that was focused, blurred or selected.

    Using the widget is extremely easy, of course. For example, we could transform a simple select box into something more attractive using the menu widget:

    We’ll need our script to read through the options in the <select> box we are replacing and build a new unordered-list which will serve as the base of the menu widget:

    <script>
    	(function ($) {
    
    	//cached els
    	var base = $("#selectmenu").hide(),
    		container = $("<div />", {
    			"class": "ui-menu-container ui-widget ui-widget-content ui-corner-all"
    		}),
    		label = $("<span />", {
    			id: "label",
    			text: "Choose..."
    		}).appendTo(container),
    			list = $("<ul />", {
    			id: "menu"
    		}),
    		item = $("<li />");
    
    	//build underlying list for menu
    	$.each(base.children(), function () {
    
    		var tempItem = item.clone();
    
    		$("<a />", {
    			href: "#",
    			text: $(this).text()
    		}).appendTo(tempItem);
    
    		tempItem.appendTo(list);
    	});
    
    	list.appendTo(container);
    
    	//build menu opener
    	$("<a />", {
    		"class": "ui-menu-trigger ui-widget-content ui-corner-all",
    		href: "#",
    		html: "&amp;#x25BC;",
    		click: function () {
    			$("#menu").slideDown();
    		}
    	}).appendTo(container);
    
    	container.insertAfter(base);
    
    	//init menu
    	$("#menu").hide().menu({
    		select: function (e, ui) {
    			//set selected index on hidden <select>
    			base.attr("selectedIndex", ui.item.index());
    
    			//update ui
    			$("#label").text(ui.item.text());
    			$("#menu").slideUp();
    		}
    	});
    
    } (jQuery));

    The first chunk of code caches a selector for the <elect> box and creates the elements that we’ll need. The next section uses jQuery’s each() method to read each <option> and create a corresponding <a> element for it. Once an entire list has been created, we can then initialize the menu widget using the list as its underlying structure. This is done using the menu() method and passing in a configuration object in order to use the select event, which is triggered every time a selection from the menu is made.

    Within our callback function, we first make sure we update the selectedIndex of the <elect> box our fancy menu is replacing. We can find out the index of whichever menu item was selected using the items property of the ui object passed to our function as the second parameter. We also update the text in our replacement and hide the menu.

    Obviously this is just a quick example to highlight how the menu widget can be used as part of another widget, not an instruction on creating jQuery UI widgets. For details of the CSS and HTML used, see the code download.

    The Menubar Widget

    The menubar widget is used to create a horizontal menu which supports any number of nested menus, menu icons, keyboard navigation and full theming.

    One of the new widgets in the library that makes use of the menu widget is the menubar, which is used to create a horizontal menu which supports any number of nested menus, menu icons, keyboard navigation and full theming.

    The best way to understand the role of the menubar is to see it in action; the underlying mark-up is simply an unordered list structure:

    <ul id="menu">
    	<li>
    		<a href="#">File</a>
    		<ul>
    			<li><a href="#">New</a></li>
    			<li><a href="#">Open</a></li>
    			<li><a href="#">Close</a></li>
    		</ul>
    	</li>
    	<li>
    		<a href="#">Edit</a>
    		<ul>
    			<li><a href="#">Undo</a></li>
    			<li><a href="#">Redo</a></li>
    		</ul>
    	</li>
    	<li>
    		<a href="#">View</a>
    		<ul>
    			<li><a href="#">Home Screen</a></li>
    			<li>
    				<a href="#">Zoom</a>
    				<ul>
    					<li><a href="#">150%</a></li>
    					<li><a href="#">120%</a></li>
    					<li><a href="#">100%</a></li>
    					<li><a href="#">80%</a></li>
    					<li><a href="#">50%</a></li>
    				</ul>
    			</li>
    		</ul>
    	</li>
    </ul>

    A <ul> element is all we need. Any number of sub-menus can be used which are represented by nested <ul> elements. To initialize the widget, all we need to do is call the widget’s menubar() method:

    $("#menu").menubar();

    That’s it; that one line of code will initialize the widget and transform our list into an attractive menubar:

    To change the appearance of the top-level menu items, so that they look like buttons, and/or to add sub-menu indicators, we can use the buttons and menuIcon configuration options within the menubar() method:

    $("#menu").menubar({
    	menuIcon: true,
    	buttons: true
    });

    The other configuration options we can use are autoExpand, which makes the submenus appear on hover instead of click, and position, which allow us to position the widget wherever we like in relation to another element. This option hooks into the separate position widget, just like it uses the menu widget to create the submenus.

    At this point, the submenu items don’t actually do anything, so other than looking pretty, it actually does nothing. To change that we can use the select event which the underlying menu widget exposes to execute arbitrary code that makes the menu function. This widget only exposes the standard suite of methods; destroy, disable, enable, option and widget.

    The Spinner

    The spinner widget is a great new addition to the library; its premise is simple, but its effect is great and I think I’m not alone in saying that I’ve been waiting for it to appear for some considerable time!

    It adds up and down buttons to a text <input> so that its value can be incrementally increased or decreased without typing; an instant win for the user-experience.

    Let’s see it in action; for the default behaviour, all we need is a simple <input> on the page (with an id of spinner in the example), and a tiny bit of script:

    <script>
        (function () {
            $("#spinner").spinner()
        } (jQuery));
    </script>

    This gives us the attractive and fully keyboard-accessible spinner:

    The API for spinner is extensive with a range of configurable options, custom events and methods. The options we can use to configure the widget are as follows:

    • incremental
    • max
    • min
    • numberFormat
    • page
    • step

    The unique methods we can use to trigger specialist behaviour in the widget include:

    • stepUp
    • stepDown
    • pageUp
    • pageDown
    • value

    There are also some custom events we can use to hook into key interaction, which are as follows:

    • change
    • spin
    • start
    • stop
    Rich Tooltips

    The tooltip widget allows us to create rich, attractive tooltips using, by default, the title attribute. Any element that can have a title attribute can have a tooltip added, providing helpful supplementary information to a form using simple links.

    <label>Name:</label><input /><a href="#" class="tip" title="Your actual name, you don't need help with that right..?">?</a>
    <label>Age:</label><input /><a href="#" class="tip" title="The length of your existence">?</a>

    Then all we need to do is call the tooltip method on our elements:

    $(".tip").tooltip();

    This will generate tooltips using the title attributes of the elements:

    As well as using the title attribute, we can use the content configuration option to specify an alternative means of adding content to the tooltip, we could use the text content of a hidden <span> element for example:

    <label>BMI:</label><input /><a href="#" class="alt-tip" title="This will not be used">?</a>
    <span id="bmi">To calculate your BMI simply divide your height in Kilograms by your height in metres squared<span>
    
    $(".alt-tip").tooltip({
    	content: function () {
    		return $("#bmi").text();
    	},
    	position: {
    		my: "center bottom",
    		at: "center top"
    	}
    });

    Now the tooltip will take the text content of our <span>:

    We also use the position configuration option to reposition the tooltip in this example.

    Popups

    The popup widget should also be ready for the 1.9 release. Like the menu widget that we looked at earlier, the popup is a low-level widget that is designed to be used by other widgets.

    It’s actually even more low-level that the menu and has no visible UI itself. It will eventually form the basis of all widgets that show any kind of popup, so expect to see it listed as a dependency for the menu, the tooltip and probably other widgets such as the dialog.

    Summary

    jQuery UI 1.9 will be a special release, much like 1.7 was a couple of years ago. Not only does it bring new widgets to the UI toolkit at our disposal, bug fixes and performance enhancements, it will also bring many changes to the API of each individual widget.

    jQuery UI is currently undergoing a huge rewrite, with all existing widgets recreated with new, simplified APIs that will make learning and extending the library much easier, with these changes culminating in version 2.0. Some of these rewrites will introduce breaking changes to existing widgets. This is unavoidable, and in fact, is essential if we wish to see the library progress, but to make the transition easier rewritten widgets will continue to function using existing syntax throughout the life-cycle of 1.9 and the old APIs will not be fully removed (where possible) until the 2.0 release.

    So this is the beginning of a hugely exciting time for users of jQuery UI, with new widgets appearing, better APIs and improved performance and a general refinement to all aspects of the official UI library for jQuery.



  • Permalink for 'Getting Real-Time with Pusher'

    Getting Real-Time with Pusher

    Posted: October 4th, 2011, 9:26am MDT by Nikko Bautista

    Do you want to spice up your web applications by making them real-time — but don’t want to create new infrastructures for the sole purpose of getting web sockets to work? In this article, we’ll explore how to use and implement Pusher, an HTML5 WebSocket-powered real-time messaging service for your applications.

    Introduction What are WebSockets?

    WebSocketAccording to the WebSocket Wikipedia page, WebSocket is a technology providing for bi-directional, full-duplex communication channels, over a single TCP socket.

    WebSockets Illustration by Pusher

    In layman’s terms, WebSockets enable a client and a server to communicate in both directions. It lets a server send messages to the client, and vice-versa.

    How is this relevant to my web application?

    Over the years, data expiration has always been a problem with web applications, specifically those that have multiple people logged in and working on the same things. For example, in a project management application, users sometimes create to-do items which their team members are creating at the same time. With WebSockets, this can be mitigated by allowing the server to push notifications to all connected parties, allowing browsers to receive new data in real-time. In effect, before you create a duplicate to-do item, you’ll see that someone else has already created it.

    What is Pusher? Pusher

    Pusher is a hosted API for quickly, easily and securely adding scalable real-time functionality via WebSockets to web and mobile apps.

    Essentially, Pusher encapsulates WebSockets implementation, functionality, debugging, and hosting for you.
    Instead of having to run your own WebSockets server, it allows you to offload the entire process to Pusher’s servers, saving you both time and money.

    Pusher is a hosted API for quickly, easily and securely adding scalable real-time functionality via WebSockets to web and mobile apps.

    For Pusher to work, you’ll need both a client library and a publisher library. Client libraries are used with the client that’s interfacing with your application. This might be a browser (via JavaScript), an iPhone app (via Objective-C), or a Flash app (via ActionScript). Publisher libraries are used on your server to send events to your clients.

    Currently, Pusher has client libraries for JavaScript, Objective-C, ActionScript, .NET and Silverlight, Ruby, and Arduino. It has publisher libraries for Node.js, Java, Groovy, Grails, Clojure, Python, VB.NET, C#, PHP, Ruby, Perl, and ColdFusion.

    For the purposes of this tutorial, we’ll be using the JavaScript client library and the PHP publisher library. The implementation shouldn’t be too different if you’re using another programming language.

    I feel like building a live chat widget so people can chat in real-time on a website. With this in mind, let’s continue.

    Setting up Pusher Step 1: Register for a free Pusher developer account

    To begin, go to the Pusher website and register for your account. They offer a free account for Sandbox plan users, which includes 20 connections and 100,000 messages per day. When you’re ready, you can always upgrade to a paid plan, but since we’re only going to use it for our sample application, a free Sandbox plan will do the trick!

    Pusher Registration

    Pusher Registration

    On the site, click on the Sign Up button that you’ll find on the top-right corner and enter the required details. Once done, click on the Sign Up button again to complete your registration.

    Step 2: Log in for the first time

    After you register, you’ll be redirected to your Pusher Administration page. This is where you can manage all your Pusher applications. A single account can host multiple applications.

    Pusher Adminstration Page

    Pusher Administration Page

    On top, you have your navigation bar, where you will find the following sections:

    • Dashboard – this is where you’ll see your Pusher application’s statistics. You can see the Message Rate (number of messages sent per minute), Connections (number of open connections at a certain time), and Messages (total messages your application sends per day).
    • Edit – here, you can rename the current application and choose whether or not to use SSL encryption.
    • API Access – this contains your application’s API Credentials, which we’ll require later.
    • Debug – this will display all the events triggered and messages sent by your Pusher application, as well as when clients connect or disconnect. This is extremely useful when developing your web app, since you can see here exactly what Pusher sends and receives and who’s online to receive them.
    • Event Creator – this is a useful tool for sending test events to your connected clients — without having to trigger the events yourself from your web application.

    You’re now ready to begin developing with Pusher!

    Developing with Pusher Step 1: Create the HTML, CSS, JavaScript, and PHP

    Let’s begin developing our live chat widget by creating the HTML. What I have in mind is a widget that will appear at the bottom of the screen, with a “Who’s Online” list on the side, like IRC.

    <!DOCTYPE HTML>
    <html>
    <body>
    	<div id="chat_widget_container">
    		<div id="chat_widget_login">
    			<label for="chat_widget_username">Name:</label>
    			<input type="text" id="chat_widget_username" />
    			<input type="button" value="Login!" id="chat_widget_login_button" />
    			<img src=" [d2o0t5hpnwv4c1.cloudfront.net] alt="Logging in..." id="chat_widget_login_loader" />
    		</div>
    
    		<div id="chat_widget_main_container">
    			<div id="chat_widget_messages_container">
    				<div id="chat_widget_messages">
    					chat messages go here
    				</div>
    			</div>
    			<div id="chat_widget_online">
    				<p>Who's Online (<span id="chat_widget_counter">0</span>)</p>
    				<ul id="chat_widget_online_list">
    					<li>online users go here</li>
    				</ul>
    			</div>
    			<div class="clear"></div>
    			<div id="chat_widget_input_container">
    				<form method="post" id="chat_widget_form">
    					<input type="text" id="chat_widget_input" />
    					<input type="submit" value="Chat" id="chat_widget_button" />
    					<img src=" [d2o0t5hpnwv4c1.cloudfront.net] alt="Sending..." id="chat_widget_loader" />
    				</form>
    			</div>
    		</div>
    	</div>
    </body>
    </html>
    

    Some CSS to style our HTML:

    #chat_widget_container{padding:20px 20px 5px 20px; background-color:#F2F2F2; border:5px solid #AFAFAF;
    border-bottom:0px; width:333px; font-size:11px; font-family:"Lucida Grande",Arial,Helvetica,sans-serif;
    position:fixed; bottom:0px; right:20px}
    
    #chat_widget_login{width:333px; text-align:center; height:166px; margin-top:80px}
    
    #chat_widget_main_container{display:none}
    
    #chat_widget_messages_container{float:left; width:200px; border:1px solid #DDD; height:200px; overflow:auto;
    padding:5px; background-color:#FFF; position:relative}
    
    #chat_widget_messages{overflow-x:hidden; overflow-y:auto; position:absolute; bottom:0px}
    
    #chat_widget_online{width:100px; height:210px; float:left; padding:0px 10px; border:1px solid #DDD;
    border-left:0px; background-color:#FFF; overflow: auto;}
    
    #chat_widget_online_list{list-style:none; padding:0px}
    
    #chat_widget_online_list >li{margin-left:0px}
    
    #chat_widget_input_container{margin-top:10px; text-align:left}
    
    #chat_widget_input{width:260px; margin-right:10px; border:1px solid #DDD; padding:2px 5px}
    
    #chat_widget_loader{display:none}
    
    #chat_widget_login_loader{display:none}
    
    .clear{clear:both}
    

    The combined HTML and CSS above should render something along the lines of:

    Demo Login

    Demo Login

    We’ll need to create a function that triggers when we click the Login button and checks the value entered, so let’s do that:

    $('#chat_widget_login_button').click(function() {
    	$(this).hide(); //hide the login button
    	$('#chat_widget_login_loader').show(); //show the loader gif
    	username = $('#chat_widget_username').val(); //get the username
    	username = username.replace(/[^a-z0-9]/gi, ''); //filter it
    	if( username == '' ) { //if blank, then alert the user
    		alert('Please provide a valid username (alphanumeric only)');
    	} else { //else, login our user via start_session.php
    		ajaxCall('start_session.php', { username : username }, function() {
    			//We're logged in! Now what?
    		});
    	}
    });
    

    Next, we need to inform the server when we’ve logged in. To do this, we’ll create a start_session.php file which will essentially log in the user.

    <?php
    //Start a PHP session
    session_start();
    
    //Get the username sent from the user
    $username = $_REQUEST['username'];
    
    //filter it
    $username = trim(filter_var($username, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES));
    
    //set the username for the session
    $_SESSION['username'] = $username;
    
    //set a unique id for the user. since we don't have a working user system, we'll just use the time()
    //variable to generate a unique id, and add the user's name to it and the user's session id, then
    //MD5 the whole thing
    $_SESSION['userid'] = md5(time() + '_' + $username + '_' + session_id());
    
    //echo the json_encoded success message for our ajax call
    echo json_encode(array('success' => true));
    exit();
    ?>
    

    You’ll notice that I’ve created an ajaxCall function, which basically just wraps around the jQuery $.ajax function. Just add this before the $(document).ready() line.

    function ajaxCall(ajax_url, ajax_data, successCallback) {
    	$.ajax({
    		type : "POST",
    		url : ajax_url,
    		dataType : "json",
    		data: ajax_data,
    		time : 10,
    		success : function(msg) {
    			if( msg.success ) {
    				successCallback(msg);
    			} else {
    				alert(msg.errormsg);
    			}
    		},
    		error: function(msg) {
    		}
    	});
    }
    

    Now, let’s load the Pusher JavaScript library and jQuery as well. Place the following script references within the <head> of your HTML:

    <script src=" [js.pusherapp.com] <script src=" [https:] 
    Step 2: Take note of your API Credentials

    Remember the API Access page from above? Go back to it and note down your API Credentials. We’ll need these values when we set up the client and publisher libraries.

    Pusher API Credentials

    Pusher API Credentials

    Feel free to use mine, however, I highly recommend you get your own, since a free account is limited and you might be cut off midstream.

    Step 3: Implement the Pusher code

    Before we begin implementing Pusher into our application, we need to understand some Pusher terms:

    • Channel – a way of differentiating streams of data inside an application. An application can have multiple channels, and one channel can have multiple clients. We can compare this with a chat room in IRC — all messages sent to a specific chat room can be seen by all the people who are inside.
    • Events – This is akin to the server sending data to the client so you can view messages in the chat room. Events are triggered by the publisher library, and clients can subscribe to these events. In our analogy, subscribing to an event is similar to listening when people chat in the room and taking note of what they’re saying.

    There are three types of channels:

    • Public channels – channels that anybody can subscribe to, as long as they know the channel’s name.
    • Private channels – channels that only authenticated users can subscribe to.
    • Presence channels – similar to private channels, but also allow us to notify other connected clients with information about the client connecting. We’ll be using this channel in our chat widget.

    Presence channels are special since they let us send information about users when they connect. They also have special events that we can subscribe to in order to know when a user connects and disconnects. Presence channels are ideal for secure, private channels that need to know when a user goes in or out.

    Connecting to the Pusher service

    Let’s begin by connecting our client to the Pusher service. To do so, we’ll need to create a new instance of the Pusher object (from the library), and call the subscribe function. Add the following code after the //We're logged in! Now what? comment.

    The Subscribe function essentially makes the client join the channel. Once inside the channel, the client will be able to receive events that are happening inside it.

    pusher = new Pusher('12c4f4771a7f75100398'); //APP KEY
    Pusher.channel_auth_endpoint = 'pusher_auth.php'; //override the channel_auth_endpoint
    nettuts_channel = pusher.subscribe('presence-nettuts'); //join the presence-nettuts channel
    
    What’s a “channel_auth_endpoint”?

    When subscribing to a presence or private channel, we need to ensure that the connecting user is allowed to access the channel. Therefore, before letting the client fully connect to it, the Pusher client automatically makes a call to the URL defined in the channel_auth_endpoint variable and sends it information about the user connecting. Then, through channel_auth_endpoint, we can figure out if the connecting user is authorized.

    By default, this call is made to /pusher/auth, but we can override it by setting the channel_auth_endpoint variable.

    Pusher Authentication Sequence

    A unique socket_id is generated and sent to the browser by Pusher. When an attempt is made to subscribe to a private- or presence- channel the socket_id and channel_name is sent to your application, (1) via an AJAX POST request which authorizes the user to access the channel against your existing authentication system. If successful your application returns an authorization string to the browser signed with your Pusher secret. This is sent to Pusher over the WebSocket, which completes the authorization (2) if the authorization string matches.

    Going back to our application, we need to create our channel_auth_endpoint. Create a file, called pusher_auth.php and place this inside:

    <?php
    //Start the session again so we can access the username and userid
    session_start();
    
    //include the pusher publisher library
    include_once 'Pusher.php';
    
    //These values are automatically POSTed by the Pusher client library
    $socket_id = $_POST['socket_id'];
    $channel_name = $_POST['channel_name'];
    
    //You should put code here that makes sure this person has access to this channel
    /*
    if( $user->hasAccessTo($channel_name) == false ) {
    	header('', true, 403);
    	echo( "Not authorized" );
    	exit();
    }
    */
    
    $pusher = new Pusher(
    	'12c4f4771a7f75100398', //APP KEY
    	'51399f661b4e0ff15af6', //APP SECRET
    	'8896' //APP ID
    );
    
    //Any data you want to send about the person who is subscribing
    $presence_data = array(
    	'username' => $_SESSION['username']
    );
    
    echo $pusher->presence_auth(
    	$channel_name, //the name of the channel the user is subscribing to
    	$socket_id, //the socket id received from the Pusher client library
    	$_SESSION['userid'],  //a UNIQUE USER ID which identifies the user
    	$presence_data //the data about the person
    );
    exit();
    ?>
    

    Now that we can authenticate our connecting users, we’ll need to bind some JavaScript functions to Pusher events to show that we’ve already logged in. Update the code below the //We're logged in! Now what? comment, like so:

    //We're logged in! Now what?
    pusher = new Pusher('12c4f4771a7f75100398'); //APP KEY
    Pusher.channel_auth_endpoint = 'pusher_auth.php'; //override the channel_auth_endpoint
    nettuts_channel = pusher.subscribe('presence-nettuts'); //join the presence-nettuts channel
    
    pusher.connection.bind('connected', function() { //bind a function after we've connected to Pusher
    	$('#chat_widget_login_loader').hide(); //hide the loading gif
    	$('#chat_widget_login_button').show(); //show the login button again
    
    	$('#chat_widget_login').hide(); //hide the login screen
    	$('#chat_widget_main_container').show(); //show the chat screen
    
    	//here, we bind to the pusher:subscription_succeeded event, which is called whenever you
    	//successfully subscribe to a channel
    	nettuts_channel.bind('pusher:subscription_succeeded', function(members) {
    		//this makes a list of all the online clients and sets the online list html
    		//it also updates the online count
    		var whosonline_html = '';
    		members.each(function(member) {
    			whosonline_html += '<li class="chat_widget_member" id="chat_widget_member_' +
    			member.id + '">' + member.info.username + '</li>';
    		});
    		$('#chat_widget_online_list').html(whosonline_html);
    		updateOnlineCount();
    	});
    
    	//here we bind to the pusher:member_added event, which tells us whenever someone else
    	//successfully subscribes to the channel
    	nettuts_channel.bind('pusher:member_added', function(member) {
    		//this appends the new connected client's name to the online list
    		//and updates the online count as well
    		$('#chat_widget_online_list').append('<li class="chat_widget_member" ' +
    		'id="chat_widget_member_' + member.id + '">' + member.info.username + '</li>');
    		updateOnlineCount();
    	});
    
    	//here, we bind to pusher:member_removed event, which tells us whenever someone
    	//unsubscribes or disconnects from the channel
    	nettuts_channel.bind('pusher:member_removed', function(member) {
    		//this removes the client from the online list and updates the online count
    		$('#chat_widget_member_' + member.id).remove();
    		updateOnlineCount();
    	});
    });
    

    Remember to add the updateOnlineCount(); function above the $(document).ready() line:

    function updateOnlineCount() {
    	$('#chat_widget_counter').html($('.chat_widget_member').length);
    }
    
    An explanation of what we just added

    The pusher.connection.bind function allows us to bind a callback function whenever the Pusher connection status changes. There are many possible statuses, such as initialized, connecting, unavailable, failed, and disconnected. We won’t be using them in this tutorial, but you can read more about them in the Pusher documentation.

    The channel_name.bind function allows us to bind a function to a specific event that might happen inside the channel. By default, presence channels have events of their own which we can bind functions to, like the pusher:subscription_succeeded event which we used above. You can read more about them in the Client Presence Events documentation.

    Let’s test out the app now and see what happens. To do so, open two tabs of your app and log in twice. You should see something like this:

    First Test

    First Test

    When you close one tab, the second client closes as well, triggering our pusher:member_removed event, and removing the client from the online list:

    Second Test

    Second Test

    Now that that’s working, we can finally implement the core functionality of our application — the live chat.

    Implementing the live chat functionality

    Let’s begin by binding a function to the submit event of our chat form:

    $('#chat_widget_form').submit(function() {
      var chat_widget_input = $('#chat_widget_input'),
      		chat_widget_button = $('#chat_widget_button'),
      		chat_widget_loader = $('#chat_widget_loader'),
    
      		message = chat_widget_input.val(); //get the value from the text input
    
    	chat_widget_button.hide(); //hide the chat button
    	chat_widget_loader.show(); //show the chat loader gif
    
    	ajaxCall('send_message.php', { message : message }, function(msg) {
    		//make an ajax call to send_message.php
    		chat_widget_input.val(''); //clear the text input
    		chat_widget_loader.hide(); //hide the loader gif
    		chat_widget_button.show(); //show the chat button
    
    		newMessageCallback(msg.data); //display the message with the newMessageCallback function
    	});
    
    	return false;
    });
    

    The newMessageCallback function:

    function newMessageCallback(data) {
    	if( has_chat == false ) { //if the user doesn't have chat messages in the div yet
    		$('#chat_widget_messages').html(''); //remove the contents i.e. 'chat messages go here'
    		has_chat = true; //and set it so it won't go inside this if-statement again
    	}
    
    	$('#chat_widget_messages').append(data.message + '<br />');
    }
    

    Afterward, we’ll need to create send_message.php to receive our AJAX call from above and trigger the new_message event:

    <?php
    //Start the session again so we can access the username
    session_start();
    
    //include the pusher publisher library
    include_once 'Pusher.php';
    
    $pusher = new Pusher(
    	'12c4f4771a7f75100398', //APP KEY
    	'51399f661b4e0ff15af6', //APP SECRET
    	'8896' //APP ID
    );
    
    //get the message posted by our ajax call
    $message = $_POST['message'];
    
    //trim and filter it
    $message = trim(filter_var($message, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES));
    
    //wrap it with the user's name when we display
    $message = "<strong>&lt;{$_SESSION['username']}&gt;</strong> {$message}";
    
    //trigger the 'new_message' event in our channel, 'presence-nettuts'
    $pusher->trigger(
    	'presence-nettuts', //the channel
    	'new_message', //the event
    	array('message' => $message) //the data to send
    );
    
    //echo the success array for the ajax call
    echo json_encode(array(
    	'message' => $message,
    	'success' => true
    ));
    exit();
    ?>
    

    You’re probably wondering why we abstracted the newMessageCallback into its own function. Well, we’ll have to call it again when we receive a new_message event from Pusher. The following code binds a function to an event, called new_message, which will trigger every time a user sends a message. Add this code after the nettuts_channel.bind('pusher:member_removed') code block:

    nettuts_channel.bind('new_message', function(data) {
    	newMessageCallback(data);
    });
    

    The data variable in the binding function above will be the data the server sends in the $pusher->trigger() call, which should contain the message data.

    Testing

    Let’s try our app again with two browsers, not tabs. (Or try it with a friend if you’ve uploaded it somewhere.)

    Working Demo

    Hello friend!

    Congratulations! You’ve successfully created a working application using Pusher.

    Conclusion

    There you have it, a working real-time application powered by Pusher. Feel free to visit the live chat demo I’ve set up here.

    There’s a lot more that I didn’t discuss in this tutorial, such as debugging your apps, excluding recipients from events, and triggering client-side events, but you can learn these simply by reading the Pusher documentation. You can even check out their showcase of websites and applications that use Pusher to work in real-time.

    This tutorial only scratches the surface of Pusher and WebSockets in general. With this kind of technology, what you can do is only limited by what you can imagine building.

    Have you tried creating something with Pusher, or are you planning to do so soon? Let me know in the comments!

    Note: Pusher has requested that we reset the API Credentials used by the demo account on this tutorial as a precaution to it being abused. I apologize to you guys and hopefully you can just get your own :) Thanks!


  • Permalink for 'How to Use Omniauth to Authenticate your Users'

    How to Use Omniauth to Authenticate your Users

    Posted: October 3rd, 2011, 2:22pm MDT by Ian Murray

    I hate signing up for websites. I’ve already signed up for so many, using different usernames, that going back to one of them and trying to remember my credentials is sometimes impossible. These days, most sites have begun offering alternative ways to sign up, by allowing you to use your Facebook, Twitter or even your Google account. Creating such an integration sometimes feels like a long and arduous task. But fear not, Omniauth is here to help.

    Omniauth allows you to easily integrate more than sixty authentication providers, including Facebook, Google, Twitter and GitHub. In this tutorial, I’m going to explain how to integrate these authentication providers into your app.

    Step 1: Preparing your Application

    Let’s create a new Rails application and add the necessary gems. I’m going to assume you’ve already installed Ruby and Ruby on Rails 3.1 using RubyGems.

    rails new omniauth-tutorial
    

    Now open your Gemfile and reference the omniauth gem.

    gem 'omniauth'
    

    Next, per usual, run the bundle install command to install the gem.

    Step 2: Creating a Provider

    In order to add a provider to Omniauth, you will need to sign up as a developer on the provider’s site. Once you’ve signed up, you’ll be given two strings (sort of like a username and a password), that needs to be passed on to Omniauth. If you’re using an OpenID provider, then all you need is the OpenID URL.

    If you want to use Facebook authentication, head over to developers.facebook.com/apps and click on “Create New App”.

    Facebook New App

    Fill in all necessary information, and once finished, copy your App’s ID and Secret.

    Facebook Secret

    Configuring Twitter is a bit more complicated on a development machine, since they don’t allow you to use “localhost” as a domain for callbacks. Configuring your development environment for this kind of thing is outside of the scope of this tutorial, however, I recommend you use Pow if you’re on a Mac.

    Step 3: Add your Providers to the App

    Create a new file under config/initializers called omniauth.rb. We’re going to configure our authentication providers through this file.

    Paste the following code into the file we created earlier:

    Rails.application.config.middleware.use OmniAuth::Builder do
      provider :facebook, YOUR_APP_ID, YOUR_APP_SECRET
    end
    

    This is honestly all the configuration you need to get this going. The rest is taken care of by Omniauth, as we’re going to find in the next step.

    Step 4: Creating the Login Page

    Let’s create our sessions controller. Run the following code in your terminal to create a new sessions controller, and the new, create, and failure actions.

    rails generate controller sessions new create failure
    

    Next, open your config/routes.rb file and add this:

    get   '/login', :to => 'sessions#new', :as => :login
    match '/auth/:provider/callback', :to => 'sessions#create'
    match '/auth/failure', :to => 'sessions#failure'
    

    Let’s break this down:

    • The first line is used to create a simple login form where the user will see a simple “Connect with Facebook” link.
    • The second line is to catch the provider’s callback. After a user authorizes your app, the provider redirects the user to this url, so we can make use of their data.
    • The last one will be used when there’s a problem, or if the user didn’t authorize our application.

    Make sure you delete the routes that were created automatically when you ran the rails generate command. They aren’t necessary for our little project.

    Open your app/controllers/sessions_controller.rb file and write the create method, like so:

    def create
      auth_hash = request.env['omniauth.auth']
    
      render :text => auth_hash.inspect
    end
    

    This is used to make sure everything is working. Point your browser to localhost:3000/auth/facebook and you’ll be redirected to Facebook so you can authorize your app (pretty cool huh?). Authorize it, and you will be redirected back to your app and see a hash with some information. In between will be your name, your Facebook user id, and your email, among other things.

    Step 5: Creating the User Model

    The next step is to create a user model so users may sign up using their Facebook accounts. In the Rails console (rails console), create the new model.

    rails generate model User name:string email:string
    

    For now, our user model will only have a name and an email. With that out of the way, we need a way to recognize the user the next time they log in. Keep in mind that we don’t have any fields on our user’s model for this purpose.

    The idea behind an application like the one we are trying to build is that a user can choose between using Facebook or Twitter (or any other provider) to sign up, so we need another model to store that information. Let’s create it:

    rails generate model Authorization provider:string uid:string user_id:integer
    

    A user will have one or more authorizations, and when someone tries to login using a provider, we simply look at the authorizations within the database and look for one which matches the uid and provider fields. This way, we also enable users to have many providers, so they can later login using Facebook, or Twitter, or any other provider they have configured!

    Add the following code to your app/models/user.rb file:

    has_many :authorizations
    validates :name, :email, :presence => true
    

    This specifies that a user may have multiple authorizations, and that the name and email fields in the database are required.

    Next, to your app/models/authorization.rb file, add:

    belongs_to :user
    validates :provider, :uid, :presence => true
    

    Within this model, we designate that each authorization is bound to a specific user. We also set some validation as well.

    Step 6: Adding a Bit of Logic to our Sessions Controller

    Let’s add some code to our sessions controller so that it logs a user in or signs them up, depending on the case. Open app/controllers/sessions_controller.rb and modify the create method, like so:

    def create
      auth_hash = request.env['omniauth.auth']
    
      @authorization = Authorization.find_by_provider_and_uid(auth_hash["provider"], auth_hash["uid"])
      if @authorization
        render :text => "Welcome back #{@authorization.user.name}! You have already signed up."
      else
        user = User.new :name => auth_hash["user_info"]["name"], :email => auth_hash["user_info"]["email"]
        user.authorizations.build :provider => auth_hash["provider"], :uid => auth_hash["uid"]
        user.save
    
        render :text => "Hi #{user.name}! You've signed up."
      end
    end
    

    This code clearly needs some refactoring, but we’ll deal with that later. Let’s review it first:

    • We check whether an authorization exists for that provider and that uid. If one exists, we welcome our user back.
    • If no authorization exists, we sign the user up. We create a new user with the name and email that the provider (Facebook in this case) gives us, and we associate an authorization with the provider and the uid we’re given.

    Give it a test! Go to localhost:3000/auth/facebook and you should see “You’ve signed up”. If you refresh the page, you should now see “Welcome back”.

    Step 7: Enabling Multiple Providers

    The ideal scenario would be to allow a user to sign up using one provider, and later add another provider so he can have multiple options to login with. Our app doesn’t allow that for now. We need to refactor our code a bit. Change your sessions_controlller.rb’s create method to look like this:

    def create
      auth_hash = request.env['omniauth.auth']
    
      if session[:user_id]
        # Means our user is signed in. Add the authorization to the user
        User.find(session[:user_id]).add_provider(auth_hash)
    
        render :text => "You can now login using #{auth_hash["provider"].capitalize} too!"
      else
        # Log him in or sign him up
        auth = Authorization.find_or_create(auth_hash)
    
        # Create the session
        session[:user_id] = auth.user.id
    
        render :text => "Welcome #{auth.user.name}!"
      end
    end
    

    Let’s review this:

    • If the user is already logged in, we’re going to add the provider they’re using to their account.
    • If they’re not logged in, we’re going to try and find a user with that provider, or create a new one if it’s necessary.

    In order for the above code to work, we need to add some methods to our User and Authorization models. Open user.rb and add the following method:

    def