Feeds

100722 items (110 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+ (61 unread)

Setup Fuel

We need a FuelPHP installation with an RM package enabled. I’m going to use a MySQL database with a sample table. While the Fieldset class can be configured to use a normal model, using an ORM will save us some time.

If you haven’t reviewed the first couple parts of the FuelPHP series here on Nettuts+, now is a great time to check out part one and two, by Phil Sturgeon.

Set up a database connection at fuel/app/config/development/db.php.

		return array(
		  'default' => array(
		 	 'connection'  => array(
		 		 'dsn'  	=> 'mysql:host=localhost;dbname=blog',
		 		 'username' => 'root',
		 		 'password' => 'root',
		 	 ),
		  ),
		);
		

Enable the ORM package through fuel/app/config.php

			'packages'  => array(
				'orm',
			),
		

And, finally, here’s the SQL for the table I’m using for this tutorial.

			CREATE TABLE  `blog`.`posts` (
			`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
			`post_title` VARCHAR( 100 ) NOT NULL ,
			`post_content` TEXT NOT NULL ,
			`author_name` VARCHAR( 65 ) NOT NULL ,
			`author_email` VARCHAR( 80 ) NOT NULL ,
			`author_website` VARCHAR( 60 ) NULL,
			`post_status` TINYINT NULL
			) ENGINE = INNODB;
		
Model

We need a model for our controller to interact with the posts table. Go ahead and create a post.php inside app/classes/model/. Create a Model_Post class and make sure it extends \Orm\Model. The ORM will automatically use the posts table in our database since we have used the singular of “posts”. If you want to set a different table, set up a static property called $_table_name.

		class Model_Post extends \Orm\Model
		{
			protected static $_table_name = 'posts'; //set the table name manually
		}
	
Setting Up the Properties

We should specify the columns of our posts table within our model. At the same time, we can also set up labels, form validation rules to use with our fieldset class to generate the form. All of these go in an associated array, called $_properies. With everything in place, our final model should look like so:

	class Model_Post extends \Orm\Model
	{
		protected static $_table_name = 'posts';

		protected static $_properties = array(
			'id',
			'post_title' => array( //column name
				'data_type' => 'string',
				'label' => 'Post Title', //label for the input field
				'validation' => array('required', 'max_length'=>array(100), 'min_length'=>array(10)) //validation rules
			),
			'post_content' => array(
				'data_type' => 'string',
				'label' => 'Post Content',
				'validation' => array('required')
			),
			'author_name' => array(
				'data_type' => 'string',
				'label' => 'Author Name',
				'validation' =>  array('required', 'max_length'=>array(65), 'min_length'=>array(2))
			),
			'author_email' => array(
				'data_type' => 'string',
				'label' => 'Author Email',
				'validation' =>  array('required', 'valid_email')
			),
			'author_website' => array(
				'data_type' => 'string',
				'label' => 'Author Website',
				'validation' =>  array('required', 'valid_url', 'max_length'=>array(60))
			),
			'post_status' => array(
				'data_type' => 'string',
				'label' => 'Post Status',
				'validation' => array('required'),
				'form' => array('type' => 'select', 'options' => array(1=>'Published', 2=>'Draft')),
			)

		);
	}
	

Let’s examine what options we can use. data_type simply holds the fields’s type. It could be either string, integer or mysql_date. The value for the label property will be shown as the field label once the form is generated. validation accepts an array of validation rules. By default, these fields will be text input fields. Using the form, you can make it a select or texarea.

The ORM treats the column named id as the primary and will not be shown when generating a form. If your table’s primary key column is different, use the $_primary_key property to specify it.

	/**
	 * Post Model
	 */
	class Model_Post extends \Orm\Model
	{
		protected static $_table_name = 'posts';

		protected static $_primary_key = array('id'); //you can set up multiple columns, .. $_primary_key => array('id', 'user_id')
	}
	
Controller

Now that the model is ready, let’s create the controller. Controllers should be placed within fuel/app/classes/controller/. I’ve created a controller, called Controller_Posts (posts.php) and extended it from Controller_Template.

		/**
		 * Post Controller fuel/app/classes/controller/posts.php
		 */
		class Controller_Posts extends \Controller_Template
		{
			//list posts
			function action_index()
			{

			}

			//add new one
			function action_add()
			{

			}

			//edit
			function action_edit($id)
			{

			}
		}
	

Users will be able to see a list of posts, add new ones, or edit an existing one. Because I’m using the template controller, I can use a base template file to work with. Templates go in fuel/app/views/template.php

	<!DOCTYPE html>
	<html>
	<head>
	    <meta [http-equiv="Content-type"] content="text/html; charset=utf-8" />
	    <?php echo Asset::css('bootstrap.css'); ?>
	</head>

	<body>

		<div id="content">

			<p>
				<?php
					echo \Html::anchor('posts/index', 'Listing'), '&nbsp;', \Html::anchor('posts/add', 'Add');
				?>
			</p>

			<?php if(isset($messages) and count($messages)>0): ?>
			<div class="message">
				<ul>
				<?php
					foreach($messages as $message)
					{
						echo '<li>', $message,'</li>';
					}
				?>
				</ul>
			</div>
			<?php endif; ?>

			<?php echo $content; ?>
		</div>

	</body>
	</html>
	

This is merely standard HTML markup with the Twitter bootstrap. The $content variable will have the content. We can set an array of messages and if we do, it will be printed as an unordered list.

Adding New Posts

This is where the fun begins. We’re going to generate the form for adding new posts. As you might have guessed, we’ll be working with the action_add() method. Let’s generate the form and pass it to our template.

	//add new one
	function action_add()
	{
		$fieldset = Fieldset::forge()->add_model('Model_Post');
		$form     = $fieldset->form();

		$this->template->set('content', $form->build(), false); //false will tell fuel not to convert the html tags to safe string.
	}
	

Fieldset::forge() will return a new instance of the fieldset class. It’s the same as doing new Fieldset. However, using the forge method here, we can name our instances. If we call an instance twice with the same name, an existing instance will be returned if available [the Factory pattern]. To name your instance, pass the name to the forge method. Fieldset::forge('new_post')

Using the add_model method, we pass the model which we want the forms to be generated from. Fieldset will grab the data from $_properties to generate the form. Calling the form() method from the fieldset object will return an instance from Form class, and by calling the build() method, we can get a html (string) output of the form.

		$this->template->set('content', $form, false);
	

Finally, we pass the $form to the template as content. Another method of passing variables to a template is $this->template->content = $form.

Fire up your browser and navigate to http://path_to_site/index.php/posts/add. You should see a form identical to this.

No submit button? Let’s fix that. We need to add a new field to our form object.

		$form->add('submit', '', array('type' => 'submit', 'value' => 'Add', 'class' => 'btn medium primary'));
	

Using the add method we can add additional fields to our form. First parameter is our new fields name, second is for label, for the third parameter we pass an array of attributes.

After adding this, our action_add() will look like this.

	function action_add()
	{
		$fieldset = Fieldset::forge()->add_model('Model_Post');
		$form     = $fieldset->form();
		$form->add('submit', '', array('type' => 'submit', 'value' => 'Add', 'class' => 'btn medium primary'));

		$this->template->set('content', $form->build(), false);
	}
	

And our form..

Validation and Saving

Now that we have a nice form, let’s validate it and save to the database. The fieldset object includes an instance from FuelPHP’s validation class. All the rules has been applied and ready to go.

	function action_add()
	{
		$fieldset = Fieldset::forge()->add_model('Model_Post');
		$form     = $fieldset->form();
		$form->add('submit', '', array('type' => 'submit', 'value' => 'Add', 'class' => 'btn medium primary'));

		if($fieldset->validation()->run() == true)
		{
			$fields = $fieldset->validated();

			$post = new Model_Post;
			$post->post_title     = $fields['post_title'];
			$post->post_content   = $fields['post_content'];
			$post->author_name    = $fields['author_name'];
			$post->author_email   = $fields['author_email'];
			$post->author_website = $fields['author_website'];
			$post->post_status    = $fields['post_status'];

			if($post->save())
			{
				\Response::redirect('posts/edit/'.$post->id);
			}
		}
		else
		{
			$this->template->messages = $fieldset->validation()->errors();
		}

		$this->template->set('content', $form->build(), false);
	}
	

$fieldset->validation() returns a validation class instance and by accessing its run() method we can check if validation is passed. If so, we add a new post to our database. $fieldset->validated() will return an array of validated fields. If validation is passed and post is saved, the user will be redirected to the edit page, otherwise pass the validation errors to our template as message variable.

If you try to submit some invalid data, you will get an output like so:

Everything seems fine except for one issue: data we submit doesn’t appear after the page refresh. Not to worry, one method call and you’re done.

	$fieldset = Fieldset::forge()->add_model('Model_Post')->repopulate(); //repopulate method will populate your form with posted data
	

Cool, huh? Add some valid data and it will redirect to the action_edit() method, which is not ready yet.

Editing a Post

Editing a section is pretty much the same as our add post section. Except we need to populate the data with an existing post. I’m going to duplicate the action_add code.


	function action_edit($id)
	{
		$post = \Model_Post::find($id);

		$fieldset = Fieldset::forge()->add_model('Model_Post')->populate($post); //model post object is passed to the populate method
		$form     = $fieldset->form();
		$form->add('submit', '', array('type' => 'submit', 'value' => 'Save', 'class' => 'btn medium primary'));

		if($fieldset->validation()->run() == true)
		{
			$fields = $fieldset->validated();

			//$post = new Model_Post;
			$post->post_title     = $fields['post_title'];
			$post->post_content   = $fields['post_content'];
			$post->author_name    = $fields['author_name'];
			$post->author_email   = $fields['author_email'];
			$post->author_website = $fields['author_website'];
			$post->post_status    = $fields['post_status'];

			if($post->save())
			{
				\Response::redirect('posts/edit/'.$id);
			}
		}
		else
		{
			$this->template->messages = $fieldset->validation()->errors();
		}

		$this->template->set('content', $form->build(), false);
	}
	

With some small modifications to our action_add() method, we have our edit method. repopulate() method has been replaced by populate() method. Using the populate method, we can populate a form with an existing post’s data.

In this case, we grab the post from our database using the $id parameter, then pass it to the requisite method. We don’t need $post = new Model_Post; anymore because we are not adding any thing to the database. The $post object we create in the beginning is used to assign the new values. Once edited it will redirect back to its edit screen. We’re done! Add some posts, and try editing them.

Listing Pages

Let’s build up the listing section so users can see all the posts in one place.

The listing is handled by the action_index() method

	//list posts
	function action_index()
	{
		$posts = \Model_Post::find('all');

		$view  = \View::forge('listing');
		$view->set('posts', $posts, false);

		$this->template->content = $view; //In config file View objects are whitelisted so Fuelphp will not escape the html.
	}
	

Model_Post::find('all') will return an array of posts objects for all of our posts. Using View::forge(), a new view object is instantiated. The parameter for View::forge() is the name for our specific view. It’s located at app/views/listing.php. The array of posts object ($posts) is then passed to our view. The Listing view will take care of the listing and finally we assign the view to $this->template->content.

In the view, we loop through $posts and generate the list.

	<?php
	/**
	 * Listing view, views/listing.php
	 */
	if($posts):
		foreach($posts as $post):
	?>

	<div class="post">
		<h2><?php echo $post->post_title; ?> <small><?php echo \Html::anchor('posts/edit/'.$post->id, '[Edit]');?></small></h2>
		<p><?php echo $post->post_content; ?></p>
		<p>
			<small>By <?php echo $post->author_name; ?></small><br />
			<small><?php echo $post->author_email; ?></small><br />
			<small><?php echo $post->author_website; ?></small><br />
		</p>
	</div>

	<?php
		endforeach;
	endif;
	?>
	

If you have any posts in the database, it will look something like this.

Some Final Modifications

Everything seems to be working correctly; however, there are some minor issues. The generated form has a text field for the post content, which would be better off as a textarea.

	//Model_Post
	'post_content' => array(
		'data_type' => 'string',
		'label' => 'Post Content',
		'validation' => array('required'),
		'form' => array('type' => 'textarea') //will give us a textarea
	),
	

You can pass all the field types text, textarea, select, radio etc. For select or radio elements, you can set the options. Setting options for a select using another table is also possible. If you want to change the default layout, place a form config file in fuel/app/config/form.php If you’re not sure about what to put in there, copy stuff from fuel/core/config/form.php. Fuel uses this file to generate the forms.

Summary

I hope you now have a clear understanding of the fieldset class. If you have any questions, please let me know in the comments below. Thank you so much for reading!


  • Permalink for 'Automate Your Projects With Apache Ant'

    Automate Your Projects With Apache Ant

    Posted: March 12th, 2012, 8:00am MDT by Andrew Burgess

    Ever find yourself doing boring, repetitive tasks as a web developer? Today, I’m going to show you how you can cut those meta-tasks out of your development cycle with a little bit of automation. In this tutorial, you’ll learn how to easily perform those repetitive tasks with Apache Ant.


    March of 2011 Intro: What is Ant?

    Ant makes it incredibly easy to define a set of tasks that you can then execute with a few commands.

    Ant is a piece of software that was originally built for automating software builds. It’s made by Apache (yes, as in Apache server), and its primarily purpose is to build Java applications. When you’re building software (or, in our case, websites/apps), you do several tasks that are identical each time you build or publish or deploy your project. It’s a waste of your valuable time to do this manually. Ant makes it incredibly easy to define a set of tasks that you can then execute with a few short-and-sweet commands through the terminal.

    Ready? Let’s Get started!

    Step 0: Creating our Dummy Project

    Before we get to Ant, we need to have a project to work with here. Here’s the index.html file I’m using:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Dummy Project</title>
        <link rel="stylesheet" href="css/reset.css"  />
        <link rel="stylesheet" href="css/grid.css"   />
        <link rel="stylesheet" href="css/custom.css" />
    </head>
    <body>
        <div>
            <h1> Demo Page </h1>
            <p> There are three CSS files and three JavaScript files in this project.
            <ul>
                <li><a href=" [meyerweb.com] Meyer's Reset</a></li>
                <li><a href=" [www.blueprintcss.org] from the Blueprint CSS</a></li>
                <li>A custom stylesheet</li>
            </ul>
            <ul>
                <li> <a href=" [jquery.com">jQuery<]             <li> <a href=" [javascript.crockford.com] Crockford's Top Down Operator Precedence files tokens.js and parse.js.</a></li>
            </ul>
            <p> All these files are uncompressed; that's the point of this tutorial, after all. </p>
        </div>
        <script src="js/jquery-latest.js"></script>
        <script src="js/tokens.js"></script>
        <script src="js/parse.js"></script>
    </body>
    </html>
    

    As you can see, this explains the rest of the project. If you download the project (link at the top), you’ll get the CSS and JavaScript files.

    So, what are we going to do with this project? As you can see, we’ve got multiple CSS and JavaScript files linked up in this project. What we’ll do is compile and compress each into its respective file and FTP it all up to a server. Before all of that, we’ll start by installing Ant.

    Step 1: Installing Ant

    Installing Ant can be a rather daunting task. Thankfully, both the Windows and Mac installation process is pretty similar. If you’re on Linux, I’m going to assume you either have Ant installed already, know how, or can figure it out without my hand-holding.

    If you’re on a Mac, you probably already have Ant installed; however, some of the more advanced tasks (in our case, FTP) won’t work. So, we’ll install the latest version.

    Before we begin, I’ll point you to the full instructions that Apache offers: you can get them here. (Unfortunately, that’s the whole manual for Ant; I can’t do any better, as it’s done with frames. You’ll see the “Installing Apache Ant” link in the left frame.) What I tell you below can all be found in there (and more besides), but my version is a little more web-developer friendly.

    First off, let’s make sure we have the right Java dependencies. Whether you’re on Windows or Mac, you’ll need the Java Development Kit (JDK) – at least version 1.4. You can download it here. If you’re not sure which version of the JDK you have, run the command java -version in the terminal / command line. As I understand it, the JDK version number is the same as the Java version number.

    Now, let’s download the latest version of Ant. You can get it from the download page for the binary distribution (of course, you can get the source and compile it yourself, if that’s how you roll). You’ll find the links half-way down the page:

    Download Links

    Once you’ve downloaded and unzipped it, we have to install it. This is what you’ll get:

    Ant Unzipped

    The first part of the installation differs with your platform. Let’s start with the Windows steps:

    Windows-Specific Install Bits

    First, you’ll have to choose the folder in which you’d like to install Ant. I went with C:\ant, but it’s up to you. Create that folder, and move the bin, lib, and etc folders from your download folder to that folder. You’ll also want to move fetch.xml and get-m2.xml.

    Once you’ve done that, you’ll have to setup some environmental variables. If you aren’t sure how to do this, you can find instructions here (Make these system variables—although, truthfully, it shouldn’t matter). This is what you’ll need to set up:

    • You’ll need a variable called ANT_HOME; this should point to the folder to which you moved the Ant components. Example: C:\ant.
    • You’ll need a variable called JAVA_HOME; this might already be there, but if it’s not, it should point to the folder holding your Java install. Mine is C:\Program Files\Java\jdk1.6.0_18.
    • You’ll need to modify you’re Path variable. This is a list of folders the command line searches through to find the commands you want to execute. DON’T overwrite this competely; just add ;%ANT_HOME%\bin to the end of it. Don’t miss that semicolon; that’s what separates the paths in the list. You might be able to guess that the %ANT_HOME% bit references the variable we made earlier.

    Now, you’ve got Ant installed on Windows! There’s one more important step, though; so skip pver the Mac piece and keep following along.

    Mac-Specific Install Bits

    You’ve already got ant installed on your Mac; you can see this by running the command which ant on the terminal. This will output something along the lines of /usr/bin/ant, as the path to the Ant executable you use. However, if you actually go to that folder, you’ll find that it’s just a symlink to the real stuff.

    Path to Ant

    As you can see, for me it’s linked to /usr/share/java/ant-1.8.1/bin/ant. Now, you could use this, but when I tried to, I wasn’t able to use the FTP component. Rather than install Ant somewhere else and mess with the symlink, I chose to do this: move what was in the usr/share/java/ant-1.8.1 folder into a subfolder called _old and move the new stuff in. You’ll have to move the bin, lib, and etc folders, plus the fetch.xml and get-m2.xml files. Now, that symlink will point to the updated version of ant. If you run ant -version in the terminal, you should see that you’ve got version 1.8.2 (or whatever version is latest at the time you’re reading this).

    Back to All OS Instructions

    There’s one more step to finish the installation. There are several optional components that don’t come with Ant, but that we’ll need for our project, and that you may want to use down the road. Let’s get them now.

    You’ll start by opening a command line or terminal and changing to the directory that you’ve just installed Ant in. More importantly, it’s the directory you put the fetch.xml file in. Now, run this command:

    ant -f fetch.xml -Ddest=system

    This will download and install quite a few optional components; this isn’t one of those blink-and-it’s-over commands: it could take a few minutes.

    Now, you’ve got Ant installed and ready to run; let’s get to work.

    Step 2: Creating the build.xml File

    Ant uses an XML file to store the tasks for the current project.

    Ant uses an XML file to store the tasks for the current project; when you’re in that project’s directory on the command line, you’ll be able to run the command ant TASK_NAME_HERE, and it will find the appropriate task within the XML file and execute it.

    If you’re not familiar with XML, don’t worry. XML stands for eXtensible Markup Language, and it’s very similar to HTML. It uses tags and attributes to define data. Actually, it’s more similar to XHTML (RIP), in that the rules are strict: all tags and attributes must be lowercase, values are quoted, a doctype is required, etc. Don’t worry though, you’ll get the hang of it.

    The XML file that Ant looks for by default should be named build.xml; you’ll want to put it in your project folder.

    So what exactly is going in the XML file? Here’s a start:

    <?xml version="1.0"?>
    <project name="Compress, Concatenate, and FTP CSS and JS" default="initialize">
    
    </project>
    

    Looks like HTML, eh? The first line is an XML doctype. Next, we have the root node, which is a project. I’ve added two attributes to it: a name, which just explains what our list of tasks will do; and a default, which defines the default task to run.

    See, here’s how the default task idea works. Let’s say we create a task called call_mom. We could run that from the terminal by doing this:

    ant call_mom

    If you find that most of the time you run Ant on a project, you’re calling the same task, you’ll want to make it the default. In our case, we’ve set initialize as the default task, the one that will run if we don’t tell ant to run anything.

    ant initialize
    ant

    These are both the same.

    Now that we’ve got our build.xml file, let’s create our first task.

    Step 3: Writing our First Task

    Tasks are called targets within the build.xml file. Check this out:

    <target name="call_mom">
        <echo> Hi Mom! </echo>
    </target>

    Plug this into your build.xml file and run ant call_mom on the console. You should output that looks something like this:

    Buildfile: /path/to/your/build.xml
    
    call_mom:
         [echo]  Hi Mom! 
    
    BUILD SUCCESSFUL
    Total time: 0 seconds

    In its output, Ant will have an entry for all the tasks that are run. Then, any output from those tasks will be displayed, tabbed in under the appropriate task name. As you can see, we’ve called the echo task, which prints out whatever we put inside it.

    But how did I know echo was a task? Well, you can get a list of the built-in tasks here in the documentation. This is a good time to point out that many tasks have several ways they can be called. For example, we could also have done: . What I show you isn’t the only way to do things.

    Now that you’re starting to warm into the ideas of Ant, let’s talk about properties.

    Step 4: Creating a Properties Files

    Ant has properties, which are very like variables in a programming language.

    As you use Ant more, you might find that you have a boilerplate build.xml file that you only tweak slightly. One of these tweaks might be file/folder names. Ant has properties, which are very like variables in a programming language. You can create them this way (this is done inside a task).

    <property name="js_dir" value="js" />
    <!-- or -->
    <property name="css_dir">stylesheets</property>

    You can also move all these properties out into a separate file, and import the file. That’s what we’ll do here. This brings us to creating our first (real) task:

    <target name="get_properties">
        <property file="ant.properties" />
        <echo>Imported Properties</echo>
    </target>

    We’ve called our task get_properties. It involves two actions: first, we use the property task to import the file (we can do that with the file attribute). Then, we echo a message saying that it was successful. It’s that simple.

    Of course, we’ll need to create the ant.properties file. This is super-simple; here’s the one we’ll use today:

    css_dir = css
    js_dir = js
    assets_dir = assets

    You might think this actually makes it harder, because our variables names are longer than the values themselves. Well, that’s true, but it gives us some flexibility in the use of our build.xml file, makes it more reusable and more shareable.

    Step 5: Creating Some More Tasks

    Okay, now let’s get serious. We’ve obviously got quite a few more tasks to create before we have a useful build.xml file.

    Here’s a list of the tasks we need to create:

    • One to compile the CSS files.
    • One to compress the CSS file.
    • One to compile the JavaScript files.
    • One to compress the JavaScript file.
    • One to upload everything to our server.
    • One to initialize the other tasks.
    • One to clean up what the others do.

    We’re going to use a few different tactics to do all this, to give to a good overview of how Ant works.

    Compiling the CSS and JavaScript

    Let’s start with the compiling tasks; these take a set of files and concatenate them all into one file. Ant has a built-in task named concat that does this.

    <target name="concat_css">
        <concat destfile="${assets_dir}/style.css">
            <filelist id="files" dir="${css_dir}">
                <file name="reset.css" />
                <file name="grid.css" />
                <file name="custom.css" />
            </filelist>
        </concat>
    </target>

    I’ve named this task concat_css. Inside, we’re only running the concat task. As you can see, the file they will be concatenated into (destfile, or destination file) will be in assets/style.css. You’ll notice that I’m use the assets_dir properties, which will substitute the correct value in. You must wrap usages of properties in the dollar-sign-and-braces notation.

    Inside the concat task, we define a filelist This is just one of the ways that we can grab a bunch of files. I’m using it here because it allows me to define the order I’d like these files concatenated. I’m giving it an id, which gives us access to the file set in the same way we’d use a parameter (although we won’t be doing that). It also has the attribute dir, which tells the task which folder to find the files in. Then, inside, just define the appropriate file nodes, with their name attribute holding the filename.

    There’s your first real task! Hopefully, it makes sense. While we’re at it, the JavaScript one isn’t too different:

    <target name="concat_js">
        <concat destfile="${assets_dir}/script.js">
            <filelist id="files" dir="${js_dir}">
                <file name="jquery-latest.js" />
                <file name="tokens.js" />
                <file name="parse.js" />
            </filelist>
        </concat>
    </target>
    Compressing the CSS and JavaScript

    Compression gets a bit trickier, because it’s not built into Ant. However, Ant supports outside tasks via java .jar files. This is incredibly handy for us, because YUI Compressor is available as a .jar file (that’s the only way it’s available). You can download it on the YUI Library download page. You’ll want to save it to a smart location, and maybe rename it. I’ve saved it to MY_USER_FOLDER/bin/yui.jar. Do what pleases you.

    Now, YUI Compressor will compress both JavaScript and CSS. What we can do here is create one compress task, and then call it from two more specific tasks. We can do this because Ant has support for calling other tasks and passing in parameters. Let’s see how this works:

    <target name="compress">
        <java jar="/Users/andrew/bin/yui.jar" fork="true">
            <arg value="${file}" />
            <arg value="-o" />
            <arg value="${file}" />
        </java>
        <echo>${file}</echo>
    </target>

    We’re using the java command here. This is very similar to running the jar file from the command line. The jar attribute points to the jar file. If the fork attribute is true, the jar will be run in a Java virtual machine separate from the one Ant is running on. Then, inside the java node, we define the arguments. On the command line, we would pass in input.file -o output.file. So, we do the same thing here.

    But, where’s the file property coming from? From here:

    <target name="compress_css" depends="concat_css">
        <antcall target="compress">
            <param name="file" value="${assets_dir}/style.css" />
        </antcall>
    </target>

    This is our CSS compression task. First, notice that the target node has a second attribute: depends. You can probably guess that this means that the compress_css tasks depends on the concat_css task, so it must be run first. This way, we can call compress_css and it will automatically call concat_css first.

    Now, what’s going on inside? We’re executing an antcall task, which simply calls another task within our build.xml file—in this case, that’s our compress task. Inside that, we can create as many parameters as we need to, each having a name and a value. Yep, this is very much like calling a function. This is the file parameter that we use within our compress task.

    And here’s the JavaScript version:

    <target name="compress_js" depends="concat_js">
        <antcall target="compress">
            <param name="file" value="${assets_dir}/script.js" />
        </antcall>
    </target>

    Don’t forget, this one is dependant on concat_js.

    Getting the Ball Rolling

    Way back at the top—on our root project node—we set the default task as initialize. We haven’t created that task yet, so let’s do it now.

    <target name="initialize" depends="get_properties,clean_up">
        <mkdir dir="${assets_dir}" />
        <antcall target="compress_css" />
        <antcall target="compress_js"  />
        <echo>Done!</echo>
    </target>

    This task depends on two other tasks (one of which we haven’t created yet); we just use a comma separated list to require multiple tasks.

    Inside, the first task is to create our assets directory, with the mkdir task (just like on the command line). Next, we make two antcalls, one to compress the CSS, and one to compress the JavaScript. Remember, these two tasks depend on their respective concatenation functions, so they will call those. Finally, we’ll echo a message letting the user know that we’re done.

    Cleaning Up

    What about that clean_up task that initialize depends on? It’s pretty simple:

    <target name="clean_up" depends="get_properties">
        <delete dir="${assets_dir}" />
    </target>

    It merely deletes the assets directory. This isn’t completely necessary, but you might find it useful.

    Uploading the Project

    Let’s create one more task; we want to upload our project to a server. Thanks to the ftp command, this is a cinch.

    <target name="upload_files" depends="initialize">
        <ftp server="your_server.com"
             userid="your_user_name"
             password="your_password"
             port="21"
             remotedir="/public_html"
             passive="yes"
             binary="no">
            <fileset dir=".">
                <include name="assets/*"   />
                <include name="index.html" />
            </fileset>
        </ftp>
    </target>

    We’re calling this task upload_files, and it depends on initialize. We’re using the FTP task here. As you can see, all the important info is stored in the attributes. If you’ve worked with FTP clients before, all these options should be familiar.

    • Inside the ftp node, we’ve created a collection of files that we want to upload. In this case, we’re using a fileset element.
    • We have a dir attribute on the filset node that defines the root directory for what we want to collect.
    • Then, inside, we use the include node to get the specific files: we just pass as the name attribute the file(s) we want to get. In our example, we’re getting everything the assets directory and its contents, and the index.html file.

    Once you fill in your server information in this task, it should upload those files for you!

    Notice how we’ve arranged these tasks, though. If we run ant on the command line, we’re concatenate and compress the CSS and JavaScript, but we won’t upload it; that’s not the default. If we want to upload it, we can run ant upload_files; since that depends on initialize, we don’t have to call initialize first. Of course, we can call any individual task we’d like (for example: ant compress_js).

    Conclusion: Wrapping It Up

    Before we close, there are a few odds and ends I’d like to mention:

    • Notice that I didn’t use the depends task to daisy-chain tasks together. You could do that, but I’ve chosen to keep that to actual dependant tasks, and create the initialize task to call the others. This just seems more correct semantically.
    • What I’ve shown you is just a small sliver of what Ant is capable of. If you want to learn more, start by checking out the tasks overview. This will show you all the built-in tasks. You’ll also realize that there are many ways to do the same this (as I showed you with the echo task). The patterns I’ve used are by no means the “one right way.” Also, the Ant Wiki is a great resource.
    • It might be nice if we could have a task that will parse the HTML, find the stylesheets and scripts, and get them in the correct order. Unfortunately—since Ant wasn’t written for web developers—that’s not built in. We’d have to create an antlib (an extension), and that would be written in Java. For now, we’ll have to hard-code out lists of stylesheets and scripts.

    And that’s a wrap! I hope you’ve learned some new techniques that will save you time in the future. If you have any questions, feel free to post them below! Thank you so much for reading!


  • Permalink for 'Sass vs. LESS vs. Stylus — a Preprocessor Shootout'

    Sass vs. LESS vs. Stylus — a Preprocessor Shootout

    Posted: March 9th, 2012, 10:00am MST by Jeffrey Way

    Wielding the true power of a CSS preprocessor is an adventure. There are countless languages, syntaxes, and features, all ready for use right now.

    In this article, we will be covering the various features and benefits of using three different preprocessors—Sass, LESS, and Stylus.

    Introduction

    Preprocessors produce CSS that works in all browsers.

    CSS3 preprocessors are languages written for the sole purpose of adding cool, inventive features to CSS without breaking browser compatibility. They do this by compiling the code we write into regular CSS that can be used in any browser all the way back to the stone ages. There are thousands of features that preprocessors bring to the table, and in this article we will cover some of the publicized ones, and some of the not-so-publicized ones. Let’s get started.

    Syntax

    The most important part of writing code in a CSS preprocessor is understanding the syntax. Luckily for us, the syntax is (or can be) identical to regular CSS for all three preprocessors.

    Sass & LESS

    Sass and LESS both use the standard CSS syntax. This makes it extremely easy to convert an existing CSS file to either preprocessor. Sass uses the .scss file extension and LESS uses the .less extension. The basic Sass or LESS file can be setup like below:

    /* style.scss or style.less */
    h1 {
      color: #0982C1;
    }
    

    As you may have noticed, this is just regular CSS, which compiles perfectly in both Sass and LESS.

    It’s important to note that Sass also has an older syntax, which omits semicolons and curly brackets. Although this is still around, it is old and we won’t be using it past this example. The syntax uses the .sass file extension and looks like this:

    /* style.sass */
    h1
      color: #0982c1
    
    Stylus

    The syntax for Stylus is much more verbose. Using the .styl file extension, Stylus accepts the standard CSS syntax, but it also accepts some other variations where brackets, colons, and semi-colons are all optional. For example:

    /* style.styl */
    h1 {
      color: #0982C1;
    }
    
    /* omit brackets */
    h1
      color: #0982C1;
    
    /* omit colons and semi-colons */
    h1
      color #0982C1
    

    Using different variations in the same stylesheet is also valid, so the following will compile without errors.

    h1 {
      color #0982c1
    }
    h2
      font-size: 1.2em
    
    Variables

    Variables can be declared and used throughout the stylesheet. They can have any value that is a CSS value (e.g. colors, numbers [units included], or text.), and can be referenced anywhere throughout our stylesheet.

    Sass

    Sass variables are prepended with the $ symbol and the value and name are separated with a semicolon, just like a CSS property.

    $mainColor: #0982c1;
    $siteWidth: 1024px;
    $borderStyle: dotted;
    
    body {
      color: $mainColor;
      border: 1px $borderStyle $mainColor;
      max-width: $siteWidth;
    }
    
    LESS

    LESS variables are exactly the same as Sass variables, except the variable names are prepended with the @ symbol.

    @mainColor: #0982c1;
    @siteWidth: 1024px;
    @borderStyle: dotted;
    
    body {
      color: @mainColor;
      border: 1px @borderStyle @mainColor;
      max-width: @siteWidth;
    }
    
    Stylus

    Stylus variables don’t require anything to be prepended to them, although it allows the $ symbol. As always, the ending semicolon is not required, but an equal sign in between the value and variable is. One thing to note is that Stylus (0.22.4) compiles if we prepend the @ symbol to a variable name, but will not apply the value when referenced. In other words, don’t do that.

    mainColor = #0982c1
    siteWidth = 1024px
    $borderStyle = dotted
    
    body
      color mainColor
      border 1px $borderStyle mainColor
      max-width siteWidth
    
    Compiled CSS

    Each of the above files will compile to the same CSS. You can use your imagination to see how useful variables can be. We will no longer need to change one color and have to retype it twenty times, or want to change our site width and have to dig around to find it. Here’s the CSS after compilation:

    body {
      color: #0982c1;
      border: 1px dotted #0982c1;
      max-width: 1024px;
    }
    
    Nesting

    If we need to reference multiple elements with the same parent in our CSS, it can be tedious to keep writing the parent over and over.

    section {
      margin: 10px;
    }
    section nav {
      height: 25px;
    }
    section nav a {
      color: #0982C1;
    }
    section nav a:hover {
      text-decoration: underline;
    }
    

    Instead, using a preprocessor, we can write the children selectors inside the parent’s brackets. Also, the & symbol references the parent selector.

    Sass, LESS, & Stylus

    All three preprocessors have the same syntax for nesting selectors.

    section {
      margin: 10px;
    
      nav {
        height: 25px;
    
        a {
          color: #0982C1;
    
          &amp;:hover {
            text-decoration: underline;
          }
        }
      }
    }
    
    Compiled CSS

    This is the compiled CSS from the code above. It is exactly the same as when we started—how convenient!

    section {
      margin: 10px;
    }
    section nav {
      height: 25px;
    }
    section nav a {
      color: #0982C1;
    }
    section nav a:hover {
      text-decoration: underline;
    }
    
    Mixins

    Mixins are functions that allow the reuse of properties throughout our stylesheet. Rather than having to go throughout our stylesheet and change a property multiple times, we can now just change it inside our mixin. This can be really useful for specific styling of elements and vendor prefixes. When mixins are called from within a CSS selector, the mixin arguments are recognized and the styles inside the mixin are applied to the selector.

    Sass
    /* Sass mixin error with (optional) argument $borderWidth which defaults to 2px if not specified */
    @mixin error($borderWidth: 2px) {
      border: $borderWidth solid #F00;
      color: #F00;
    }
    
    .generic-error {
      padding: 20px;
      margin: 4px;
      @include error(); /* Applies styles from mixin error */
    }
    .login-error {
      left: 12px;
      position: absolute;
      top: 20px;
      @include error(5px); /* Applies styles from mixin error with argument $borderWidth equal to 5px*/
    }
    
    LESS
    /* LESS mixin error with (optional) argument @borderWidth which defaults to 2px if not specified */
    .error(@borderWidth: 2px) {
      border: @borderWidth solid #F00;
      color: #F00;
    }
    
    .generic-error {
      padding: 20px;
      margin: 4px;
      .error(); /* Applies styles from mixin error */
    }
    .login-error {
      left: 12px;
      position: absolute;
      top: 20px;
      .error(5px); /* Applies styles from mixin error with argument @borderWidth equal to 5px */
    }
    
    Stylus
    /* Stylus mixin error with (optional) argument borderWidth which defaults to 2px if not specified */
    error(borderWidth= 2px) {
      border: borderWidth solid #F00;
      color: #F00;
    }
    
    .generic-error {
      padding: 20px;
      margin: 4px;
      error(); /* Applies styles from mixin error */
    }
    .login-error {
      left: 12px;
      position: absolute;
      top: 20px;
      error(5px); /* Applies styles from mixin error with argument borderWidth equal to 5px */
    }
    
    Compiled CSS

    All the preprocessors compile to the same code below:

    .generic-error {
      padding: 20px;
      margin: 4px;
      border: 2px solid #f00;
      color: #f00;
    }
    .login-error {
      left: 12px;
      position: absolute;
      top: 20px;
      border: 5px solid #f00;
      color: #f00;
    }
    
    Inheritance

    When writing CSS the old-fashioned way, we could use the following code to apply the same styles to multiple elements at once:

    p,
    ul,
    ol {
      /* styles here */
    }
    

    That works great, but if we need to further style the elements individually, another selector has to be created for each and it can quickly get messier and harder to maintain. To counter this, inheritance can be used. Inheritance is the ability for other CSS selectors to inherit the properties of another selector.

    Sass & Stylus
    .block {
      margin: 10px 5px;
      padding: 2px;
    }
    
    p {
      @extend .block; /* Inherit styles from '.block' */
      border: 1px solid #EEE;
    }
    ul, ol {
      @extend .block; /* Inherit styles from '.block' */
      color: #333;
      text-transform: uppercase;
    }
    
    Compiled CSS (Sass & Stylus)
    .block, p, ul, ol {
      margin: 10px 5px;
      padding: 2px;
    }
    p {
      border: 1px solid #EEE;
    }
    ul, ol {
      color: #333;
      text-transform: uppercase;
    }
    
    LESS

    LESS doesn’t truly support inheriting styles like Sass and Stylus. Instead of adding multiple selectors to one set of properties, it treats inheritance like a mixin without arguments and imports the styles into their own selectors. The downside to this is that the properties are repeated in your compiled stylesheet. Here’s how you would set it up:

    .block {
      margin: 10px 5px;
      padding: 2px;
    }
    
    p {
      .block; /* Inherit styles from '.block' */
      border: 1px solid #EEE;
    }
    ul, ol {
      .block; /* Inherit styles from '.block' */
      color: #333;
      text-transform: uppercase;
    }
    
    Compiled CSS (LESS)
    .block {
      margin: 10px 5px;
      padding: 2px;
    }
    p {
      margin: 10px 5px;
      padding: 2px;
      border: 1px solid #EEE;
    }
    ul,
    ol {
      margin: 10px 5px;
      padding: 2px;
      color: #333;
      text-transform: uppercase;
    }
    

    As you can see, the styles from .block were inserted into the selectors that we wanted to give the inheritance to. It’s important to note that priority can become an issue here, so be cautious.

    Importing

    In the CSS community, importing CSS is frowned upon because it requires multiple HTTP requests. Importing with a preprocessor works differently, however. If you import a file from any of the three preprocessors, it will literally include the import during the compile, creating only one file. Keep in mind though that importing regular .css files compiles with the default @import "file.css"; code. Also, mixins and variables can be imported and used in your main stylesheet. Importation makes creating separate files for organization very worthwhile.

    Sass, LESS, & Stylus
    /* file.{type} */
    body {
      background: #EEE;
    }
    
    @import "reset.css";
    @import "file.{type}";
    
    p {
      background: #0982C1;
    }
    
    Compiled CSS
    @import "reset.css";
    body {
      background: #EEE;
    }
    p {
      background: #0982C1;
    }
    
    Color Functions

    Color functions are built in functions that will transform a color upon compilation. This can be extremely useful for creating gradients, darker hover colors, and much more.

    Sass
    lighten($color, 10%); /* returns a color 10% lighter than $color */
    darken($color, 10%);  /* returns a color 10% darker than $color */
    
    saturate($color, 10%);   /* returns a color 10% more saturated than $color */
    desaturate($color, 10%); /* returns a color 10% less saturated than $color */
    
    grayscale($color);  /* returns grayscale of $color */
    complement($color); /* returns complement color of $color */
    invert($color);     /* returns inverted color of $color */
    
    mix($color1, $color2, 50%); /* mix $color1 with $color2 with a weight of 50% */
    

    This is only a short list of the available color functions in Sass, a full list of available Sass color functions can be found by reading the Sass Documentation.

    Color functions can be used anywhere that a color is valid CSS. Here’s an example:

    $color: #0982C1;
    
    h1 {
      background: $color;
      border: 3px solid darken($color, 50%);
    }
    
    LESS
    lighten(@color, 10%); /* returns a color 10% lighter than @color */
    darken(@color, 10%);  /* returns a color 10% darker than @color */
    
    saturate(@color, 10%);   /* returns a color 10% more saturated than @color */
    desaturate(@color, 10%); /* returns a color 10% less saturated than @color */
    
    spin(@color, 10);  /* returns a color with a 10 degree larger in hue than @color */
    spin(@color, -10); /* returns a color with a 10 degree smaller hue than @color */
    
    mix(@color1, @color2); /* return a mix of @color1 and @color2 */
    

    A list of all the LESS functions can be found by reading the LESS Documentation.

    Here’s an example of how to use a color function in LESS:

    @color: #0982C1;
    
    h1 {
      background: @color;
      border: 3px solid darken(@color, 50%);
    }
    
    Stylus
    lighten(color, 10%); /* returns a color 10% lighter than 'color' */
    darken(color, 10%);  /* returns a color 10% darker than 'color' */
    
    saturate(color, 10%);   /* returns a color 10% more saturated than 'color' */
    desaturate(color, 10%); /* returns a color 10% less saturated than 'color' */
    

    A full list of all the Stylus color functions can be found by reading the Stylus Documentation.

    Here’s an example using Stylus color functions:

    color = #0982C1
    
    h1
      background color
      border 3px solid darken(color, 50%)
    
    Operations

    Doing math in CSS is quite useful, and now fully possible. It’s simple and this is how to do it:

    Sass, LESS, & Stylus
    body {
      margin: (14px/2);
      top: 50px + 100px;
      right: 100px - 50px;
      left: 10 * 10;
    }
    
    Practical Applications

    We have covered a lot of the features and new things that preprocessors can do, but we haven’t covered anything hands-on or practical. Here’s a short list of real-world applications where using a preprocessor is a life-saver.

    Vendor Prefixes

    This is one of the hyped up reasons to use a preprocessor and for a very good reason—it saves loads of time and tears. Creating a mixin to handle vendor prefixes is easy and saves a lot of repetition and painful editing. Here’s how to do it:

    Sass
    @mixin border-radius($values) {
      -webkit-border-radius: $values;
         -moz-border-radius: $values;
              border-radius: $values;
    }
    
    div {
      @include border-radius(10px);
    }
    
    LESS
    .border-radius(@values) {
      -webkit-border-radius: @values;
         -moz-border-radius: @values;
              border-radius: @values;
    }
    
    div {
      .border-radius(10px);
    }
    
    Stylus
    border-radius(values) {
      -webkit-border-radius: values;
         -moz-border-radius: values;
              border-radius: values;
    }
    
    div {
      border-radius(10px);
    }
    
    Compiled CSS
    div {
      -webkit-border-radius: 10px;
         -moz-border-radius: 10px;
              border-radius: 10px;
    }
    
    3D Text

    Faking 3D text using multiple text-shadows is a clever idea. The only problem is that changing the color after the fact is difficult and cumbersome. Using mixins and color functions, we can create 3D text and change the color on the fly!

    Sass
    @mixin text3d($color) {
      color: $color;
      text-shadow: 1px 1px 0px darken($color, 5%),
                   2px 2px 0px darken($color, 10%),
                   3px 3px 0px darken($color, 15%),
                   4px 4px 0px darken($color, 20%),
                   4px 4px 2px #000;
    }
    
    h1 {
      font-size: 32pt;
      @include text3d(#0982c1);
    }
    
    LESS
    .text3d(@color) {
      color: @color;
      text-shadow: 1px 1px 0px darken(@color, 5%),
                   2px 2px 0px darken(@color, 10%),
                   3px 3px 0px darken(@color, 15%),
                   4px 4px 0px darken(@color, 20%),
                   4px 4px 2px #000;
    }
    
    span {
      font-size: 32pt;
      .text3d(#0982c1);
    }
    
    Stylus
    text3d(color)
      color: color
      text-shadow: 1px 1px 0px darken(color, 5%), 2px 2px 0px darken(color, 10%), 3px 3px 0px darken(color, 15%), 4px 4px 0px darken(color, 20%), 4px 4px 2px #000
    span
      font-size: 32pt
      text3d(#0982c1)
    

    I chose to write the Stylus text-shadows on one line because I omitted the curly brackets.

    Compiled CSS
    span {
      font-size: 32pt;
      color: #0982c1;
      text-shadow: 1px 1px 0px #097bb7,
                   2px 2px 0px #0875ae,
                   3px 3px 0px #086fa4,
                   4px 4px 0px #07689a,
                   4px 4px 2px #000;
    }
    
    End Result Columns

    Using number operations and variables for columns is an idea I came up with when I was first playing with CSS preprocessors. By declaring a desired width in a variable, we can easily change it down the road without any mental-math. Here’s how it’s done:

    Sass
    $siteWidth: 1024px;
    $gutterWidth: 20px;
    $sidebarWidth: 300px;
    
    body {
      margin: 0 auto;
      width: $siteWidth;
    }
    .content {
      float: left;
      width: $siteWidth - ($sidebarWidth+$gutterWidth);
    }
    .sidebar {
      float: left;
      margin-left: $gutterWidth;
      width: $sidebarWidth;
    }
    
    LESS
    @siteWidth: 1024px;
    @gutterWidth: 20px;
    @sidebarWidth: 300px;
    
    body {
      margin: 0 auto;
      width: @siteWidth;
    }
    .content {
      float: left;
      width: @siteWidth - (@sidebarWidth+@gutterWidth);
    }
    .sidebar {
      float: left;
      margin-left: @gutterWidth;
      width: @sidebarWidth;
    }
    
    Stylus
    siteWidth = 1024px;
    gutterWidth = 20px;
    sidebarWidth = 300px;
    
    body {
      margin: 0 auto;
      width: siteWidth;
    }
    .content {
      float: left;
      width: siteWidth - (sidebarWidth+gutterWidth);
    }
    .sidebar {
      float: left;
      margin-left: gutterWidth;
      width: sidebarWidth;
    }
    
    Compiled CSS
    body {
      margin: 0 auto;
      width: 1024px;
    }
    .content {
      float: left;
      width: 704px;
    }
    .sidebar {
      float: left;
      margin-left: 20px;
      width: 300px;
    }
    
    Notable Quirks

    There are quite a few quirks to using a CSS preprocessor. I’m going to go over a few of the fun ones, but if you’re really interested in finding them all I recommend you scour the documentation or, better yet, just start using a preprocessor in your daily coding.

    Error Reporting

    If you’ve written CSS for any decent amount of time, I am sure you have reached a point where you had an error somewhere and simply could not find it. If you’re anything like me you probably spent the afternoon pulling your hair out and commenting out various things to hunt the error down.

    CSS preprocessors report errors. It’s just that simple. If there’s something wrong with your code it tells you where, and if you’re lucky: why. You can check out this blog post if you’re interested in seeing how errors are reported in the different preprocessors.

    Comments

    When compiling with a CSS preprocessor, any double-slash comment gets removed (e.g. //comment) and any slash-asterisk comment stays (e.g. /* comment */). That being said, use double-slash for comments you want on the non-compiled side and slash-asterisk for comments you want visible after the compilation.

    Just a note: if you compile minified, all comments are removed.

    Conclusion

    Each CSS preprocessor we covered (Sass, LESS, and Stylus) has its own unique way of accomplishing the same task— giving developers the ability to use useful, unsupported features while keeping browser compatibility and code cleanliness.

    While not a requirement for development, preprocessors can save a lot of time and have some very useful features.

    I encourage you all to try as many of the preprocessors as possible so that you can effectively choose a favorite and know why it is favored over the numerous others. If you haven’t yet tried using a preprocessor to write your CSS, I highly recommend you give it a try.

    Do you have a favorite CSS preprocessor feature I didn’t mention? Is there something one can do that another cannot? Let us know in the comments below!

    A special thanks to Karissa Smith, a super-talented friend of mine that created the preview thumbnail for this article.


  • Permalink for 'Build a Contacts Manager Using Backbone.js: Part 2'

    Build a Contacts Manager Using Backbone.js: Part 2

    Posted: March 8th, 2012, 10:00am MST by Dan Wellman

    Welcome back to part two of this tutorial; in part one we looked at some of the model, collection and view basics for when working with Backbone and saw how to render individual contact views using a master view bound to a collection.

    In this part of the tutorial, we’re going to look at how we can filter our view based on user input, and how we can add a router to give our basic application some URL functionality.
    We’ll need the source files from part one as we’ll be building on the existing code for this part. I’d strongly recommend reading part one if you haven’t already.

    Reacting to User Input

    You may have noticed in part one that each of our individual models has an attributed called type which categorises each model based on whether it relates to a friend, family member of colleague. Let’s add a select element to our master view that will let the user filter the contacts based on these types.

    Now, we can hardcode a select menu into our underlying HTML and manually add options for each of the different types. But, this wouldn’t be very forward thinking; what if we add a new type later on, or delete all of the contacts of a certain type? Our application doesn’t yet have the capability to add or remove contacts (part three spoiler alert!), but it’s still best to take these kinds of things into consideration, even at this early stage of our application.

    As such, we can easily build a select element dynamically based on the existing types. We will add a tiny bit of HTML to the underlying page first; add the following new elements to the contacts container:

    <header>
        <div id="filter"><label>Show me:</label></div>
    </header>

    That’s it, we’ve an outer <header> element to act as a general container, within which is another container with an id attribute, and a <label> with some explanatory text.

    Now let’s build the <select> element. First we’ll add two new methods to our DirectoryView mater view; the first one will extract each unique type and the second will actually build the drop-down. Both methods should be added to the end of the view:

    getTypes: function () {
        return _.uniq(this.collection.pluck("type"), false, function (type) {
            return type.toLowerCase();
        });
    },
    
    createSelect: function () {
        var filter = this.el.find("#filter"),
            select = $("<select/>", {
                html: "<option>All</option>"
            });
    
        _.each(this.getTypes(), function (item) {
            var option = $("<option/>", {
                value: item.toLowerCase(),
                text: item.toLowerCase()
            }).appendTo(select);
        });
        return select;
    }

    The first of our methods, getTypes() returns an array created using Underscore’s uniq() method. This method accepts an array as an argument and returns a new array containing only unique items. The array we pass into the uniq() method is generated using Backbone’s pluck() method, which is a simple way to pull all values of a single attribute out of a collection of models. The attribute we are interested in here is the type attribute.

    In order to prevent case issues later on, we should also normalise the types to lowercase. We can use an iterator function, supplied as the third argument to uniq(), to transform each value before it is put through the comparator. The function receives the current item as an argument so we just return the item in lowercase format. The second argument passed to uniq(), which we set to false here, is a flag used to indicate whether the array that is being compared has been sorted.

    The second method, createSelect() is slightly larger, but not much more complex. Its only purpose is to create and return a new <select> element, so we can call this method from somewhere else in our code and receive a shiny new drop-down box with an option for each of our types. We start by giving the new <select element a default <option> with the text All.

    We then use Underscore’s each() method to iterate over each value in the array returned by our getTypes() method. For each item in the array we create a new <option> element, set its text to the value of the current item (in lowercase) and then append it to the <select>.

    To actually render the <select> element to the page, we can add some code to our master view’s initialize() method:

    this.$el.find("#filter").append(this.createSelect());

    The container for our master view is cached in the $el property that Backbone automatically adds to our view class, so we use this to find the filter container and append the <select element to it.

    If we run the page now, we should see our new <select> element, with an option for each of the different types of contact:

    Filtering the View

    So now we have our <select menu, we can add the functionality to filter the view when an option is selected. To do this, we can make use of the master view’s events attribute to add a UI event handler. Add the following code directly after our renderSelect() method:

    events: {
        "change #filter select": "setFilter"
    },

    The events attribute accepts an object of key:value pairs where each key specifies the type of event and a selector to bind the event handler to. In this case we are interested in the change event that will be fired by the <select element within the #filter container. Each value in the object is the event handler which should be bound; in this case we specify setFilter as the handler.

    Next we can add the new handler:

    setFilter: function (e) {
        this.filterType = e.currentTarget.value;
        this.trigger("change:filterType");
    },

    All we need to do in the setFilter() function is set a property on the master view called filterType, which we set to the value of the option that was selected, which is available via the currentTarget property of the event object that is automatically passed to our handler.

    Once the property has been added or updated we can also trigger a custom change event for it using the property name as a namespace. We’ll look at how we can use this custom event in just a moment, but before we do, we can add the function that will actually perform the filter; after the setFilter() method add the following code:

    filterByType: function () {
        if (this.filterType === "all") {
            this.collection.reset(contacts);
        } else {
            this.collection.reset(contacts, { silent: true });
    
            var filterType = this.filterType,
                filtered = _.filter(this.collection.models, function (item) {
                return item.get("type").toLowerCase() === filterType;
            });
    
            this.collection.reset(filtered);
        }
    }

    We first check whether the master view’s filterType property is set to all; if it is, we simply repopulate the collection with the complete set of models, the data for which is stored locally on our contacts array.

    If the property does not equal all, we still reset the collection to get all the contacts back in the collection, which is required in order to switch between the different types of contact, but this time we set the silent option to true (you’ll see why this is necessary in a moment) so that the reset event is not fired.

    We then store a local version of the view’s filterType property so that we can reference it within a callback function. We use Underscore’s filter() method to filter the collection of models. The filter() method accepts the array to filter and a callback function to execute for each item in the array being filtered. The callback function is passed the current item as an argument.

    The callback function will return true for each item that has a type attribute equal to the value that we just stored in the variable. The types are converted to lowercase again, for the same reason as before. Any items that the callback function returns false for are removed from the array.

    Once the array has been filtered, we call the reset() method once more, passing in the filtered array. Now we’re ready to add the code that will wire up the setType() method, the filterType property and filterByType() method.

    Binding Events to the Collection

    As well as binding UI events to our interface using the events attribute, we can also bind event handlers to collections. In our setFilter() method we fired a custom event, we now need to add the code that will bind the filterByType() method to this event; add the following code to the initialize() method of our master view:

    this.on("change:filterType", this.filterByType, this);

    We use Backbone’s on() method in order to listen for our custom event. We specify the filterByType() method as the handler function for this event using the second argument of on(), and can also set the context for the callback function by setting this as the third argument. The this object here refers to our master view.

    In our filterByType function, we reset the collection in order to repopulate it with either all of the models, or the filtered models. We can also bind to the reset event in order to repopulate the collection with model instances. We can specify a handler function for this event as well, and the great thing is, we’ve already got the function. Add the following line of code directly after the change event binding:

    this.collection.on("reset", this.render, this);

    In this case we’re listening for the reset event and the function we wish to invoke is the collection’s render() method. We also specify that the callback should use this (as in the instance of the master view) as its context when it is executed. If we don’t supply this as the third argument, we will not be able to access the collection inside the render() method when it handles the reset event.

    At this point, we should now find that we can use the select box to display subsets of our contacts. The reason why we set the silent option to true in our filterByType() method is so that the view is not re-rendered unnecessarily when we reset the collection at the start of the second branch of the conditional. We need to do this so that we can filter by one type, and then filter by another type without losing any models.

    Routing

    So, what we’ve got so far is alright, we can filter our models using the select box. But wouldn’t it be awesome if we could filter the collection using a URL as well? Backbone’s router module gives us this ability, let’s see how, and because of the nicely decoupled way that we’ve structured our filtering so far, it’s actually really easy to add this functionality. First we need to extend the Router module; add the following code after the master view:

    var ContactsRouter = Backbone.Router.extend({
        routes: {
            "filter/:type": "urlFilter"
        },
    
        urlFilter: function (type) {
            directory.filterType = type;
            directory.trigger("change:filterType");
        }
    });

    The first property we define in the object passed to the Router’s extend() method is routes, which should be an object literal where each key is a URL to match and each value is a callback function when the URL is matched. In this case we are looking for URLs that start with #filter and end with anything else. The part of the URL after the filter/ part is passed to the function we specify as the callback function.

    Within this function we set or update the filterType property of the master view and then trigger our custom change event once again. This is all we need to do in order to add filtering functionality using the URL. We still need to create an instance of our router however, which we can do by adding the following line of code directly after the DirectoryView instantiation:

    var contactsRouter = new ContactsRouter();

    We should now be able to enter a URL such as #filter/family and the view will re-render itself to show just the contacts with the type family:

    So that’s pretty cool right? But there’s still one part missing – how will users know to use our nice URLs? We need to update the function that handles UI events on the <select element so that the URL is updated when the select box is used.

    To do this requires two steps; first of all we should enable Backbone’s history support by starting the history service after our app is initialised; add the following line of code right at the end of our script file (directly after we initialise our router):

    Backbone.history.start();

    From this point onwards, Backbone will monitor the URL for hash changes. Now, when we want to update the URL after something happens, we just call the navigate() method of our router. Change the filterByType() method so that it appears like this:

    filterByType: function () {
        if (this.filterType === "all") {
            this.collection.reset(contacts);
    
            <b>contactsRouter.navigate("filter/all");</b>
    
        } else {
            this.collection.reset(contacts, { silent: true });
    
            var filterType = this.filterType,
                filtered = _.filter(this.collection.models, function (item) {
                    return item.get("type") === filterType;
            });
    
            this.collection.reset(filtered);
    
            <b>contactsRouter.navigate("filter/" + filterType);</b>
        }
    }

    Now when the select box is used to filter the collection, the URL will be updated and the user can then bookmark or share the URL, and the back and forward buttons of the browser will navigate between states. Since version 0.5 Backbone has also supported the pushState API, however, in order for this to work correctly the server must be able to render the pages that are requested, which we have not configured for this example, hence using the standard history module.

    Summary

    In this part of the tutorial, we looked at a couple more Backbone modules, specifically the Router, History and Events modules. We’ve now looked at all of the different modules that come with Backbone.

    We also looked at some more Underscore methods, including filter(), which we used to filter down our collection to only those models containing a specific type.

    Lastly, we looked at Backbone’s Router module, which allowed us to set routes that can be matched by our application in order to trigger methods, and the History module which we can use to remember state and keep the URL updated with hash fragments.

    One point to take away is the loosely coupled nature of our filtering functionality; when we added filtering via the select menu, it was done in such a way that it was very quick and easy to come along afterwards and add a completely new method of filtering without having to change our filter() method. This is one of the keys to successfully building non-trivial, maintainable and scalable JavaScript applications. If we wanted, it would be very easy to add another, completely new method of filtering, which having to change our filtering method.

    In the next part of this series, we’ll go back to working with models and see how we can remove models from, and add new ones to the collection.


  • Permalink for 'Decoding HTML5: My New Book'

    Decoding HTML5: My New Book

    Posted: March 8th, 2012, 8:54am MST by Jeffrey Way

    Hey guys! I have a few fun things to announce. After months of work, my new book, Decoding HTML5, is finally available. Even better, though, I’ve managed to work out a special arrangement with Rockable Press to offer much, much more.

    The Book - $19 Decoding HTML5

    Toying with new JavaScript APIs is like Christmas for me!

    Toying with new JavaScript APIs is like Christmas for me! So when I set out to write this book, I had one goal in mind: decipher that incredibly confusing spec into something that any John Q. designer or developer can understand. It’s what I wish I had in the beginning.

    Have you ever found yourself thinking, “I wish there was somebody who could sit next to me and make me understand this code…because I don’t!” I’ve been in that position countless times.

    Well, if you can relate, I think this book just might do the trick. Rather than using high level jargon that no beginner could possibly understand, I’ve done my best to break these complicated concepts into chunks that everyone can grasp.

    I cover everything from the new semantic elements, to form enhancements, to a variety of the new JavaScript APIs, such as web workers, web storage, and geolocation.

    Now Available: $19 HTML5 Fundamentals

    In addition to the book, I’ve also released my latest Tuts+ Premium course, called “HTML5 Fundamentals.

    HTML5 Fundamentals Screencast Course

    Split into two chunks, this first course – geared specifically for those of you who prefer visual training – will get you up and running with HTML5 in no time. It’s the perfect companion to Decoding HTML5. The follow-up, “Advanced HTML5,” is scheduled for May-June.

    A Special Arrangement

    I’m very excited to announce that I was able to work out a special arrangement with Rockable Press.

    Beginning today, Decoding HTML5 has already been added to the Tuts+ Premium library.

    For those unfamiliar, Tuts+ Premium provides top-notch education in the creative fields. You might be familiar with the massively popular (and free) “30 Days To Learn jQuery“? That was part of Tuts+ Premium, and there are countless more courses and ebooks on the site just like it. A monthly membership to the site is $19.

    So what this means is that you have two choices, if you’d like to pick this book up:

    Overall, I really hope you enjoy the book!


  • Permalink for 'Sexy Code Snippet Management With Gists'

    Sexy Code Snippet Management With Gists

    Posted: March 6th, 2012, 1:59pm MST by Jeffrey Way

    I’ve always struggled to find the perfect code snippet management tool…until now (and it’s free). I’ll show you my preferred workflow, using GitHub Gists and Sublime Text 2.

    View at 720p for optimal viewing. Summary

    So that’s the system I prefer these days; do you have a better method?


  • Permalink for 'PHP 5.4 is Here! What You Must Know'

    PHP 5.4 is Here! What You Must Know

    Posted: March 5th, 2012, 9:05am MST by Dejan Marjanovic

    PHP 5.4 is here; the next major step forward since version 5.3 – keeping PHP 6 (full Unicode support) on hold for now. The latest enhancements significantly improve its elegance, while removing deprecated functionality, resulting in a dramatic optimization of the runtime (up to 20% more speed and memory usage reduction).

    brace yourself New Features and Improvements

    Some of the key new features include traits, a shortened array syntax, a built-in webserver for testing purposes, use of $this in closures, class member access on instantiation, <?= is always available, and more!

    PHP 5.4.0 significantly improves performance, memory footprint and fixes over 100 bugs. Notable deprecated/removed features include register_globals, magic_quotes (about time) and safe_mode. Also worth mentioning is the fact that multibyte support is enabled by default and default_charset has been changed from ISO-8859-1 to UTF-8.

    Content-Type: text/html; charset=utf-8 is always sent; so there’s no need to set that HTML meta tag, or send additional headers for UTF-8 compatibility.

    Traits

    The best demonstration of traits is when multiple classes share the same functionality.

    Traits (horizontal reuse/multiple inheritance) are a set of methods, which are structurally similar to a class (but can’t be instantiated), that can enable developers to reuse sets of methods freely in several independent classes. Because PHP is a single inheritance language, a subclass can inherit from only one superclass; that’s where traits come to play.

    The best use of traits is demonstrated when multiple classes share the same functionality. For instance, imagine that we are building some website, and need to use both the Facebook and Twitter APIs. We build two classes which, in common, have a cURL wrapper function/method. Instead of performing the classic copy & paste of that method – to be used in two classes – we use Traits (copy & paste, compiler style). This way, we make reusable code, and follow the DRY (Don’t Repeat Yourself) principle.

    Here’s an example:

    /** cURL wrapper trait */
    trait cURL
    {
        public function curl($url)
        {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($ch);
            curl_close($ch);
            return $output;
        }
    }
    
    /** Twitter API Class */
    class Twitter_API
    {
        use cURL; // use trait here
        public function get($url)
        {
            return json_decode($this->curl('http://api.twitter.com/'.$url));
        }
    }
    
    /** Facebook API Class */
    class Facebook_API
    {
        use cURL; // and here
        public function get($url)
        {
            return json_decode($this->curl('http://graph.facebook.com/'.$url));
        }
    }
    
    $facebook = new Facebook_API();
    echo $facebook->get('500058753')->name; // Rasmus Lerdorf
    
    /** Now demonstrating the awesomeness of PHP 5.4 syntax */
    echo (new Facebook_API)->get('500058753')->name; // Rasmus Lerdorf
    $foo = 'get';
    echo (new Facebook_API)->$foo('500058753')->name; // and again, Rasmus Lerdorf
    echo (new Twitter_API)->get('1/users/show.json?screen_name=rasmus')->name; // and yet again, Rasmus Lerdorf
    // P.S. I'm not obsessed with Rasmus :)
    

    Got it? No? Here is the simplest example!

    trait Net
    {
        public function net()
        {
            return 'Net';
        }
    }
    
    trait Tuts
    {
        public function tuts()
        {
            return 'Tuts';
        }
    }
    
    class NetTuts
    {
        use Net, Tuts;
        public function plus()
        {
            return '+';
        }
    }
    
    $o = new NetTuts;
    echo $o->net(), $o->tuts(), $o->plus();
    echo (new NetTuts)->net(), (new NetTuts)->tuts(), (new NetTuts)->plus();
    

    If you have any question about traits, please post a note in the comments section below.

    Important Tip: The magic constant for traits is __TRAIT__.

    Built-in CLI Web-Server

    In web development, PHP’s best friend is Apache [HTTPD] Server. Sometimes, though, it can be overkill to set up [httpd.conf] just to use it within a development environment, when you really need tiny web server that can be launched with a simple command line. Thankfully, PHP 5,4 comes with a built-in CLI web server.

    The PHP CLI web server is designed for developmental purposes only, and should not be used in production.

    Note: The instructions below are for a Windows environment.

    Step 1 – Create Document Root Directory, Router File and Index File

    Go to your hard drive root (assuming C:\). Create a directory/folder, called public_html. Create a new file within this folder, and name it router.php. Copy the contents below, and paste it into this newly created file.

    <?php
    // router.php
    if (preg_match('#\.php$#', $_SERVER['REQUEST_URI']))
    {
        require basename($_SERVER['REQUEST_URI']); // serve php file
    }
    else if (strpos($_SERVER['REQUEST_URI'], '.') !== false)
    {
        return false; // serve file as-is
    }
    ?>
    

    Now, create another file, called index.php. Copy the contents below and save the file.

    <?php
    // index.php
    echo 'Hello Nettuts+ Readers!';
    ?>
    

    Open your php.ini file (it is located in the PHP install directory – e.g. C:\php).

    Find the include_path settings (it is located at ~708th line). Add C:\public_html to the end of the string between quotes, separate by a semicolon. The final result should look like:

    include_path = ".;C:\php\PEAR;C:\public_html"
    

    Save and close the file. On to next step.

    Step 2 – Run Web-Server

    Open the command prompt (Windows + R, type in cmd, hit Enter); you should see something like this, depending on your Windows version.

    Microsoft Windows XP [Version 5.1.2600]
    (C) Copyright 1985-2001 Microsoft Corp.
    C:\Documents and Settings\nettuts>
    

    Change your current directory to the PHP installation by following the example below:

    C:\Documents and Settings\nettuts>cd C:\php
    C:\php>
    

    Here comes the most important part – running the web-server. Copy…

    php -S 0.0.0.0:8080 -t C:\public_html router.php
    

    … and paste it in the command prompt (right mouse button, click Paste to paste). Hit Enter. If all goes well, you should see something similar to what’s shown below. Do not close the command prompt; if you do, you will exit the web-server as well.

    C:\php>php -S 0.0.0.0:8080 -t C:\public_html router.php
    PHP 5.4.0 Development Server started at Fri Mar 02 09:36:40 2012
    Listening on 0.0.0.0:8080
    Document root is C:\public_html
    Press Ctrl-C to quit.
    

    Open up http://localhost:8080/index.php in your browser and you should see:

    Hello Nettuts+ Readers!
    

    Voila! That’s it, happy coding!

    Tip 1: Make a php-server.bat file with the following contents: C:\php\php -S 0.0.0.0:8080 -t C:\public_html router.php. Double click it, and, now, the server is up and running!

    Tip 2: Use 0.0.0.0 instead of localhost if you anticipate that your server will be accessed from the internet.

    Shorter Array Syntax

    PHP 5.4 offers a new shorter array syntax:

    $fruits = array('apples', 'oranges', 'bananas'); // "old" way
    
    // The same as Javascript's literal array notation
    $fruits = ['apples', 'oranges', 'bananas'];
    
    // associative array
    $array = [
        'foo' => 'bar',
        'bar' => 'foo'
    ];
    

    Please note that “old” method is still in use and always will be. This is simply an alternative.

    Array Dereferencing

    No more temporary variables when dealing with arrays!

    Let’s imagine that we want to retrieve the middle name of Alan Mathison Turing:

    echo explode(' ', 'Alan Mathison Turing')[1]; // Mathison
    

    Sweet; but it wasn’t always this easy. Before 5.4, we had to do:

    $tmp = explode(' ', 'Alan Mathison Turing');
    echo $tmp[1]; // Mathison
    

    Now, what if we want to get the last name (last element in array):

    echo end(explode(' ', 'Alan Mathison Turing')); // Turing
    

    This works fine, however, it will throw a E_STRICT (Strict Standards: Only variables should be passed by reference) error, since it became part of E_ALL in error_reporting.

    Here’s a slightly more advanced example:

    function foobar()
    {
        return ['foo' => ['bar' => 'Hello']];
    }
    echo foobar()['foo']['bar']; // Hello
    
    $this In Anonymous Functions
    this is anonymous functions

    You can now refer to the object instance from anonymous functions (also known as closures) by using $this.

    class Foo
    {
        function hello() {
            echo 'Hello Nettuts!';
        }
    
        function anonymous()
        {
            return function() {
                $this->hello(); // $this wasn't possible before
            };
        }
    }
    
    class Bar
    {
        function __construct(Foo $o) // object of class Foo typehint
        {
            $x = $o->anonymous(); // get Foo::hello()
            $x(); // execute Foo::hello()
        }
    }
    new Bar(new Foo); // Hello Nettuts!
    

    Note that this could be achieved prior to 5.4, but it was overkill.

        function anonymous()
        {
            $that = $this; // $that is now $this
            return function() use ($that) {
                $that->hello();
            };
        }
    
    <?= is Always On

    Regardless of the php.ini setting, short_open_tag, <?= (open PHP tag and echo) will always be available. This means that you can now safely use:

    <?=$title?>
    

    …in your templates instead of…

    <?php echo $title ?>
    
    Binary Number Representation
    binary php

    There are only 0b10 kinds of people;
    those who understand binary and those who don’t.

    From now on, integers can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation, optionally preceded by a sign (- or +). To use octal notation, precede the number with a 0 (zero). To use hexadecimal notation, precede the number with 0x. To use binary notation, precede the number with 0b.

    Example: representation of number 31 (decimal).

    echo 0b11111; // binary, introduced in PHP 5.4
    echo 31; // duh
    echo 0x1f; // hexadecimal
    echo 037; // octal
    
    Callable Typehint
    wuts dat

    Typehinting is for those who desire to make PHP a stronger typed language. Type Hints can only be of the object and array type since PHP 5.1, and callable since PHP 5.4. Traditional type hinting with int and string isn’t yet supported.

    function my_function(callable $x)
    {
        return $x();
    }
    
    function my_callback_function(){return 'Hello Nettuts!';}
    
    class Hello{static function hi(){return 'Hello Nettuts!';}}
    class Hi{function hello(){return 'Hello Nettuts!';}}
    
    echo my_function(function(){return 'Hello Nettuts!';}); // anonymous function
    echo my_function('my_callback_function'); // callback function
    echo my_function(['Hello', 'hi']); // class name, static method
    echo my_function([(new Hi), 'hello']); // class object, method name
    
    Initialized High Precision Timer

    $_SERVER['REQUEST_TIME_FLOAT'] has been added, with microsecond precision (float). This is useful when you need to calculate the execution time for a script.

    echo 'Executed in ', round(microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'], 2), 's';
    
    __destruct() (or Summary)

    Overall, PHP 5.4 offers numerous improvements. Now, it’s up to you to grab a fresh copy from php.net, and make quality Object-Oriented PHP code!

    What do you think PHP 5.5 will bring us, and what do you expect?


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

    Best of Tuts+ in February 2012

    Posted: March 2nd, 2012, 10:30am 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 Baseball-Inspired Text Effect in Photoshop Create a Baseball-Inspired Text Effect in Photoshop

      Applying texture to a text effect can be a lot of fun. In this tutorial we will explain how to create a baseball-inspired text effect using layer styles, patterns, and brushes. Let’s get started!

      Visit Article

    • Create a Mini Planet Using Photoshop’s 3D Capabilities Create a Mini Planet Using Photoshop’s 3D Capabilities

      When most people think about Photoshop, they probably don’t think about 3D. What most people don’t realize, however, is that Photoshop CS5 Extended includes some powerful tools to help you render your artwork in 3D. In this tutorial we will demonstrate how to create a mini planet using Photoshop’s 3D capabilities. Let’s get started!

      Visit Article

    • Create a Coffee Cake Photo Manipulation – Tuts+ Premium Tutorial Create a Coffee Cake Photo Manipulation – Tuts+ Premium Tutorial

      In this Tuts+ Premium tutorial, author Stephen Petrany will demonstrate how to take pieces from multiple photos and seamlessly blend them into a "coffee cake" photo manipulation. This tutorial will also explore unique ways to work with paths and smart objects. If you are looking to take your photo manipulation skills to the next level then Log in or Join Now to get started!

      Visit Article

    • Nettuts+ — Web Development Tutorials
    • The Largest jQuery Class in the World The Largest jQuery Class in the World

      A couple weeks ago, Tuts+ Premium launched a free new real-time course, called “30 Days to Learn jQuery.” After signing up, each member receives an email, linking to a new video lesson for an entire month.

      Visit Article

    • How to Customize Your Command Prompt How to Customize Your Command Prompt

      Lately, I’ve been getting this question a lot: “how did you get your terminal to look the way it does?” If you’ve noticed my terminal and are curious about how I set it up, this is the tutorial for you! Of course, what you learn here will be enough to get you started on creating your own custom command prompt, as well!

      Visit Article

    • NewRelic is your Secret Weapon Attention Developers: NewRelic is your Secret Weapon

      While the title of this article may sound like a cliche, hatched in the bowels of PR hell, I’m serious when I say that NewRelic is your secret weapon.

      Visit Article

    • Vectortuts+ — Illustrator Tutorials
    • How to Create a Vintage Type Postcard How to Create a Vintage Type Postcard

      Follow this in-depth look at the process of designing type for a vintage style postcard in Adobe Illustrator CS5. Harken back to an era when postcards were all the rage with this friendly type style. The tutorial will delve into clipping masks, using bitmap images, working with layers and type effects.

      Visit Article

    • Create a Block Game Interface in Illustrator Create a Block Game Interface in Illustrator

      In the following tutorial you will learn how to create a block game interface in Adobe Illustrator CS5. Vector game graphics allow for versatile artwork. The workflow presented in this tutorial will teach you how to create game graphics in Illustrator. These techniques can be applied to multiple interface design and game design projects. It’s time to jump in, learn to create these shapes, and give them colorful graphic depth.

      Visit Article

    • 25+ Illustrator Tutorials for Creating Vintage Graphics and Retro Illustration Illustrator Tutorials for Creating Vintage Graphics and Retro Illustration

      If youre looking to improve your vector design skills, learn how to use Illustrator on a deeper level, and discover how to create vintage vector graphics, then you’ve landed on the right article. We’ve assembled a collection of tutorials that show you how to create vintage illustrations, and retro graphics using Illustrator effects and a variety of professional workflows.

      Visit Article

    • Webdesigntuts+ — Web Design Tutorials
    • Principles for Successful Button Design Principles for Successful Button Design

      There are a thousand ways to design and create buttons today and you only need to spend a small amount of time looking through work on dribbble to get a sense of them. A great deal of these examples are exactly the same, but occasionally there are the odd few that feel like they’ve had a little more care and attention in their making.

      Visit Article

    • The CSS3 Version Orman Clark’s Vertical Navigation Menu: The CSS3 Version

      Next in the Orman Clark’s coded PSD series is his awesome looking Vertical Navigation Menu. We’ll recreate it with CSS3 and jQuery while using the minimal amount of images possible.

      Visit Article

    • Login Page Coding the SimpleAdmin Theme: Login Page

      It’s time to translate our admin layout into a working template. We’ll begin by setting out the markup for our Login page, then we’ll hit the stylesheets..

      Visit Article

    • Phototuts+ — Photography Tutorials
    • Exploring Stock Photography The Stock Market: Exploring Stock Photography

      Creative professionals all over the world frequently require high quality images, but often don’t have the budget to hire a photographer for small projects. Enter stock photography: an industry where awesome photographs are out there and ripe for the using. Today, we’ll be taking a look at the wild world of the stock market – stock photography, that is.

      Visit Article

    • Packed with New Features Lightroom 4 Beta: Packed with New Features

      In six short years, Adoble Lightroom has changed the way many photographers manage their images. With powerful cataloging and developing features, Lightroom offers photographers the ability to customize their photo management workflow and manage the thousands of images more efficiently than ever before. Adobe’s innovation continues with Lightroom 4, which is currently in Beta. Today, we’ll be taking a look at some of the new features of the latest iteration of Lightroom.

      Visit Article

    • A Primer to Digital Medium Format Camera A Primer to Digital Medium Format Camera

      Over the last few months, I’ve observed a trend among several well known photographers. No longer satisfied with crop factor cameras or even 35mm equivalent full frame digital cameras, more and more photographers are jumping to digital medium format. What are the advantages offered by digital medium formats, and will you be using one anytime soon? Read on to find out.

      Visit Article

    • Cgtuts+ — Computer Graphics Tutorials
    • Reception Area Render With 3D Studio Max & V-Ray, Part 1 Achieving 3D Realism: Reception Area Render With 3D Studio Max & V-Ray, Part 1

      The following tutorial is based on a real project. This unique tutorial will take users through the real process of creating shaders with bespoke physical properties and applying textures based on real photo references.

      Visit Article

    • Create And Render A Still Life Scene In Blender, Using Cycles Create And Render A Still Life Scene In Blender, Using Cycles

      Today, we’ll have a brief introduction to Blender’s new rendering engine – Cycles. This tutorial will cover modeling a small and easy still life scene, setting up different types of materials used in cycles and then finally lighting and rendering the scene.

      Visit Article

    • An Introduction To UVMapping In 3d Studio Max Using The Unwrap UVW Modifier An Introduction To UVMapping In 3d Studio Max Using The Unwrap UVW Modifier

      So UVMapping… you hate it, I hate it. But unfortunately it’s a necessary step in the process of completing most cg projects. In this tutorial we’ll look at creating uvs using the ‘Unwrap UVW’ modifier in 3D Studio Max, and discuss what uv mapping is, why it’s necessary and some ways to approach it.

      Visit Article

    • Aetuts+ — After Effects Tutorials
    • Create The Amazing Spider-Man Title Sequence Entirely In After Effects Create The Amazing Spider-Man Title Sequence Entirely In After Effects

      Nancy will show us how to create the title sequence for the Amazing Spider-Man entirely in After Effects using ShapeShifter AE. She shows us how to combine Shape Layers + Layer Masks to model and animate Spideys symbol. Download the free project file and follow along. You’ll be amazed at how easy it is to create!

      Visit Article

    • 3D Transforming Text With ShapeShifter AE D Transforming Text With ShapeShifter AE

      In this tutorial, we will be taking a look at how to build this 3D transforming text animation using Mettle’s ShapeShifter AE plug-in. We will also be enhancing some of the elements using 3rd party plug-ins such as Trapcode Shine (CC Light Burst alternative), Frischluft’s Out of Focus (Lens Blur alternative), and RE:Vision RSMB (CC Force Motion Blur alternative).

      Visit Article

    • Create An Awesome Array Of Shattering Strings Create An Awesome Array Of Shattering Strings

      We’ll be starting in Cinema 4d to create text fragments and use XPresso to export the Mograph positional data to After Effects. From there, we’ll jump over into After Effects and use expressions to connect 3d nulls to 2d data points… We’ll also be using a macro in Microsoft Word to edit multiple lines of expressions. It doesn’t matter if you’re a Cinema 4d user or strictly an After Effects user, today’s tutorial should be something helpful for everyone!

      Visit Article

    • Audiotuts+ — Audio & Production Tutorials
    • The 15 Minute Mix The 15 Minute Mix

      Consider this your challenge for today. Take a song that you just recorded, or have been working on and mix it in 15 minutes. Shut off everything, pull the faders up and follow the following tutorial. Use a stopwatch to keep track of time and when you should be switching tasks.

      If you don’t have any sessions to try, you can use any of these 50 different multi-tracks.

      Visit Article

    • 35 Audio Tutorial Sites That Will Keep You Learning Audio Tutorial Sites That Will Keep You Learning

      The reason you’re here on our site is because you’re interested in audio tutorials. I think we do a great job: we have a huge number of excellent tuts – both free and premium. But we know we haven’t cornered the market. There are an amazing number of audio tut sites out there, and the number seems to grow every year. Here are 35 of the best.

      Visit Article

    • Creating Skrillex Style Tech Basslines in NI Massive Quick Tip: Creating Skrillex Style Tech Basslines in NI Massive

      This series of quick tips will outline how you can use the ever powerful NI Massive synth to create techy basslines used by artists such as Skrillex. In this example I have used Cubase but the same principles will translate to pretty much any other DAW. Here is an example of the kind of sound you can expect to end up with at the end of this series:

      Visit Article

    • Activetuts+ — Flash, Flex & ActionScript Tutorials
    • Construct 2, a Drag and Drop HTML5 Game Maker Review: Construct 2, a Drag and Drop HTML5 Game Maker

      Construct 2 is an HTML5 game making tool that doesn’t require any programming knowledge. You just drag and drop items around, add behaviors to them, and make them come alive with “events”.

      Visit Article

    • An Introduction to Binary, Hexadecimal, and More Number Systems: An Introduction to Binary, Hexadecimal, and More

      Ever see crazy binary numbers and wonder what they meant? Ever see numbers with letters mixed in and wonder what is going on? You’ll find out all of this and more in this article. Hexadecimal doesn’t have to be scary.

      Visit Article

    • Understanding Affine Transformations With Matrix Mathematics Understanding Affine Transformations With Matrix Mathematics

      Inspired by Prof. Wildberger in his lecture series on linear algebra, I intend to implement his mathematical ideas with Flash. We shall not delve into the mathematical manipulation of matrices through linear algebra: just through vectors. This understanding, although diluting the elegance of linear algebra, is enough to launch us into some interesting possibilities of 2×2 matrix manipulation. In particular, we’ll use it to apply various shearing, skewing, flipping, and scaling effects to images at runtime.

      Visit Article

    • Wptuts+ — WordPress Tutorials
    • Creating a Filterable Portfolio with WordPress and jQuery Creating a Filterable Portfolio with WordPress and jQuery

      Learn in this tutorial how to make a filterable Portfolio with jQuery integrated with WordPress, remember that this portfolio kind can make a big difference on your themes!

      Visit Article

    • How to Include JavaScript and CSS in Your WordPress Themes and Plugins How to Include JavaScript and CSS in Your WordPress Themes and Plugins

      Knowing the proper way to include JavaScript and CSS files in your WordPress themes and plugins is very important for designers and developers. If you don’t adhere to best practices, you run the risk of conflicting with other themes and plugins, and potentially creating problems that could have been easily avoided. This article is intended as a reference for playing nicely with others.

      Visit Article

    • How to Create a Simple Post Rating System With WordPress and jQuery How to Create a Simple Post Rating System With WordPress and jQuery

      There already are many post rating system plugins out there. Surprisingly, no one fits my needs, they either are too complicated or with too many built-in options. So, in this tutorial, you’ll learn how to build your own simple post rating functionality, directly within your theme files. There’s no need for plugin!

      Visit Article

    • Mobiletuts+ — Mobile Development Tutorials
    • Getting Started With RenderScript on Android Getting Started With RenderScript on Android

      RenderScript is a scripting language on Android that allows you to write high performance graphic rendering and raw computational code. Learn more about RenderScript and write your first graphics app that leverages RenderScript in this tutorial.

      Visit Article

    • Twitter & Maps PhoneGap From Scratch: Twitter & Maps

      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

    • Supplementing iAd Placement with AdMob Supplementing iAd Placement with AdMob

      Click-based advertising within a mobile application is a great way to make some money off of your free or inexpensive applications. While there are many choices out there, many iOS developers tend to go with the iAds platform for a variety of reasons including simplicity, aesthetics, and a high CPM.

      Visit Article


  • Permalink for '30 Days to Learn C#: New Premium Course'

    30 Days to Learn C#: New Premium Course

    Posted: March 1st, 2012, 4:18pm MST by Jeremy McPeak

    We’re pleased to announce our latest Tuts+ Premium course: “30 Days to Learn C#.” My aim is to introduce you to the C# language (and a tiny bit of the .NET Framework), and give you a clear understanding of the fundamentals needed to start writing applications in C#.

    All I ask for is a few minutes of your time each day for a month.

    This is by no means a fully exhaustive look at the language, but I will get you familiar with the language and platform. I won’t lie; some of the material is easier to grasp if you have some programming background. But I do try to explain things from the standpoint of a complete beginner. So even if you haven’t programmed before, I hope you’ll find my explanations of programming concepts and fundamentals understandable.

    All I ask is for a few minutes of your time each day for a month. Most lessons are between ten and fifteen minutes. Naturally, some are shorter and some are longer, but I promise none go over 31 minutes!

    Ready to become a better programmer?

    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 'Build a Contacts Manager Using Backbone.js: Part 1'

    Build a Contacts Manager Using Backbone.js: Part 1

    Posted: March 1st, 2012, 11:20am MST by Dan Wellman

    In this tutorial, we’re going to look at building a fully functional contacts manager using Backbone.js, Underscore.js, and jQuery. We’ll take a look at the basic components that make Backbone tick as well as some of the convenience methods exposed by Underscore.

    What Exactly Are All These Libraries?

    Backbone is an architectural framework that allows us to easily create non-trivial JavaScript applications using MVC-style organisation and structure. Backbone isn’t considered true MVC – C is for Collection not Controller, but it still offers many of the same benefits and enables us to write powerful yet maintainable code.

    Underscore is a utility library that provides enhanced functionality to JavaScript, adding additional functions for working with arrays, collections, functions and objects.

    I’m sure jQuery needs no introduction here.

    Getting Started

    We’ll need a root project folder containing css, img and js subfolders, so go ahead and create these now. We’ll start out with the following HTML page:

    <!DOCTYPE html>
    
    <html lang="en">
        <head>
            <meta charset="UTF-8" />
            <title>Backbone.js Web App</title>
            <link rel="stylesheet" href="css/screen.css" />
        </head>
        <body>
            <div id="contacts"></div>
            <script src="js/jquery-1.7.1.min.js"></script>
            <script src="js/Underscore-min.js"></script>
            <script src="js/Backbone-min.js"></script>
            <script src="js/app.js"></script>
        </body>
    </html>

    Save this as index.html in the root project folder. Backbone’s only mandatory requirement is Underscore.js, but we’ll also want to make use of jQuery so we link to these two libraries before Backbone. Our application’s code will go into app.js and any styles will go into screen.css. On the page, we’ve got an empty container that will form the basis of our application.

    Next we can create the skeletal JavaScript file that we’ll gradually fill out over the course of this series. In a new file add the following code:

    (function ($) {
    
        var contacts = [
            { name: "Contact 1", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "anemail@me.com", type: "family" },
            { name: "Contact 2", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "anemail@me.com", type: "family" },
            { name: "Contact 3", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "anemail@me.com", type: "friend" },
            { name: "Contact 4", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "anemail@me.com", type: "colleague" },
            { name: "Contact 5", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "anemail@me.com", type: "family" },
            { name: "Contact 6", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "anemail@me.com", type: "colleague" },
            { name: "Contact 7", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "anemail@me.com", type: "friend" },
            { name: "Contact 8", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "anemail@me.com", type: "family" }
        ];
    
    } (jQuery));

    Save this in the js folder as app.js. We’ll put all of our code in an anonymous function which we invoke immediately, aliasing jQuery as the $ character. Also defined at this stage is an array of objects where each object represents a contact.

    We’ll use this local data store for this part of the tutorial as it allows us to get some script up and running without worrying to much about syncing with a server. We’ll save that for another day!

    Models

    A model represents the data of an application; in our application this will be an individual contact, which will have attributes such as a name, a contact number, etc. You could say that an individual model represents the atomic part of the application – the smallest possible unit of functionality. Add the following code directly after the data array:

    var Contact = Backbone.Model.extend({
        defaults: {
            photo: "/img/placeholder.png"
        }
    });

    To create a model in Backbone we just extend the Backbone.Model class using the extend() method. We can pass an object into the method which allows us to customize the model with our own functionality. One of the properties we can set within this object is called defaults. This property allows us to configure default values for any attribute that we would like our models to have.

    In this case, we set a placeholder image as the default value of the photo attribute for model instances. Any models that don’t have this attribute when defined will be given it.

    Models have other properties that we can use to add functionality; we could define an initialize() method, and this method would be invoked automatically by Backbone for us when each model is initialized. We won’t make use of this at present, but don’t worry, we’ll come back to models a little later on.

    Collections

    A collection is a class for managing groups of models. We’ll use a simple one in this example to store all of our contacts. Add the following code directly after the Contact model:

    var Directory = Backbone.Collection.extend({
        model: Contact
    });

    Like a model, a collection is a Backbone class that we extend to add custom functionality specific to our application. Collections also have an extend() method, and it accepts an object that allows us to set properties of the class and add behaviour. We use the model property to tell the collection what class each item in the collection should be built from, which in this case is an instance of our Contact model. Don’t worry that the classes we’ve defined so far seem extremely simple, we’ll be coming back and adding additional functionality in later parts of the tutorial.

    Views

    Views are responsible for displaying the data of the application in an HTML page. One of the benefits of separating out the parts of the application that process the data and the parts that display the data is that we can very easily make a change to one, without requiring extensive changes to the other. We’ll use a couple of views in our application, the first of which should be added directly after the Directory class:

    var ContactView = Backbone.View.extend({
        tagName: "article",
        className: "contact-container",
        template: $("#contactTemplate").html(),
    
        render: function () {
            var tmpl = _.template(this.template);
    
            this.$el.html(tmpl(this.model.toJSON()));
            return this;
        }
    });

    This view handles displaying an individual contact. Just like models and collections, views have an extend() method used to extend the Backbone.View class. We set several instance properties in our view; the tagName property is used to specify the container for the view and the className properties specifies a class name that is added to this container. We’ll use a simple template in our HTML file to render each contact, so the template property stores a cached reference to the template, which we select from the page using jQuery.

    Next we define a render() function; this function isn’t invoked automatically by Backbone and while we could call it from the automatically invoked initialize() method to make the view self-rendering, we don’t need to in this case.

    Within the render() method we store a reference to Underscore’s template() method and pass to it the stored template. When passed a single argument containing a template Underscore doesn’t invoke it immediately but will return a method that can be called in order to actually render the template.

    We then set the HTML content of the <article> element created by the view to the interpolated template using jQuery’s html() method for convenience. This is done by calling the templating function that Underscore returned previously and passing it the data to interpolate. The data is obtained from the model using Backbone’s toJSON() method on the model. Interpolating just means that the tokens within the template are replaced with actual data. Notice also that we use $el to set the HTML content; this is a cached jQuery object representing the current element so that we don’t have to keep creating new jQuery objects.

    At the end of the render() method, we return the this object, which points to the view instance that the render() method is called on. This is so that we can chain other Backbone methods to the view instance after calling its render() method.

    Micro Templating With Underscore

    Now would probably be an appropriate time to look at Underscore’s built-in micro-templating facitlities. Underscore provides the template() method as we saw to consume and interpolate templates. To the HTML page we should add the template that we will use; add the following code directly after the contacts container <div>:

    <script id="contactTemplate" type="text/template">
        <img src="<%= photo %>" alt="<%= name %>" />
        <h1><%= name %><span><%= type %></span></h1>
        <div><%= address %></div>
        <dl>
            <dt>Tel:</dt><dd><%= tel %></dd>
            <dt>Email:</dt><dd><a href="mailto:<%= email %>"><%= email %></a></dd>
        </dl>
    </script>

    We use a <script> element with an id attribute so that we can easily select it, and a custom type attribute so that the browser doesn’t try to execute it. Within the template we specify the HTML structure we would like to use, and use tokens to specify where the model data should be inserted. There are a couple of other features we can make use of with Underscore including interpolating HTML-escaped values, or executing arbitrary JavaScript, but we don’t need to make use of these for the purpose of this tutorial.

    A Master View

    To finish off this part of the tutorial we going to create one more view. Our current view represents each individual contact so is mapped to a model on a 1:1 basis. But this view isn’t self-rendering and we haven’t invoked it yet. What we need is a view that maps 1:1 to our collection, a master view that will render the right number of contact views to display each of our contacts. Directly after the ContactView, add the following class:

    var DirectoryView = Backbone.View.extend({
        el: $("#contacts"),
    
        initialize: function () {
            this.collection = new Directory(contacts);
            this.render();
        },
    
        render: function () {
            var that = this;
            _.each(this.collection.models, function (item) {
                that.renderContact(item);
            }, this);
        },
    
        renderContact: function (item) {
            var contactView = new ContactView({
                model: item
            });
            this.$el.append(contactView.render().el);
        }
    });

    This view will be attached to an element that already exists on the page, the empty container that is hard-coded into the <body>, so we select the element with jQuery and set it as the el property. When then define a simple initialize() function which creates an instance of our collection class and then calls its own render() method, making this view self-rendering.

    We then define the render() method for our master view. Within the function, we store a reference to the view so that we can access it within a callback function, and then use Underscore’s each() method to iterate over each model in our collection.

    This method accepts two arguments (in this form, although it can also be used with just one argument); the first is the collection of items to iterate over, the second is an anonymous function to be executed for each item. This callback function accepts the current item as an argument. All we do within this callback function is call the renderContact() method and pass to it the current item.

    Lastly we define the renderContact() method. In this method we create a new instance of our ContactView class (remember, the ContactView class represents an individual contact) and set its model property to the item passed into the method. We then append the element created by calling the view’s render() method to the $el property of the DirectoryView master view (the empty container we selected from the page). The $el property is a cached jQuery object that Backbone creates for us automatically.

    The master view is responsible for generating each individual model within our collection. All we need to do is initialise our master view, and because it is self-rendering, it will display all of the contacts specified in the array of dummy data:

    var directory = new DirectoryView();

    When we run this page in a browser now, we should see a visual representation of our data:

    Backbone creates an instance of a model for each item in our original array, which are stored in our collection and rendered as an instance of a view.

    This tutorial isn’t about CSS, so I haven’t covered the example CSS at all. It’s just basic CSS, if you’re curious take a look at the style sheet included in the demo archive.

    Summary

    In this part of the tutorial we’ve been introduced to some of the core components of Backbone.js; models, collections and views. Models are classes that we can create in order to store data about a particular thing and define behaviour for it. Collections are used to manage groups of models and views allow us to render our models using interpolated templates that display the data from our models.

    In the next part of the tutorial we’ll take a look at how we can filter our collection to display only a subset of our models. We’ll also take a look at another major component of Backbone – Routers.


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

    Recently in Web Development (February ’12 Edition)

    Posted: February 29th, 2012, 10:58am 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 The Developer Community Bickers About Prefixes

    Last month played host to glorious drama as developer and vendors started discussing about vendor prefixes. Specifically, Microsoft, Mozilla and Opera have stated that they’re going to adopt and style webkit properties in the future.

    There is a ton of information to absorb on either side of the argument so here are some links to catch up:

    Do You Exclusively Use webkit Prefixes?
    Now Vendor Prefixes Have Become a Problem
    Call For Action On Vendor Prefixes

    Nettuts image Apache Celebrates 17th Anniversary, Releases Version 2.4

    Apache, as one of the most popular servers, powers a vast portion of the internet. As of this month, Apache is officially 17 years old — old, specially by internet standards.

    The new version brings in lots of juicy improvements like asynchronous I/O support, reduced memory usage and dramatically improved performance.

    Read more

    Nettuts image Firefox 2012 Roadmap Published

    Firefox released their extremely detailed roadmap for the year 2012. In addition to performance improvements and feature additions, there are a bunch of things that I’m looking forward to in the roadmap.

    Faster startups, more developer tools and inbuilt PDF viewers? Sign me up!

    Read more

    Nettuts image Visual Studio Gets a VIM Emulation Layer

    Get the best of both worlds — Visual Studio’s robustness with VIM’s spiffy key binds. I’ve been trying this out for the past couple of weeks and it works great!

    Read more

    Nettuts image Chrome Launches on Android

    With the sheer number of mobile devices accessing the internet, it’s no longer feasible to really ignore that segment of users. Google has finally released a version of their popular Chrome browser for the Android operating system. The mobile versions syncs all your information seamlessly, if it helps…

    Read more

    Nettuts image Django 1.4 Beta 1 Released

    With all the noise around Rails and NodeJS, it’s easy to forget that there are other great frameworks still kicking around.

    Django is one such framework. And they just released a beta with a lot of new features including improved password hashing, form wizards, IPV6 support, CSRF improvements and much more. Make sure to check out this excellent framework!

    Read more

    Nettuts image Our Favorite Tools Get Updated

    A lot of our favorite web development tools got updated this month — HTML5 Boilerplate and Modernizr being the more visible ones. Unable to hold my excitement, I posted a PSA earlier this month. Make sure to check the link below to find out more.

    Read more

    Nettuts image Backbone Gets a Bunch of Features and Gets Closer to Version 1

    After an almost 9 month hiatus, Backbone introduced a lot of features over this month pushing the version number upto an exciting 0.9.1. I’ve linked you to the changelog below so you can take a look as to what’s changed.

    Read more

    Nettuts image Token Firefox and SublimeText 2 Updates

    Yes, I know. Another month, another Firefox version. We’re at version 10 now with fairly middling changes.

    On to more cheerful news, a new beta version of ST2 is out with a nice new icon, better indentation, better auto complete and more. Plus, you’ll now be granted +10 coolness on using ST2. True story.

    SublimeText 2 changelog
    Firefox 10 changelog

    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.

    Psd.js

    psd.js is a general purpose file parser for PSD files created in Photoshop. Given a PSD file, it can parse out information such as image size and color modes, image resources, layer info, image contents, etc.

    Github Repo

    SQLFiddle

    SQL Fiddle is a tool for database developers to test out their SQL queries. If you do not know SQL or basic database concepts, this site is not going to be very useful to you.

    SQLFiddle

    Touchy.js

    Touchy.js is a simple light-weight (1.65 kb compressed) JavaScript library for dealing with touch events in the browser. With no dependencies, just add the script to your page and start hacking.

    Github Repo

    Turn.js

    Turn.js is a plugin for jQuery that adds a beautiful transition similar to real pages in a book or magazine. It works in all modern browsers including touch devices.

    Github Repo

    Pot.js

    Pot.js is a JavaScript library that can be performed without causing stress to the UI and the CPU load by using easy loop iteration functions.

    Github Repo

    StratifiedJS

    StratifiedJS extends the JavaScript language with a small number of constructs for concurrent programming. It allows you to express asynchronous control flow in a straightforward sequential style

    Introduction to StratifiedJS

    Ingrid

    Ingrid is a fluid CSS layout system, whose main goal is to reduce the use of classes on individual units and is a bit less obtrusive and bit more fun to reflow for responsive layouts.

    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 XaoS.js

    A real-time fractal zoomer. Using it is simple: left-click to zoom in, right-click to zoom out.

    Read more

    Nettuts image “Programmer” is an Overgeneralization

    Erik McClure shares his thoughts on the sheer diversity when it comes to programmers. With software engineering exploding in sheer scope and complexity, this is makes for a great insightful read.

    Read more

    Nettuts image Differences Between JQuery .bind() vs .live() vs .delegate() vs .on()

    The all knowing Elijah Manor talks about the differences between each of these jQuery event binding methods. It’s a little dense if you’re newbie but if you’re really looking to grasp the internals of jQuery, this is a must read.

    Read more

    Nettuts image Prototypes and Inheritance in JavaScript

    This post is as old as the pyramids — in internet time but the information inside is still pretty spot on.

    Read more

    Nettuts image Patterns for Large-Scale JavaScript Application Architecture

    Addy Osmani presents his minibook on effective architecture for JavaScript apps when they reach a non-trivial size. It’s a bit long but definitely worth your time.

    Read more

    Nettuts image Backbone and Ember

    A super quick look at the differences between Backbone and Ember, two JavaScript frameworks vying for your front end MVC needs.

    Read more

    Nettuts image The Great Web Framework Shootout

    On this page you will find benchmark results comparing the performance of a few of the most popular OSS web frameworks in use today.

    Read more

    Nettuts image Learn Regex the Hard Way

    Zed Shaw teaches you how to regex away to development glory in this extensive guide.

    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 You’re a Bad PHP Programmer'

    Why You’re a Bad PHP Programmer

    Posted: February 28th, 2012, 12:00pm MST by Jason Lengstorf

    We all have our bad habits. In this article, we’ll go over a list of bad practices that are worth examining, reevaluating, and correcting immediately.

    February of 2011 Who the Hell Do You Think You Are?

    Every time I open a project that isn’t mine, it’s accompanied by a tinge of fear that I’m walking into some kind of Temple of Doom scenario, filled with trap doors, secret codes, and that one line of code that, upon alteration, brings down the entire app (and possibly sends a giant boulder hurtling toward me down a narrow hallway).

    When we’re wrong, and everything is fine apart from some minor differences in “how I would have done it,” we breathe a sigh of relief, roll up our sleeves, and dive into the project.

    But when we’re right… Well, that’s a whole different story.

    Our first thought upon seeing this unholy mess is usually along the lines of, “Who the hell does this guy think he is?” And rightfully so; what kind of programmer would willingly create such an unholy mess out of a project?

    The Answer Might Surprise You

    Awful code is the accumulation of multiple small shortcuts or concessions.

    Your first instinct might be to assume that the guy who built the project is a novice, or maybe he’s just an idiot. But that’s not always the case.

    My theory is that awful code is the accumulation of multiple small shortcuts or concessions — just as often as it’s the product of inexperience or stupidity. This makes the Temple of Doom app much scarier, because whoever built it might be just as smart, savvy, and well-read as you are. They just got lazy or put things together in a rush, and each of those little shortcuts added up into the winding nightmare that just fell in your lap.

    Even scarier, this could mean that at some point, someone inherited your code and immediately burst into tears.

    You’re Better Than That, Baby!

    It never hurts to reexamine your current practices and make sure you’re not taking any shortcuts that could be contributing to someone else’s lost sleep.

    Let’s take a few minutes and go over some common shortcuts, concessions, and other bad practices to ensure that our projects aren’t striking fear into the hearts of the villagers.

    You Don’t Plan Before You Start Coding

    Before you write a single line of code, you should have a solid plan of attack.

    Before you write a single line of code, you should have a solid plan of attack. This helps keep you on track and avoids wandering code that will confuse you later, not to mention some other poor soul.

    One approach that has saved me time — both in development and in commenting — is to write an outline in comments first:

    <?php
    
    // Include necessary data
    
    // Initialize the database connection
    
    // Include the common header markup
    
    // Determine the page variables from the POST data
    
    // Load the proper database info using the page vairiables
    
    // Loop through the loaded rows
    
        // Format the images for display
    
        // Create a permalink
    
        // Format the entry for display
    
        // Add the formatted entry to the entry array
    
    // Collapse the entry array into page-ready markup
    
    // Output the entries
    
    // Include the common footer markup

    As you can see, without writing a single line of code, I already know almost exactly what the file will look like. Best of all, you can plan out an entire application this way, and if you get to a point where one feature requires a functionality tweak to another, all you have to do is change the comment.

    It requires a shift in the way you approach development, but it will make your project organization skills go through the roof.

    NOTE: Some of these comments aren’t necessary; some of them will change; others will need to be added — that’s expected. This is kind of like writing an outline for a paper or writing a grocery list: it just keeps you on the right track when you go to finish the job.

    You Don’t Comment Anything

    Yet the single worst problem with most code that I encounter is that it’s poorly commented, or not commented at all.

    It makes me sad that I have to write this down. When something is as easy as commenting, it shouldn’t be something we have to remind each other to do.

    Yet the single worst problem with most code that I encounter is that it’s poorly commented, or not commented at all. This not only adds a good chunk of time to my initial familiarization with the project, but it pretty much guarantees that a fix made using an unconventional method out of necessity will confuse me. Then, if I end up doing any refactoring, I’ll inadvertently break the app because I haven’t encountered the extenuating circumstances that required the fix.

    This process can take anywhere from 10 minutes to 6 hours. (And you’ve done this to me, I know where you live. I’m coming for you.)

    So say this out loud:

    I, [state your name], hereby swear to make comments in any situation where the purpose of the code I’ve written isn’t immediately apparent.

    “Immediately apparent” refers to code that can’t be self-documenting (because it wouldn’t be reasonable to do so) and/or doesn’t complete a dead-simple task. Think about it this way: if you had to stop and think about your solution for more than a few seconds, it probably merits a quick line of explanation.

    To illustrate my point, I’m going to use an example from an article I wrote recently for beginners. 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);

    Five seconds at a time will add up in a big way.

    Now glancing at this code doesn’t require any additional brain power: you see the comment, see the code, and never have to question its intent.

    It might only save you five seconds of contemplation, but if you’ve got a complex app, five seconds at a time will add up in a big way.

    So stop making excuses. Write the damn comment.

    You Sacrifice Clarity for Brevity

    Good examples of sacrificing clarity for brevity include unclear variable names and dropping the curly braces.

    It’s a universal temptation to get something done in as few characters as possible, but that temptation is kind of like the temptation to only have one pair of underwear: sure, the laundry gets done quickly, but the problems that arise from your choice hugely outweigh the benefits.

    Good examples of sacrificing clarity for brevity include short, unclear variable names (such as $a — what does $a store?) and dropping the curly braces.

    Dropping curly braces from control structures is a particular pet peeve of mine. If you don’t like curly braces, switch to Python. In PHP, it’s just too easy to lose the meaning without them.

    For example, look at this set of nested if-else statements without curly braces:

    <?php
    
    $foo = 8;
    
    if( $foo<10 )
        if( $foo>5 )
            echo "Greater than 5!";
        else
            echo "Less than 5!";
    else
        echo "Greater than 10!";
        echo "<br />Another note.";

    At a glance, it looks like the last line should only fire if the value of $foo is greater than 10. But what’s actually happening is a case of improper indenting; the last echo statement will fire no matter what
    $foo stores.

    Can you figure it out if you look at it for a few seconds and know that if-else statements without curly braces only affect the immediate next line? Of course.

    Should you have to waste the energy figuring that out? Absolutely not.

    Adding curly braces adds a few lines, but it clarifies the statement immensely, even with the odd indentation:

    <?php
    
    $foo = 8;
    
    if( $foo<10 )
    {
        if( $foo>5 )
        {
            echo "Greater than 5!";
        }
        else
        {
            echo "Less than 5!";
        }
    }
    else
    {
        echo "Greater than 10!";
    }
    echo "<br />Another note.";

    Yes, it’s a good thing to keep your code concise, but not at the expense of clarity. It’s worth the extra lines to ensure no one has to bang their head against a keyboard trying to sift through your code.

    You Don’t Follow a Coding Standard

    Choose a standard and stick to it.

    Getting cute with your formatting might satisfy your artistic urges, but it does no good for anyone. Choose a standard (I recommend the PEAR coding standard) and stick to it. Everyone will thank you. (Including yourself, someday.)

    Trust me. I was that guy once — I wanted to have a “signature style” — and I wasted a lot of hours fixing my atrocious formatting later on. There’s a time to be different and a time to do it like everyone else.

    When it comes to programming, think of it like a spoken language. Grammar and punctuation exist for a reason: so we can clearly understand each other when we write things down. Think of coding standards like a geeky version of Strunk & White’s Elements of Style — following the guidelines means people understand what you’re trying to say, not that you’re a boring person.

    You Duplicate Code

    You’re doing it wrong.

    Try to look at every single piece of your app as something that will need to change at some point. If it does, will you have to update more than one file? If you answered yes, it’s time to reevaluate how you write code.

    If you’ve got code doing the same thing in more than one place in your app, you’re doing it wrong.

    You Don’t Follow a Development Pattern

    You should always have a structure when you code.

    You should always have a structure when you code. I don’t mean to imply that you need to be following the MVC pattern or something equally rigid, but I do mean that you should know how to classify components and where they should go.

    By following a logical development pattern, many decisions become automatic, and someone coming into your code doesn’t have to guess much when looking for a certain functionality in your codebase.

    It doesn’t take long, and it really will clarify your apps in a big way.

    You’re Too Clever for Your Own Good

    The simplest solution is usually the most appropriate

    There’s a fine line between a crafty solution and an overcomplicated one.

    It’s always tempting to try out some sweet new trick you’ve learned, but we have to resist the urge to force a complex solution into a space where a simple one is sufficient.

    On a basic level, the simplest solution is usually the most appropriate. You’re trying to get from point A to point B — taking a detour through point Awesome is fun, but really doesn’t add any benefits.

    Your super-sweet solution does, however, pose a problem in which someone else may not have seen that particular solution and will just get lost. It’s not because they’re not as smart as you, either; it’s likely because they didn’t see that particular article or weren’t trying to force a square concept into a round problem.

    Don’t dumb yourself down, but remember to avoid overcomplicating things “just ’cause.”

    You’re a Wang

    Avoid actively making your code hard to understand at all costs.

    When I was first getting into development, I worked with a guy that was a self-proclaimed “expert” programmer. Whenever I had a question about a concept, he never gave me a straight answer; in order to get the answer to my original question, I had to answer a couple preliminary questions to “prove you can handle the answer.”

    This guy was also really good at writing code that was cryptic, obfuscated, and just generally confusing.

    Files like his are the result of programmers who think that they need to make their code hard to read in order to “keep the idiots out.”

    The general philosophy behind this tends to be, “If you’re not smart enough to understand this code, you shouldn’t be in it in the first place.”

    This is a deeply misguided and anti-social approach to programming. It’s a very elitist way of looking at things, and it shows that the programmer has lost touch with his beginner roots, when he himself needed help.

    Avoid actively making your code hard to understand at all costs. It doesn’t make you any cooler or smarter, and it doesn’t bolster respect. It just makes you a wang.

    Dude, What Are You Talking About?

    If you stop learning, then the projects you work on are stuck in whatever time period you decided to settle.

    In addition to the shortcuts and general laziness above, another thing that might be holding you back is a lack of continued learning and forward progress.

    Technology isn’t changing because the community at large is bored and we decided to redecorate; most new technologies emerge to more efficiently and easily solve existing problems. Choosing to ignore progress is choosing to start the slow process of marginalizing your skillset.

    Here are a few things we can all stop doing to make sure that our skillsets are up-to-date, all without having to give up our weekends.

    You’re Trying to Do it All Yourself

    Find out which of these programmers have a similar approach and let them fill you in on the big news.

    You can’t keep up with the whole community. As anyone who’s ever tried to keep up with a subscription to 200+ tech blogs will tell you, it simply can’t be done within a reasonable timeframe.

    Fortunately, there are those within the community who dedicate their time to watching the progression of technology and reporting their findings. If you take the time to find out which of these programmers has a similar approach and style, you can let them fill you in on the big news.

    Watching 2-5 of these “early adopter” type bloggers can be more beneficial than subscribing to every tech blog you come across for several reasons:

    • If you trust their opinion, they’ll be screening technologies for you.
    • If a technology pops up on more than one of these blogs, you know you should at least take a few minutes to learn more about it because it’s obviously popular.
    • Often, these blogs will feature a quick intro tutorial, which can save you the headache of starting from zero with a new technology.

    Among the PHP bloggers I trust are David Walsh and Chris Shiflett.

    You’re Not Out of Your Comfort Zone

    I simply mean to suggest that you’ll feel more fulfilled as a programmer and see your talents progress more and more if you choose to always be looking to the next level of programming.

    If you’re not doing something that challenges you, something is wrong. Finding new challenges within projects is most of what makes programming rewarding (or at least it should be).

    Try asking yourself the following questions when you start looking at new projects:

    • Is there a new technology that interests me that applies here?
    • Have I learned of a better way to do this since the last time I took on a project like this?
    • Is there a best practice I need to enforce that I could make sure to follow throughout this project?

    Keep in mind: I’m not talking about doing anything grossly complex, here.

    It can be as simple as remembering to add Docblocks to your objects, or as complex as making your app compatible with XMLRPC so it’s easier for users to post updates.

    Just try not to settle in and convince yourself you’ve learned everything you’re going to learn. That’s when it’ll start getting ugly for you.

    You’re Not Sharing

    Always discuss your code with your fellow programmers.

    The best way to improve is to discuss your code with your fellow programmers. This can be done through multiple avenues: if you’re feeling particularly outgoing, write a tutorial or release an open-source project; if you don’t feel up to something of that scale, maybe you could hang out on a community forum and offer help to the newcomers.

    “How does helping the noobs help me progress?” you ask. Usually, if you post a solution that could be optimized, other experienced programmers are going to hop in and offer tweaks. So this approach is a double-whammy of awesomeness: you’re not only helping progress the community by offering your knowledge to beginners, but you’re sharpening your own skillset by hanging your chops out for everyone to see and help you develop.

    You Don’t Have Any Side Projects

    If you want to get into something new and cool that’s a bit too involved to put into a real project, the best way to learn is to start a side project that uses said technique.

    That way, you can progress at your own pace, in your free time, and never risk missing a deadline or “doing it wrong.”

    We’re All Guilty

    If we’re doing it right, we should always be improving. And logic tells us that if we’re better now, then we were worse before. And if we follow that line of reasoning back far enough, there was a point where we were terrible.

    I know that when I look back at some of the code I wrote in the past, I’m horrified.

    So… Stop it.

    We’ll never be perfect. But we can do everything in our power to make sure that we’re getting as close as possible.

    What are your pet peeves when dealing with other developers’ code? Let me know in the comments!


  • Permalink for 'Elevate Your PHP to the Cloud'

    Elevate Your PHP to the Cloud

    Posted: February 27th, 2012, 2:16pm MST by Philip Sturgeon

    This article will walk you through cloud hosting for your PHP application with Pagoda Box. It’ll detail how to handle PHP dependencies, get your MySQL databases up and running (and debug locally), and customise various aspects of PHP with ease.

    Introduction

    As a developer who has been playing around with PHP since the age of 11, it’s hard to remember many things that have absolutely changed the way I develop. In 2007, I picked up CodeIgniter, which made me rethink how I structure my code and use OOP to get things done. In 2010, I began working with Git and Git Flow for teamwork and branching, but, recently, the biggest thing to change my development workflow has been one “Platform as a Service,” called Pagoda Box.

    You might be a rockstar developer who knows how to set up a LAMP stack, but how much of your potential development time do you waste setting it up, optimizing it, securing things, locking it down, scaling resources and monitoring traffic.

    Every day, I spot a developer battling to defend his server from some group of hackers or script kiddies, getting port flooded, having trouble getting some random security patch working, struggling to migrate to larger more powerful servers, getting mad trying to set up Capistrano, the list goes on. Services like Pagoda Box can help you skip all of that; so let’s see how.

    Step 1 - Register With Pagoda Box

    The first step is to grab yourself an account. It’s free, so go ahead.

    Register Step 2 - Create Your Application

    Each application needs to have a unique name, as they are also used for preview URLs. You can call this application whatever you wish, as you will be hiding it behind a domain shortly, but call it something obvious and memorable.

    SSH Key form Step 3 - Set Up Git

    Git is an extremely useful version management system. Right now, it is massively popular thanks to sites like GitHub who allow for free social code hosting, but it is also great for deploying your code.

    If you are new to Git then try the crash course.

    If you haven’t already, set up Git. Their documentation will help you get started. Windows users will find it a little more difficult than OSX or Linux users, so if you have a Virtual Machine of Ubuntu lying around, now would be a great time to fire it up.

    Step 4 - Create Your SSH Key

    To push your code to Pagoda Box you need to authorize your computer to have push access to applications on your account. Create an SSH key and paste it here.

    SSH Key form Step 5 - Deploy Your Code

    First, set up a folder for your application and set the Git remotes. Remotes are essentially nicknames for a repository URL. By setting up this remote, we’re letting our local Git repo know how to push code to Pagoda Box.

    	$ mkdir my-awesome-app && cd my-awesome-app
    	$ git init
    	Initialized empty Git repository in /Users/phil/Sites/my-awesome-app/.git/
    	$ git remote add pagoda git@git.pagodabox.com:my-awesome-app.git
    

    Now with all of this account and environment setup done, we can start deploying code. For now, we’ll deploy a simple Hello World app:

    	$ echo '<?php echo "Hello World!";?>' > index.php
    

    This is a little command line trick to put some text into a file. You could alternatively create this file with your favorite text editor or IDE.

    	$ git add index.php
    	$ git commit -m "OH HAI"
    	[master (root-commit) 6aa23f4] OH HAI
    	 1 files changed, 1 insertions(+), 0 deletions(-)
    	 create mode 100644 index.php
    

    So far, we have made a new folder for our website, initialized Git, added a remote which tells Git where the Pagoda Box app lives, and added a new index.php file, which will simply say Hello World!. Next:

    	$ git push pagoda master
    	Counting objects: 3, done.
    	Writing objects: 100% (3/3), 244 bytes, done.
    	Total 3 (delta 0), reused 0 (delta 0)
    
    	:: Auto deploy enabled for 'master'
    	 +> to change, visit [https:] 	:: Deploying to 6aa23f4 on master
    	:: Parsing Boxfile
    	:: Executing deploy
    	 +> Init submodules
    	 +> Booting web1.1
    	  - [22-Feb-2012 20:38:41] NOTICE: fpm is running, pid 54
    	  - [22-Feb-2012 20:38:41] NOTICE: ready to handle connections
    	 +> Propagating network updates
    	:: Cleaning up
    
    	To git@git.pagodabox.com:my-awesome-app.git
    	 * [new branch]  master -> master
    

    This is where the magic happens. You will push to a Git remote like any other repository, but then you will see the output of Pagoda Box taking over and creating a deployment. This will fire up a new instance each time and switch over from the live instance to this new instance instantaneously, meaning immediate updates – unlike slow FTP-based file deployment systems. Also unlike some similar services, all of your temporary files (cache, logs, image uploads, etc) will be there after any resize or re-deployment. Awesome!

    Now if you refresh the Pagoda Box page, you will see a Dashboard with all sorts of options.

    Step 6 - Creating a Boxfile

    Pagoda Box has a special config file: Boxfile. This goes in the root of your application. An advanced example may look something like this:

    web1:
    
      ################################################
      ## GENERAL SETTINGS
      ################################################
      shared_writable_dirs: [/system/cms/cache, /system/cms/logs, /uploads, /addons]
    
      ################################################
      ## WEB SPECIFIC SETTINGS
      ################################################
      index_list: [index.php]
    
      ################################################
      ## PHP SPECIFIC SETTINGS
      ################################################
      php_version: 5.3.8
      php_extensions: [mysqli, curl, gd, mbstring]
      php_date_timezone: Europe/London
      php_max_execution_time: 30
      php_max_input_time: 60
      php_post_max_size: 25M
      php_file_uploads: On
      php_upload_max_filesize: 20M
      php_max_file_uploads: 20
    

    This example gives you the chance to create writable folders, set your index_list (which is index.php by default) and change all sorts of PHP settings that would normally be in a php.ini file.

    The most important line here is:

    	php_extensions: [mysqli, curl, gd, mbstring]
    

    Pagoda Box allows you to list your applications dependencies. The “mysqli” driver is “MySQL Improved” which you should start using, as “mysql” is going to be deprecated in PHP 5.4. “curl” and “gd” are fairly standard and “mbstring” helps you work with UTF-8 code.

    It’s good to know they are available – along with plenty of others – but for this tutorial we’ll only need the following:

    	php_extensions: [pdo, pdo_mysql]
    

    So let’s make our new Boxfile and save it:

    web1:
      php_extensions: [pdo, pdo_mysql]
    

    We’ll be using this later on.

    Step 7 - Create a Database

    At the time of this writing, Pagoda Box only supports MySQL databases, which is fine as that is what the majority of developers use.

    We can fire up as many small database instances as we like for free; we only start paying when they get bigger, so you won’t get surprised by a massive bill just for building a website. Just like the web instances, they can also be scaled to grow with your website.

    New Database

    To make a new one, click the + icon and give it a name. You’ll see a progress bar up top while it builds; then the page will refresh.

    Step 8 - Connecting From Your App

    Connecting via PHP is a cinch. You are given multiple $_SERVER variables, which contain credentials for each database you have. This means you can keep hard-coded passwords out of your application – which is very useful if you don’t want all of your developers to see live passwords, or if you have your complete website on GitHub, like some people are beginning to do.

    $db = new PDO(sprintf('mysql:host=%s;dbname=%s;port=%s', $_SERVER['DB1_HOST'], $_SERVER['DB1_NAME'], $_SERVER['DB1_PORT']), $_SERVER['DB1_USER'], $_SERVER['DB1_PASS']);

    This is a basic example of the variables in use – connecting to your MySQL database via the PDO extension. If you’re using a framework, such as CodeIgniter, you can shove those variables into your database.php config files.

    Step 9 - Connecting Remotely

    Some web servers – especially those run-of-the-mill cPanel set-ups – have phpMyAdmin installed and can be configured to allow remote access to the MySQL databases.

    Instead of this approach, Pagoda Box uses Ruby Gem for – amongst other things – creating a temporary secure SSH tunnel. This means your MySQL databases are locked down behind a firewall and are only accessible via this secure SSH connection.

    So, to install the gem run:

    	$ sudo gem install pagoda
    

    Then to create the tunnel, simply run:

    	$ pagoda tunnel db1
    

    The first time you run this (or any other pagoda gem command) you should be asked for a username and password. This is your Pagoda Box username and password, and is needed so that the gem can act on your behalf and is nothing to do with your database.

    	$ pagoda tunnel db1
    	it appears this is the first time you have used our client
    	  Username: someguy
    	  Password: 
    
    	Tunnel Established!  Accepting connections on :
    	-----------------------------------------------
    
    	HOST : 127.0.0.1 (or localhost)
    	PORT : 3307
    	USER : (found in pagodabox dashboard)
    	PASS : (found in pagodabox dashboard)
    
    	-----------------------------------------------
    	(note : ctrl-c To close this tunnel)
    

    Go to your dashboard and click on the database, then click “Show Credentials” to see a info window like this:

    Database Credentials

    Use these credentials to connect. Don’t forget to specify which port; it is listed in the output from the gem above – not the green box. Remember, you are connecting to the local tunnel, not directly to the database.

    Step 10 - Making a Blog

    What sort of tutorial would this be if it didn’t involve making a blog in 20 minutes?

    For all development you should really be building things locally using MAMP, XAMPP, WAMP, etc., then deploying code and database changes using some sort of “Migrations” or schema change tracking stuff, but we’ll do this the old fashioned way.

    First connect to your database remotely via the tunnel, then run this query to build a new table:

    CREATE TABLE posts (
      'id' int(11) NOT NULL AUTO_INCREMENT,
      'title' varchar(255) NOT NULL,
      'slug' varchar(255) NOT NULL,
      'summary' text NOT NULL,
      'body' text NOT NULL,
      'created_at' int(11) NOT NULL,
      'updated_at' int(11) NOT NULL,
      PRIMARY KEY (id)
    ) ENGINE=InnoDB;
    
    INSERT INTO posts VALUES
    ('1', 'Women love guys who use FuelPHP', 'women-love-guys-who-use-fuelphp', 'It is a well proven fact that girls love developers, but things have never been so good for PHP developers. Everyone who starts using FuelPHP gets 150% more women within the first month. Fact.', 'It is a well proven fact that girls love developers, but things have never been so good for PHP developers. Everyone who starts using FuelPHP gets 150% more women within the first month. Fact.', '1322825332', '1322934052'),
    ('2', 'People who echo HTML from apps die younger', 'bad-practises', 'Scientists have proven that PHP developers who echo HTML directly our of PHP files die younger. Often it happens while the developer is in the office. While sat at their chairs they suffer multiple wounds, but apparently there are no witnesses, even though their colleagues were in the office \"refactoring bad code\" all day.', 'Important body text', '1322826479', '1322826479');
    

    With some test posts in place we can create this index.php:

    <?php 
    
    	$db = new PDO(sprintf('mysql:host=%s;dbname=%s;port=%s', $_SERVER['DB1_HOST'], $_SERVER['DB1_NAME'], $_SERVER['DB1_PORT']), $_SERVER['DB1_USER'], $_SERVER['DB1_PASS']);
    
    	$posts = array();
    	foreach ($db->query('SELECT * from posts') as $row)
    	{
    		echo "<h2>{$row['title']}</h2>";
    		echo "<p><em>Posted: ".date('l jS \of F Y', $row['created_at'])."</em><br />";  		echo $row['summary']."</p>";
    	}
    

    With that file saved, and our new Boxfile (from step 6) in place, we can deploy these new changes:

    	$ git add Boxfile index.php
    	$ git commit -m "Added Boxfile and deployed index.php changes"
    	$ git push pagoda master
    

    Go to “ [my-awesome-app.pagodabox.com”] and see the output:

    Database Credentials

    This is clearly not something that you’ll want running on your website, but it does enough. You can see that your database content is being output to the browser, and your demo URL is working. You can replace this with your CMS of choice, or build something custom.

    Step 11 - Use a Real Domain

    There is no point having your wonderful new blog on a pagodabox.com subdomain; so let’s park a domain on top of it.

    First, in the DNS/SSL tab of your dashboard, add in some entries for your domain:

    Database Credentials

    Now that your application is ready to accept a domain you should head over to whoever handles the DNS for your domain. Go to the DNS management area and set an A record for "myawesomedomain.com" to be "50.97.141.37" – which is the IP address listed on the interface for your app. These IP addresses are not unique per application, but will not always be the same. Set a CNAME record for "www.myawesomedomain.com" to alias "myawesomedomain.com" and you should be all set.

    Summary

    This may all seem rather different from how you work at the moment, but start to think about how much work you are saving yourself in the long run. Using PaaS is the same reason we use jQuery over native JavaScript, or PHP frameworks over writing native PHP. Why mess around with minor details when you can instead focus on building an awesome app?

    Other alternatives you might consider are PHPFog and Orchestr.io, which both offer similar services. Have fun, and thanks for reading!


  • Permalink for 'Eleven2 Reseller Hosting and Shared Hosting Giveaway + iPad Giveaway'

    Eleven2 Reseller Hosting and Shared Hosting Giveaway + iPad Giveaway

    Posted: February 27th, 2012, 9:30am MST by Grant Friedman

    Looking for a place to host your new website? If so, then we have a treat for you. The folks at Eleven2 are offering 1 year of free shared or reseller hosting to 10 lucky Nettuts+ readers. To enter, all you have to do it fill out the form below and tell us whether you would prefer shared or reseller hosting. Winners will also be entered into a drawing to win a free iPad.

    Update: The winners for this giveaway have been selected and contacted. Thanks so much to everyone who participated.

    But there is more, for those of you who can’t or don’t have time to wait until the winners are selected, Eleven2 is also offering our readers 35% off their first invoice if you sign up using the discount code NET35. In addition, Eleven2 will also enter those of you who choose to sign up using that discount code into a drawing to win a free iPad.

    If you would like to learn more about what Eleven2 has to offer, please visit their website.

    Submit Your Entry Up for Grabs

    10 Lucky Winners will receive 1 Year of Free Web Hosting, with servers located in the USA or Europe. Pick between.

    Giveaway Rules
    • Submit your entry using the form above. Select whether you would prefer shared or reseller hosting.
    • You may only enter once.
    • Make sure to enter a valid email address so that we can contact you.
    • Winners will be entered into a drawing to win a free iPad.
    • The discount code NET35 only applies to your first invoice. So if you choose to pay monthly, you’ll only receive a discount on your first month. If you choose to pay annually, the discount will be applied to your first year, etc. Those of you who sign up using this method will also be entered into the drawing to win a free iPad.
    • Only 1 iPad will be given away. To qualify for this prize you must be selected as a winner of the hosting giveaway or sign up to Eleven2 using the discount code NET35.
    • Entries will be accepted until Friday, March 2, 2012 at 11:59 PM, EST.
    About Eleven2

    Eleven2 is a web hosting provider comprised of talented designers, developers, musicians, film makers, business owners, writers, photographers, and much more. Team members are a lot like you, making it easier for us to understand and deliver exactly what it is that you need. With worldwide hosting locations, you’ll be proud to call us your hosting provider.

    Click here to see what Eleven2′s customers have to say.


  • Permalink for 'Essential Sublime Text 2 Plugins and Extensions'

    Essential Sublime Text 2 Plugins and Extensions

    Posted: February 25th, 2012, 1:49pm MST by Siddharth

    Sublime Text 2 is a relatively new code editor that I’ve been trying out for a while now. While it’s still in public beta, it already offers a great mix of features and performance that has convinced me to switch from my trusted Komodo.

    While I really do love the features available out of the box, as with most things in life, there is always room for more. With Sublime Text 2 being as extensible as it is, a big ecosystem has sprouted around it, catering to most of your web development needs, be they actually useful or catering to your whimsy. To that effect, today I’d like to share some of the plugins and extensions that I’ve found quite useful. While not all of them may appeal to you, I’m sure you’ll a find a gem or two that will absolutely ease your workflow!

    Zen Coding Nettuts+ -- Essential Sublime Text 2 Plugins and Extensions

    Zen Coding is an editor plugin for high-speed HTML coding and editing. The core of this plugin is a powerful abbreviation engine which allows you to expand expressions—similar to CSS selectors—into HTML code.

    jQuery Package for Sublime Text

    And where will all us be without jQuery? This is a Sublime Text bundle to help with jQuery functions.

    Sublime Prefixr Nettuts+ -- Essential Sublime Text 2 Plugins and Extensions

    A plugin that runs CSS through the Prefixr API, written by our very own Jeffrey Way, for Sublime Text 2.

    JS Format

    JsFormat is a javascipt formatting plugin for Sublime Text 2. It uses the commandline/python-module javascript formatter from JS Beautifier to format the selected text, or the entire file if there is no selection.

    SublimeLinter Nettuts+ -- Essential Sublime Text 2 Plugins and Extensions

    SublimeLinter is a plugin that supports “lint” programs (known as “linters”). SublimeLinter highlights lines of code the linter deems to contain (potential) errors. It also supports highlighting special annotations so that they can be quickly located.

    Placeholders

    I always find inserting placeholder, or filler, content to be a quite tedious affair. With this plugin, you can insert placeholder content and HTML in a cinch!

    Sublime Alignment Nettuts+ -- Essential Sublime Text 2 Plugins and Extensions

    I’m quite a stickler for properly formatted code. One thing to get right is lining up all those darn variable assignment so they look all organized and neat. With this plugin, all it takes is the press of key. A simple key-binding allows you align multi-line and multiple selections.

    Clipboard History

    Tired of having to swap out your clipboard’s contents during a marathon hackathon? Keep a history of your clipboard items with this plugin and paste away as needed.

    SublimeREPL Nettuts+ -- Essential Sublime Text 2 Plugins and Extensions

    SublimeREPL lets you run your favorite interpreter inside a Sublime buffer. Languages supported include Python and Ruby.

    DetectSyntax

    DetectSyntax is a plugin for Sublime Text 2 that allows you to detect the syntax of files that might not otherwise be detected properly. This is specially helpful when you run into custom file formats — files used in templating is an excellent example.

    Nettuts Fetch Nettuts+ -- Essential Sublime Text 2 Plugins and Extensions

    This plugin automatically pulls in the latest copy of a file, simply by typing a keyboard shortcut. It’ll perform a curl request to your specified URL and allow you to rest assured that, for all new projects, you’re using the latest copy of a particular asset.

    JsMinifier

    It’s a good practice to always minify your files during deploying to a production server. And this plugin will swiftly automate the process by minifying your JavaScript using the Google Closure compiler.

    Sublime CodeIntel Nettuts+ -- Essential Sublime Text 2 Plugins and Extensions

    SublimeCodeIntel is a code intelligence plugin ported from Open Komodo Editor to Sublime Text 2. It shows autocomplete information with the available modules in real time as well as display information about the current function in the status bar. Nifty!

    Tag

    This is a great plugin when you’re working with a lot of markup. Tag is a collection of packages about, predictably, tags, mixed together in an effort to provide a single package with utilities to work with tags. Close a tag on a slash and tag indenting? Sign me up!

    Bracket Highlighter Nettuts+ -- Essential Sublime Text 2 Plugins and Extensions

    This plugin collection includes plugins to fold your code according to brackts, cycle through selecting tags and many more.

    Case Conversion

    Have a messy co-worker who completely ignores naming conventions? This plugin should save you a good chunk of time. Case conversions converts the current word between three of the most commonly used conventions.

    Stackoverflow Search Nettuts+ -- Essential Sublime Text 2 Plugins and Extensions

    StackOverflow is an absolute life saver — I can’t count the sheer number of times it has saved my skin. This plugin lets you do a search on SO directly from your editor.

    Sublime Guard

    Remember Jeffrey using a gem called Guard in his super useful Rails tutorial? Well, this plugin provides a seamless interface for controlling Guard and viewing Guard output within Sublime Text 2.

    Git Nettuts+ -- Essential Sublime Text 2 Plugins and Extensions

    A nifty little plugin that integrates Git and Sublime Text and implements most of the commands that you’d use in real life. Diff viewing inside ST2 is a great time saver!

    Sublime Change Quotes

    This is one for the OCD among us. This plugin converts single to double or double to single quotes whilst attempting to preserve correct escaping.

    Hex to HSL Nettuts+ -- Essential Sublime Text 2 Plugins and Extensions

    Tired of constantly having to manually convert your colors’ hexcodes to HSL? This plugin will automatically do it for you with the press of a button. Well, ok, three buttons. [Shift+Ctrl+U]

    That’s a Wrap!

    Well, that’s about all the plugins and extensions that I use on a daily basis. Considering the teeming ecosystem that Sublime Text 2 boasts, I’m sure I’m missing a ton here. Let us know in the comments and thank you so much for reading!


  • Permalink for 'The Top 15 Mobile Apps and Tools from CodeCanyon'

    The Top 15 Mobile Apps and Tools from CodeCanyon

    Posted: February 23rd, 2012, 5:58pm MST by Travis King

    With the proliferation and popularity of mobile sites, it’s no wonder that CodeCanyon’s Mobile Apps section has been growing in a big way. From iPhone to Android, developers have put together some amazing tools to help you with your mobile site development. Here’s a quick run down of some of the top selling mobile apps and tools from the marketplace. Check them out and get inspired for your next mobile site project!

    1. Create Your Own App (No Programming Skills Needed) Create Your Own App (No Programming Skills Needed) - CodeCanyon Item for Sale

    Create your own iPhone/iPod Touch application with no code at all! Let customer find you in the Apple AppStore and improve your communication potential.

    2. DOLPHIN – XML iPad/iPhone Slideshow&EBook Template

    Dolphin, XML Driven App Template, compatible with iPad and iPhone, with many exciting features, give you flexible for colorful Ebook/Slideshow creation.

    3. Appnx – Create an iPhone App using a web CMS Appnx - Create an iPhone App using a web CMS - CodeCanyon Item for Sale

    Appsnx is an engine that allows you to create fully native iPhone app using a web CMS and without a single line of code. You can create a simple app with text and images or make something more elaborated by using some of the awesome features that Appsnx includes.

    4. iRadio iPhone App iRadio iPhone App - CodeCanyon Item for Sale

    Just copy / past your streaming link and it works! Play directly when you open the application. Tested on Wifi and 3G.

    5. BizApp for Titanium BizApp for Titanium - CodeCanyon Item for Sale

    BizApp, an iOS template built on Appcelerator’s Titanium, is a perfect ‘brochure’ app.

    6. QR Code Scanner App Template ( Scanner / Reader ) QR Code Scanner App Template ( Scanner / Reader ) - CodeCanyon Item for Sale

    The QR Code Scanner App Template makes it easy and simple to integrate QR Code reading technologies into your app.

    7. BlogNews – iPhone blog app – WordPress editions

    BlogNews is a full native App for iPhone and has been built in response to the demand from the owners of WordPress Blog / Magazine who want to offer to their users a professional iPhone App.

    8. Mobile Store Locator Mobile Store Locator - CodeCanyon Item for Sale

    This mobile store locator is using a built-in API to fetch and display all the stores information. that makes it a very powerful and flexible mobile application. It enables users to views your stores list and details informations, view the stores on a Google Map, view a Google Street view, search by address, search the closest stores to their current location and more.

    9. One Website For All Devices One Website For All Devices - CodeCanyon Item for Sale

    One Website For All Devices allows you to build a single website, web application or native mobile application that works on multiple devices, screen sizes and orientations, all from the same code.

    10. HTML / PDF Viewer – iOS Xcode Project HTML / PDF Viewer - iOS Xcode Project - CodeCanyon Item for Sale

    HTML / PDF Viewer (also known as Document / Website Viewer) is a plug-and-play iOS application.

    11. Multi iRadio – Unlimited Radio – iAd Make Money Multi iRadio - Unlimited Radio - iAd Make Money  - CodeCanyon Item for Sale

    Unlimited streaming radio. Plus, make money with the iAd system that has already been instaled!

    12. AJAX Mobile Contact Form

    A contact form with very easy integration into your mobile website.

    13. PhotoGallery – iOS Xcode Project PhotoGallery - iOS Xcode Project - CodeCanyon Item for Sale

    A Photo Gallery is a plug-and-play iOS application that is perfect for photographers and agencies.

    14. Native Contact / Feedback Form – iOS Xcode Project Native Contact / Feedback Form - iOS Xcode Project - CodeCanyon Item for Sale

    Native Contact / Feedback Form is a plug-and-play iOS application.

    15. BandApp BandApp - CodeCanyon Item for Sale

    The App comes with a number of features such as Cover flow, Playable Tracks (Local sound files), Gigs with location maps as well as a twitter and RSS feed integration.


  • Permalink for 'Wrangle Async Tasks with jQuery Promises'

    Wrangle Async Tasks with jQuery Promises

    Posted: February 22nd, 2012, 2:05pm MST by Trevor Burnham

    Promises are an exciting jQuery feature that make it a breeze to manage async events. They allow you to write clearer, shorter callbacks and keep high-level application logic separate from low-level behaviors.

    Once you understand Promises, you’ll want to use them for everything from AJAX calls to UI flow. That’s a promise!

    Understanding Promises

    Once a Promise is resolved or rejected, it’ll remain in that state forever.

    A Promise is an object that represents a one-time event, typically the outcome of an async task like an AJAX call. At first, a Promise is in a pending state. Eventually, it’s either resolved (meaning the task is done) or rejected (if the task failed). Once a Promise is resolved or rejected, it’ll remain in that state forever, and its callbacks will never fire again.

    You can attach callbacks to the Promise, which will fire when the Promise is resolved or rejected. And you can add more callbacks whenever you want – even after the Promise has been resolved/rejected! (In that case, they’ll fire immediately.)

    Plus, you can combine Promises logically into new Promises. That makes it trivially easy to write code that says, “When all of these things have happened, do this other thing.”

    And that’s all you need to know about Promises in the abstract. There are several JavaScript implementations to choose from. The two most notable are Kris Kowal’s q, based on the CommonJS Promises/A spec, and jQuery Promises (added in jQuery 1.5). Because of jQuery’s ubiquity, we”ll use its implementation in this tutorial.

    Making Promises With $.Deferred

    Every jQuery Promise begins with a Deferred. A Deferred is just a Promise with methods that allow its owner to resolve or reject it. All other Promises are “read-only” copies of a Deferred; we’ll talk about those in the next section. To create a Deferred, use the $.Deferred() constructor:

    A Deferred is just a Promise with methods that allow its owner to resolve or reject it.

    var deferred = new $.Deferred();
    
    deferred.state();  // "pending"
    deferred.resolve();
    deferred.state();  // "resolved"
    deferred.reject(); // no effect, because the Promise was already resolved
    

    (Version note: state() was added in jQuery 1.7. In 1.5/1.6, use isRejected() and isResolved().)

    We can get a “pure” Promise by calling a Deferred’s promise() method. The result is identical to the Deferred, except that the resolve() and reject() methods are missing.

    var deferred = new $.Deferred();
    var promise = deferred.promise();
    
    promise.state();  // "pending"
    deferred.reject();
    promise.state();  // "rejected"
    

    The promise() method exists purely for encapsulation: If you return a Deferred from a function, it might be resolved or rejected by the caller. But if you only return the pure Promise corresponding to that Deferred, the caller can only read its state and attach callbacks. jQuery itself takes this approach, returning pure Promises from its AJAX methods:

    var gettingProducts = $.get("/products");
    
    gettingProducts.state();  // "pending"
    gettingProducts.resolve;  // undefined
    

    Using the -ing tense in the name of a Promise makes it clear that it represents a process.

    Modeling a UI Flow With Promises

    Once you have a Promise, you can attach as many callbacks as you like using the done(), fail(), and always() methods:

    promise.done(function() {
      console.log("This will run if this Promise is resolved.");
    });
    
    promise.fail(function() {
      console.log("This will run if this Promise is rejected.");
    });
    
    promise.always(function() {
      console.log("And this will run either way.");
    });
    

    Version Note: always() was referred to as complete() before jQuery 1.6.

    There’s also a shorthand for attaching all of these types of callbacks at once, then():

    promise.then(doneCallback, failCallback, alwaysCallback);
    

    Callbacks are guaranteed to run in the order they were attached in.

    One great use case for Promises is representing a series of potential actions by the user. Let’s take a basic AJAX form, for example. We want to ensure that the form can only be submitted once, and that the user receives some acknowledgement when they submit the form. Furthermore, we want to keep the code describing the application’s behavior separate from the code that touches the page’s markup. This will make unit testing much easier, and minimize the amount of code that needs to be changed if we modify our page layout.

    // Application logic
    var submittingFeedback = new $.Deferred();
    
    submittingFeedback.done(function(input) {
      $.post("/feedback", input);
    });
    
    // DOM interaction
    $("#feedback").submit(function() {
      submittingFeedback.resolve($("textarea", this).val());
    
      return false;  // prevent default form behavior
    });
    submittingFeedback.done(function() {
      $("#container").append("<p>Thank you for your feedback!</p>");
    });
    

    (We’re taking advantage of the fact that arguments passed to resolve()/reject() are forwarded verbatim to each callback.)

    Borrowing Promises From the Future

    pipe() returns a new Promise that will mimic any Promise returned from one of the pipe() callbacks.

    Our feedback form code looks good, but there’s room for improvement in the interaction. Rather than optimistically assuming that our POST call will succeed, we should first indicate that the form has been sent (with an AJAX spinner, say), then tell the user whether the submission succeeded or failed when the server responds.

    We can do this by attaching callbacks to the Promise returned by $.post. But therein lies a challenge: We need to manipulate the DOM from those callbacks, and we’ve vowed to keep our DOM-touching code out of our application logic code. How can we do that, when the POST Promise is created within an application logic callback?

    A solution is to “forward” the resolve/reject events from the POST Promise to a Promise that lives in the outer scope. But how do we do that without several lines of bland boilerplate (promise1.done(promise2.resolve);…)? Thankfully, jQuery provides a method for exactly this purpose: pipe().

    pipe() has the same interface as then() (done() callback, reject() callback, always() callback; each callback is optional), but with one crucial difference: While then() simply returns the Promise it’s attached to (for chaining), pipe() returns a new Promise that will mimic any Promise returned from one of the pipe() callbacks. In short, pipe() is a window into the future, allowing us to attach behaviors to a Promise that doesn’t even exist yet.

    Here’s our new and improved form code, with our POST Promise piped to a Promise called savingFeedback:

    // Application logic
    var submittingFeedback = new $.Deferred();
    var savingFeedback = submittingFeedback.pipe(function(input) {
      return $.post("/feedback", input);
    });
    
    // DOM interaction
    $("#feedback").submit(function() {
      submittingFeedback.resolve($("textarea", this).val());
    
      return false;  // prevent default form behavior
    });
    
    submittingFeedback.done(function() {
      $("#container").append("<div class='spinner'>");
    });
    
    savingFeedback.then(function() {
      $("#container").append("<p>Thank you for your feedback!</p>");
    }, function() {
      $("#container").append("<p>There was an error contacting the server.</p>");
    }, function() {
      $("#container").remove(".spinner");
    });
    
    Finding the Intersection of Promises

    Part of the genius of Promises is their binary nature. Because they have only two eventual states, they can be combined like booleans (albeit booleans whose values may not yet be known).

    The Promise equivalent of the logical intersection (AND) is given by $.when(). Given a list of Promises, when() returns a new Promise that obeys these rules:

    1. When all of the given Promises are resolved, the new Promise is resolved.
    2. When any of the given Promises is rejected, the new Promise is rejected.

    Any time you’re waiting for multiple unordered events to occur, you should consider using when().

    Simultaneous AJAX calls are an obvious use case:

    $("#container").append("<div class='spinner'>");
    $.when($.get("/encryptedData"), $.get("/encryptionKey")).then(function() {
      // both AJAX calls have succeeded
    }, function() {
      // one of the AJAX calls has failed
    }, function() {
      $("#container").remove(".spinner");
    });
    

    Another use case is allowing the user to request a resource that may or may not have already be available. For example, suppose we have a chat widget that we’re loading with YepNope (see Easy Script Loading with yepnope.js)

    var loadingChat = new $.Deferred();
    yepnope({
      load: "resources/chat.js",
      complete: loadingChat.resolve
    });
    
    var launchingChat = new $.Deferred();
    $("#launchChat").click(launchingChat.resolve);
    launchingChat.done(function() {
      $("#chatContainer").append("<div class='spinner'>");
    });
    
    $.when(loadingChat, launchingChat).done(function() {
      $("#chatContainer").remove(".spinner");
      // start chat
    });
    
    Conclusion

    Promises have proven themselves to be an indispensable tool in the ongoing fight against async spaghetti code. By providing a binary representation of individual tasks, they clarify application logic and cut down on state-tracking boilerplate.

    If you’d like to know more about Promises and other tools for preserving your sanity in an ever more asynchronous world, check out my upcoming eBook: Async JavaScript: Recipes for Event-Driven Code (due out in March).


  • Permalink for 'PDO vs. MySQLi: Which Should You Use?'

    PDO vs. MySQLi: Which Should You Use?

    Posted: February 21st, 2012, 10:41am MST by Dejan Marjanovic

    When accessing a database in PHP, we have two choices: MySQLi and PDO. So what should you know before choosing one? The differences, database support, stability, and performance concerns will be outlined in this article.

    Summary
    PDO MySQLi
    Database support 12 different drivers MySQL only
    API OOP OOP + procedural
    Connection Easy Easy
    Named parameters Yes No
    Object mapping Yes Yes
    Prepared statements
    (client side)
    Yes No
    Performance Fast Fast
    Stored procedures Yes Yes
    Connection

    It’s a cinch to connect to a database with both of these:

    // PDO
    $pdo = new PDO("mysql:host=localhost;dbname=database", 'username', 'password');
    
    // mysqli, procedural way
    $mysqli = mysqli_connect('localhost','username','password','database');
    
    // mysqli, object oriented way
    $mysqli = new mysqli('localhost','username','password','database');
    	

    Please note that these connection objects / resources will be considered to exist through the rest of this tutorial.

    API Support

    Both PDO and MySQLi offer an object-oriented API, but MySQLi also offers a procedural API – which makes it easier for newcomers to understand. If you are familiar with the native PHP MySQL driver, you will find migration to the procedural MySQLi interface much easier. On the other hand, once you master PDO, you can use it with any database you desire!

    Database Support

    The core advantage of PDO over MySQLi is in its database driver support. At the time of this writing, PDO supports 12 different drivers, opposed to MySQLi, which supports MySQL only.

    To print a list of all the drivers that PDO currently supports, use the following code:

    var_dump(PDO::getAvailableDrivers());

    What does this mean? Well, in situations when you have to switch your project to use another database, PDO makes the process transparent. So all you’ll have to do is change the connection string and a few queries – if they use any methods which aren’t supported by your new database. With MySQLi, you will need to rewrite every chunk of code – queries included.

    Named Parameters

    This is another important feature that PDO has; binding parameters is considerably easier than using the numeric binding:

    $params = array(':username' => 'test', ':email' => $mail, ':last_login' => time() - 3600);
    
    $pdo->prepare('
    	SELECT * FROM users
    	WHERE username = :username
    	AND email = :email
    	AND last_login > :last_login');
    
    $pdo->execute($params);

    …opposed to the MySQLi way:

    $query = $mysqli->prepare('
    	SELECT * FROM users
    	WHERE username = ?
    	AND email = ?
    	AND last_login > ?');
    
    $query->bind_param('sss', 'test', $mail, time() - 3600);
    $query->execute();

    The question mark parameter binding might seem shorter, but it isn’t nearly as flexible as named parameters, due to the fact that the developer must always keep track of the parameter order; it feels “hacky” in some circumstances.

    Unfortunately, MySQLi doesn’t support named parameters.

    Object Mapping

    Both PDO and MySQLi can map results to objects. This comes in handy if you don’t want to use a custom database abstraction layer, but still want ORM-like behavior. Let’s imagine that we have a User class with some properties, which match field names from a database.

    class User {
    	public $id;
    	public $first_name;
    	public $last_name;
    
    	public function info()
    	{
    		return '#'.$this->id.': '.$this->first_name.' '.$this->last_name;
    	}
    }

    Without object mapping, we would need to fill each field’s value (either manually or through the constructor) before we can use the info() method correctly.

    This allows us to predefine these properties before the object is even constructed! For isntance:

    $query = "SELECT id, first_name, last_name FROM users";
    
    // PDO
    $result = $pdo->query($query);
    $result->setFetchMode(PDO::FETCH_CLASS, 'User');
    
    while ($user = $result->fetch()) {
    	echo $user->info()."\n";
    }
    // MySQLI, procedural way
    if ($result = mysqli_query($mysqli, $query)) {
    	while ($user = mysqli_fetch_object($result, 'User')) {
    		echo $user->info()."\n";
    	}
    }
    // MySQLi, object oriented way
    if ($result = $mysqli->query($query)) {
    	while ($user = $result->fetch_object('User')) {
    		echo $user->info()."\n";
    	}
    }
    

    Security

    Both libraries provide SQL injection security, as long as the developer uses them the way they were intended (read: escaping / parameter binding with prepared statements).

    Lets say a hacker is trying to inject some malicious SQL through the ‘username’ HTTP query parameter (GET):

    $_GET['username'] = "'; DELETE FROM users; /*"

    If we fail to escape this, it will be included in the query “as is” – deleting all rows from the users table (both PDO and mysqli support multiple queries).

    // PDO, "manual" escaping
    $username = PDO::quote($_GET['username']);
    
    $pdo->query("SELECT * FROM users WHERE username = $username");
    
    // mysqli, "manual" escaping
    $username = mysqli_real_escape_string($_GET['username']);
    
    $mysqli->query("SELECT * FROM users WHERE username = '$username'");
    

    As you can see, PDO::quote() not only escapes the string, but it also quotes it. On the other side, mysqli_real_escape_string() will only escape the string; you will need to apply the quotes manually.

    // PDO, prepared statement
    $pdo->prepare('SELECT * FROM users WHERE username = :username');
    $pdo->execute(array(':username' => $_GET['username']));
    
    // mysqli, prepared statements
    $query = $mysqli->prepare('SELECT * FROM users WHERE username = ?');
    $query->bind_param('s', $_GET['username']);
    $query->execute();
    

    I recommend that you always use prepared statements with bound queries instead of PDO::quote() and mysqli_real_escape_string().

    Performance

    While both PDO and MySQLi are quite fast, MySQLi performs insignificantly faster in benchmarks – ~2.5% for non-prepared statements, and ~6.5% for prepared ones. Still, the native MySQL extension is even faster than both of these. So if you truly need to squeeze every last bit of performance, that is one thing you might consider.

    Summary

    Ultimately, PDO wins this battle with ease. With support for twelve different database drivers (eighteen different databases!) and named parameters, we can ignore the small performance loss, and get used to its API. From a security standpoint, both of them are safe as long as the developer uses them the way they are supposed to be used (read: prepared statements).

    So if you’re still working with MySQLi, maybe it’s time for a change!


  • Permalink for 'The Largest jQuery Class in the World'

    The Largest jQuery Class in the World

    Posted: February 20th, 2012, 3:15pm MST by Jeffrey Way

    A couple weeks ago, Tuts+ Premium launched a free new real-time course, called “30 Days to Learn jQuery.” After signing up, each member receives an email, linking to a new video lesson for an entire month.

    I’m pleased to announce that, after only two weeks into the course, we’ve amassed the largest jQuery class in the world, with 40,000 registered students!

    You Can Still Sign Up

    If you never got around to signing up for the course, you still can; there’s no deadline. Even after I publish the final “Lesson 30,” the course will continue to be freely available forever.

    The Largest jQuery Class in the World

    For those of you who have some experience with jQuery, the final two weeks of the course will focus on higher level concepts, such as templating, code organization, deferreds, and much more. It’s okay to jump ahead, if you already know the essentials!


  • Permalink for 'Nettuts+ Quiz #10: Basic CSS3 Techniques'

    Nettuts+ Quiz #10: Basic CSS3 Techniques

    Posted: February 18th, 2012, 7:39am 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. This month, we’re covering some basic concepts and techniques in CSS3.

    The prime focus today is on the easier, more accessible portions of CSS3. If you’re a hardcore CSS3 fan, don’t worry — transitions, animations, gradients and media queries are on the way!


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


  • Permalink for 'How to Upload Files with Ease Using DragonFly: New on Premium'

    How to Upload Files with Ease Using DragonFly: New on Premium

    Posted: February 16th, 2012, 3:39pm MST by Claudio Ortolina

    File uploads are generally a tricky area in web development. In this Tuts+ Premium tutorial, we will learn how to use Dragonfly, a powerful Ruby gem that makes it easy and efficient to add any kind of upload functionality to a Rails project.

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

    What We’re Going to Build

    Our sample application will display a list of users, and for each one of them, we will be able to upload an avatar and have it stored. Additionally, Dragonfly will allow us to:

    • Dynamically manipulate images without saving additional copies
    • Leverage HTTP caching to optimize our application load

    Additionally, in this lesson, we will follow a BDD [Behavior Driven Development] approach, using Cucumber and RSpec.

    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 'How to Customize Your Command Prompt'

    How to Customize Your Command Prompt

    Posted: February 16th, 2012, 7:47am MST by Andrew Burgess

    Lately, I’ve been getting this question a lot: “how did you get your terminal to look the way it does?” If you’ve noticed my terminal and are curious about how I set it up, this is the tutorial for you! Of course, what you learn here will be enough to get you started on creating your own custom command prompt, as well!

    Before we get started, I want to make something extremely clear. I’m certainly a command line enthusiast, but I’m not at all a command line pro. I feel at home in a terminal, but I’m a far cry from knowing everything. So here’s the deal: I’m going to show you how I’ve set up my terminal, but that doesn’t mean I’ll be able to explain every single line of code we’ll look at. There are some things here that are the way they are just because that’s what works … and I don’t always 100% know why.

    With that disclaimer out of the way, let’s see what we’re doing.

    Meeting the Finished Product

    Here’s what my command prompt looks like:

    If you’re not sure what you’re looking at there, let me explain:

    • In the turquoise, we have the name of the computer; in my case, that’s mothership. That’s followed by a colon.
    • Next, we have the working directory, in a yellow-orange.
    • If we’re in a git repository, we have some info on that next. The main thing here is the branch name (master or tilt_in_post_class in the screenshot). Also, if the working directory is clean, that text appears in green; otherwise, it appears in red.
    • Finally, we have a battery indicator. If the ten triangles are all green and filled in, things are powered up. As my battery empties, the triangles will empty and eventually turn red. Of course, if you aren’t on a laptop like I am, this won’t be as useful to you.
    Getting the Environment Ready

    Let’s now get a few preliminary pieces together, before actually writing some shell scripts.

    First, there’s the colour scheme. You might recognize it as Ethan Schoonover’s Solarized colour scheme. It’s pretty amazing, and I’ve used it on both the terminal and in Vim ever since I discovered it. If you want to use it in the Terminal, you’ll have to install the theme. The Terminal in Snow Leopard didn’t support xterm-256color, so you’ll have to follow some special directions on the Solarized GitHub page to get that working if you’re still on that OS.

    If you’ve moved on to Lion, you can just install the .terminal files you’ll find in the xterm-256color folder. Once you have those installed (just double-click them), you should be able to select the one you want in the Terminal preferences. Don’t forget to set it as the default scheme.

    The next thing to know is that I’m not using the default bash shell in my Terminal. Instead, I’ve switched to zsh, which is basically much bash-compatible, but has a few nice additions, like better tab completion. Here’s how to do it: open the Mac system preferences and go to “Users & Groups.” Unlock the pane by clicking the lock at the bottom and entering your password. Then, right-click on your user in the list and choose “Advanced Options.” In the “Login Shell” field, switch from /bin/bash to /bin/zsh. It’s that simple.

    Fonts

    Next step: get the right font. I’m using Inconsolata at 15pt. It’s a free monospace font that I love staring at all day long. (Besides using it in the Terminal, I use it in Vim and TextEdit.) You can set your default font from within the Terminal preferences, right where you choose the colour scheme.

    Another small thing is the size of your window: Open Terminal Preferences > Settings and click the Window tab; part-way down, you can choose the number of columns and rows you want; I use 130 columns by 30 rows.

    Battery

    Remember the battery level indicator? Well, that requires a little script from developer Steve Losh; simply copy that into a file and save it as a python file; since ~/bin is in my terminal PATH, I’ve saved the file to ~/bin/batcharge.py. As he notes, this script will only work on Mac OS X, so if you’re running zsh on another system, you’ll have to leave this part out.

    Zsh

    Last, but most certainly not least, there’s oh-my-zsh. According to the Github repo, this is just “A handful of functions, auto-complete helpers, and stuff that makes you shout ‘OH MY ZSHELL!’”

    Why use it? For me, I decided to give it a try at one point and I’ve left it installed. If you use the terminal a lot, poke around oh-my-zsh for a bit when you have some time. You might be surprised at what you’ll find. Installing oh-my-zsh is fairly simple: just follow the setup instructions in the README; they’re pretty straight-forward.

    Now we have all the necessary parts in place. We’re ready to actually start creating our custom terminal.

    Creating the Files

    When you installed oh-my-zsh, it was installed to ~/.oh-my-zsh. Pop that open. You’ll see two folders of note: themes and templates. Inside templates, you’ll find a file called zshrc.zsh-template This is a template for you ~/.zshrc file. If you’ve customized your terminal before, you’ll know that the .bashrc file is where your customizations are stored when you’re using a bash shell. The .zshrc is that same thing, except for the zsh shell. So open up that template file; you don’t have to know what exactly is going on; after all, there are a lot of comments in the file that might not make sense. One thing here is important to use. Notice the line that says this:

    ZSH_THEME="robbyrussell"

    That’s the name of the theme your terminal is using. Look in the themes folder: you’ll see a robbyrussel.zsh-theme file. What we’re going to do is create a theme of our own, so you can replace that string with the name of our new file. I’ve uncreatively called mine ‘doubleend” because it’s got into on both sides of the terminal.

    Any other customizations you want to make to your zsh environment can be made in this file. If you use the terminal a lot, check out oh-my-zsh‘s plugins (in the plugins folder): a ton of useful stuff in there.

    Don’t forget to copy to zshrc.zsh-template to your home directory and rename it to .zshrc before you make your changes. Now, in the themes folder, create a file with the theme name you set in your .zshrc file. Make sure you give it the .zsh-theme extension. We’re ready to build our custom theme.

    Building the Custom Theme

    The most important thing in your theme file is the PROMPT variable. It’s contents is your command prompt. To get the idea of this, just start with this in your theme file:

    PROMPT='myPrompt=>'

    Open a new Terminal window and you should see this:

    All right, let’s get to work. We’re going to have to write several functions, but we’ll start with the PROMPT variable. It might not be noticeable when looking at the terminal, but there are actually three lines to my prompt. The first is a blank line, just to give me some breathing room. The second has all the information, and the third has the arrow. That third line is where you actually type the command. So, here’s our start:

    PROMPT='
    
    $reset_color→ '

    Yes, you can do multiline strings that easily in shell scripting. But what’s up with $reset_color? That’s a variable that oh-my-zsh defines for us; it resets the colour of the output. This requires a short diversion to discuss how we colour different words in the prompt. You see, there’s a code—a series of characters—that switch the following text to a colour. Obviously, there’s a code for each available colour. Don’t worry, there are other variables for the other colours; you don’t have to learn the codes. By the time we get to the third line, though, we want to reset that to the default text colour; so, we use the $reset_color variable.

    If you’re curious about the arrow character, it’s the Unicode rightwards arrow (U+2192, &rarr;). That’s all.

    So, now our prompt is looking like this:

    Looking svelte. Let’s now add the computer name and working directory. This is all for that second line of our PROMPT variable.

    $fg[cyan]%m: $fg[yellow]$(get_pwd) 

    We start by setting the text colour to cyan; it appears that we’re getting that colour code from an associative array or hash; while I don’t use it, there’s a $bg hash which changes the background colour instead of the foreground (text) colour.

    After setting the colour, we have %m this outputs the name of the computer. After the colon and space, we switch the text colour to yellow. Next, we use the dollar sign and parens to add the output of the function get_pwd. This will output our current working directory, we a bit of a twist. If I’m in the home directory, I don’t want to see /Users/andrew, I want to see ~ instead. So, here’s that function:

    function get_pwd() {
    	echo "${PWD/$HOME/~}"
    }

    The function shell is pretty straightforward if you’ve written JavaScript before; identical syntax. I’m not sure where that search-and-replace syntax originated, but that looks pretty similar to the Vim search-and-replace syntax: If PWD includes the text $HOME (a system variable for your home directory), replace it with ~.

    Now, here’s what’s down:

    Good! Now comes the tricky part. You see, I want to right-align the git information and the battery indicator. Since there’s no way to actually right-align, we have to count the number of characters of text we want, subtract that from the width of the window, and add that spacing. It’s pretty hacky, and the code is pretty messy, but it’s all I’ve been able to find that actually works.

    Ready? We insert the spacing with a function that I call get_spacing. So add $(get_spacing) to the end of our second line, so it now looks like this:

    $fg[cyan]%m: $fg[yellow]$(get_pwd)$(put_spacing)

    Now, that function. Of course, here’s the shell:

    function put_spacing() {
    
    }

    There are four parts inside. Here’s the first.

    local git=$(git_prompt_info)
    if [ ${#git} != 0 ]; then
        ((git=${#git} - 10))
    else
        git=0
    fi

    We start by getting the output from the git_prompt_info function and storing it in a local variable, git. Next, if the length of that string is not 0, we reset git so that is now the length of the string minus 10. Otherwise, we reset git to 0. This doesn’t seem to make much sense, until you realize what we’re trying to do here. We want to find out how many character “slots” the git information takes up. The tricky part is that we’re reusing the variable git: first it holds the string, then it holds the number representing the number of characters our git info is long. If git is zero characters long, we set git to 0; if it isn’t (meaning we’re in a git repository), we set git to the number of characters in the string, minus 10. This is because the string character count includes the colour codes, which aren’t actually visible, so they don’t take up width. The double parens? Oh, they’re used for doing math.

    We do the very same thing for the battery output:

    local bat=$(battery_charge)
    if [ ${#bat} != 0 ]; then
        ((bat = ${#bat} - 18))
    else
        bat=0
    fi

    In the third part, we figure out how much spaces we’ll need:

    local termwidth
    (( termwidth = ${COLUMNS} - 3 - ${#HOST} - ${#$(get_pwd)} - ${bat} - ${git} ))

    A bit more math: we start with COLUMNS, which is the number of characters the Terminal is wide. We subtract all the appropriate values (the 3 is for two spaces and a colon), and we end up with the fact that we need termwidth number of spaces between the left and right parts of the prompt.

    Now, let’s create a string that’s termwidth number of spaces long:

    local spacing=""
    for i in {1..$termwidth}; do
        spacing="${spacing} "
    done
    echo $spacing

    A simple for-in loop allows us to create the string; then, we return it.

    You can’t really tell that the whitespace has been added, so I’ve added some dummy text so you can see that’s it’s been added.

    Next up, the Git info. We add $(git_prompt_info) to the end of prompt line 2; as you know, that’s a function call.

    $fg[cyan]%m: $fg[yellow]$(get_pwd)$(put_spacing)$(git_prompt_info)

    Notice that we don’t change the colour before loading the Git info: the function will take care of that, because it depends on the repository status.

    And here’s the function:

    function git_prompt_info() {
    	ref=$(git symbolic-ref HEAD 2> /dev/null) || return
    	echo "$(parse_git_dirty)$ZSH_THEME_GIT_PROMPT_PREFIX$(current_branch)$ZSH_THEME_GIT_PROMPT_SUFFIX"
    }

    The first line just checks to see if we’re in a Git repository. If we aren’t we return. If we are, the next line echos out the right info. Notice two things here: first, we’re using two variables: $ZSH_THEME_GIT_PROMPT_PREFIX and $ZSH_THEME_GIT_PROMPT_SUFFIX. I’ll show you how these are defined in a second. The other thing is two other functions that are called. These are provided by oh-my-zsh. The current_branch function just returns the current branch. The parse_git_dirty is more interesting, though. If the current branch is dirty (has uncommitted changes), the function will output the $ZSH_THEME_GIT_PROMPT_DIRTY; otherwise it will output $ZSH_THEME_GIT_PROMPT_CLEAN.

    I have these four variables defined like so:

    ZSH_THEME_GIT_PROMPT_PREFIX="[git:"
    ZSH_THEME_GIT_PROMPT_SUFFIX="]$reset_color"
    ZSH_THEME_GIT_PROMPT_DIRTY="$fg[red]+"
    ZSH_THEME_GIT_PROMPT_CLEAN="$fg[green]"

    Based on these variables, a repo on a clean master branch will output [git:master] in green; a dirty master branch will output +[git:master].

    And lastly, we call the battery_charge function:

    $fg[cyan]%m: $fg[yellow]$(get_pwd)$(put_spacing)$(git_prompt_info) $(battery_charge)

    Here’s the battery_charge function:

    function battery_charge() {
        if [ -e ~/bin/batcharge.py ]
        then
            echo `python ~/bin/batcharge.py`
        else
            echo '';
        fi
    }

    If the file exists, we run that file and echo the output. Notice that we use the backticks around the running of the file (those aren’t single quotes): this allows us to execute a string of code as if it was in the terminal. If the file doesn’t exist, we just echo an empty string.

    And with that, we’re done! Here’s what we end with:

    Conclusion

    Well, that’s what my terminal looks like. I’ve forked the oh-my-zsh project on GitHub and added this theme, so you can find it there. If you’re interested in seeing my other dotfiles, I’ve got them on GitHub too.

    However, I’m not done with my command line setup yet. While I haven’t made any changes in a while, I’m thinking of including the current user’s name (because I use this same theme on my server), and also some RVM info. Also, I’m not sure why I have the word git in there; I guess I originally had a setup that worked with multiple version control systems … Anyway, the point of all this is that this is something you’ll continually be tweaking. When I make changes, I’ll be sure to push them to GitHub, so you’ll be able to see them there.

    Let me leave you with several links that you’ll find useful in hacking around on the command line:

    Have fun!


  • Permalink for 'Attention Developers: NewRelic is your Secret Weapon'

    Attention Developers: NewRelic is your Secret Weapon

    Posted: February 14th, 2012, 5:00am MST by Ryan Allen

    While the title of this article may sound like a cliche, hatched in the bowels of PR hell, I’m serious when I say that NewRelic is your secret weapon.

    In this article, I’ll talk about the common aspects of web application performance, and then demonstrate how NewRelic makes it blissfully easy to manage.

    In the nearly six years that I’ve worked at Envato – previously developing and managing the series of marketplaces and currently managing development of the Tuts+ blog network – I’ve used NewRelic to keep costs down, improve and debug performance problems from the small to the large, and avert potential catastrophes.

    If you’re new to this topic, or don’t currently manage a website for someone in any capacity, don’t stress; this article will still be useful. You never know when this knowledge could save your bacon, and I’d wager it’s inevitable that it will – unless, of course, you decide to throw in the hypothetical developer towel and become an astronaut or rancher.

    NewRelic in 20 Seconds

    Before I launch into a reasonably long tirade on web application performance, it makes sense to quickly sum up what NewRelic is before you trundle off to Reddit or something similar.

    NewRelic is a managed service (SaaS) that you “plug in” to your web app, which collects and aggregates performance metrics of your live web application.

    The information it provides can help you find answers to questions like: Is my website slow? Who is it slow for? Where is it slow exactly? Do we need more, or bigger servers? What can we do to improve things?

    These questions and their answers are oftentimes crucial to your web application’s success or failure. If you’ve never collected performance metrics from your live web app, you’re literally running while blindfolded; at some point you’re going to hit a wall!

    Before I take you on a tour of NewRelic’s features, I have to define what web application performance is. Let’s get to it.

    What Exactly is Web Application Performance?

    Front-end performance is about “perceived” performance.

    I like to split web app performance into two conceptual parts: front-end performance and back-end performance. While the two areas do indeed have crossover and affect one another, it’s helpful to draw a distinction.

    Primarily, you can think of front-end performance as areas concerning perceived performance, such as how long a page takes to fully render to an end user. Variables that affect this type of performance include:

    • How large your HTML, CSS, JavaScript and images are
    • How many HTTP requests are sent to servers to fetch all of these assets
    • How they are organized in the page to affect perceived performance, whether or not a user’s browser has to re-download assets regardless if they’re the same or not.

    I have only seen web applications and websites “fall over” as a result of mismanagement of the back-end.

    Back-end performance involves some kind of programming language that runs your code (i.e. PHP, Ruby), and some kind of database server (i.e. MySQL). Generally, most web applications are assembling HTML documents to be sent to your user’s browser, and are made up of data fetched from one or more databases – or even one or more external service (such as the Twitter API). I also typically lump in server resources (such as CPU usage, memory usage, disk IO) into this category, as it’s the code running on your server (not in your user’s browser) that affects these resources.

    Why is this distinction so important? Because, in my experience, I have found that a confusion between the two leads to useless effort being applied when trying to improve performance issues. I have witnessed work on the front-end performance of ailing websites when the actual issue has been the backend. On the other hand, I have watched people focus on back-end optimization when the problem has been on the front-end. It’s essential that you understand and appreciate the difference.

    On their own, these two subjects can be rather deep and complicated, and it’s a topic for an entirely different series of posts. While I’m decidedly specialized in back-end performance, in all of my professional career, I have only seen web applications and websites “fall over” as a result of mismanagement of the back-end.

    Three and a Half Approaches to Managing Performance

    There are three ways in which people tend to manage the performance of their web applications:

    1. Write code, deploy it, and hope for the best.
    2. Write code, guess which areas will become bottlenecks, measure and optimize them up front, deploy and hope for the best.
    3. Write code, measure the live application with something like NewRelic, then fix and tune as appropriate.

    The first approach is 100% reactionary. If you follow this method, you will only know if your web app is failing or performing poorly when your customers tell you (if they ever tell you).

    The second approach is considerably more mature; the developers are preempting problems and attempting to resolve them upfront. While this is admirable, the possibility of spending vital resources optimizing the wrong area, and the lack of ongoing feedback will provide few facts about what is truly going on in the live environment.

    The third approach is the almost ideal situation. By monitoring a live web application, you’re able to review how various things are performing, based on what your customers are actually doing. You can write code and receive immediate feedback on how well (or not) it’s performing.

    The Ideal Approach

    The ideal approach is to follow the third and apply a healthy measure of the second.

    It doesn’t hurt to consider performance up front; it is infinitely more useful to have true metrics. The old programming adage, “premature optimization is the root of all evil” may apply here, though, in programming, as in life, axioms are rarely anything more than half-truths.

    Measurement & Management: A Balancing Act

    There is no such thing as one true method to managing your web application’s performance.

    No matter what anyone says (including me!), there is no such thing as one true method to managing your web application’s performance. Depending on your app and customers, there will be different approaches and techniques. Yet one thing remains constant: you have to measure.

    So, what do you measure? Again, there isn’t one true list, yet there’ll always be a common number of metrics worth measuring. For example:

    • The number of application requests over time.
    • The wall clock time requests take to complete.
    • The CPU usage of your servers over time.
    • The hard drive reads, writes and utilization over time (known as Disk IO).
    • The number of database queries, and the time they take to run.
    • Queries run on your database that take over two seconds to complete (slow queries).
    • Incoming and outgoing bandwidth over time.

    This list, while certainly not exhaustive, will offer significant insight into your web app’s behavior, especially if you’ve never monitored them previously.

    Once you have this kind of data, the management of your web application is where all the fun begins. You may find that, once removing a bottleneck in your database (perhaps a few slowly executed queries), you’ll expose another as more server resources are freed up. It truly is a balancing act.

    Ultimately, what successful management looks like is something like this: you may double the efficiency of that single server of yours, allowing you to delay purchasing a second. On a larger scale, you may cut your server farm down by a factor of 50%, and on a large enough scale, that can equate to serious money. On a lighter side, you may simply provide good quality of service to your customers with no sudden surprises.

    NewRelic: Your Secret Weapon

    Now that we’ve covered the “what” and “how” bits, let’s take a look at NewRelic. Once upon a time in software-land, you had to roll your own measurement into an app – if you measured at all (which can be as much work as writing your app itself). NewRelic allows you to simply plug in its agent to your Ruby, PHP, .NET or Python application, and begin collecting real data right away.

    Thoughtfully, their product is split up into three core regions:

    • End user monitoring (front-end, the browser)
    • Application monitoring (back-end, your code)
    • Server monitoring (back-end, the servers)

    Let’s have a look at each, in the order they were historically released.

    The very first feature NewRelic launched was application monitoring. It tracks and reports on ‘Requests per Minute’ (aka RPM), average response times of these requests, and keeps this data for you to analyze. This is particularly useful for discovering trends in traffic over time (e.g. does my site get slower as our page views increase?).

    Additionally, the “slow transaction traces” will provide you with a list of recent requests from real users that were disproportionately slow. Inspecting these allows you to drill down and determine why a request took such a long time, giving you the information you need to improve it.

    End user monitoring will provide you with insight into how your site is rendering in the users’ browsers. It breaks the total time into chunks, based on things like network time (how long assets took to download), DOM rendering (how long your browser spend figuring out your HTML), image loading (as served by your web server or a CDN).

    A neat feature of end user monitoring is that it shows you how well or poorly your application is performing for users in different countries. For example, perhaps 50% of your customers are based in the UK, while the other 50% are in the US. You might discover that front-end performance isn’t too great in the UK, due to the physical distance from your servers. Introducing a CDN or a server in the UK will improve their experience.

    The best part of using NewRelic and taking action based on its data is that, once you’ve made any number of changes, you can immediately review if the changes have been effective or not!

    The last piece of the puzzle, and the most recent monitoring NewRelic has introduced, is their server monitoring tools. I’ve always remarked that you must correlate your server’s resources with your web application response times to get a fuller picture of efficiency. You may have excellent response times, but you also may be needlessly sacrificing significant server resources to provide them.

    I have seen apps with excellent YSlow scores, for instance, but absolutely no headroom for more traffic – even on significant amounts of hardware!

    I hope by now you’re starting to see how valuable this kind of information is!

    Installing NewRelic

    You’ll need to at least be on a VPS and have root access for the PHP agent.

    One of my only criticisms of NewRelic is that it’s not easy to install for some types of users. If you are a Ruby on Rails programmer, you’ll find it fairly easy, as it’s a simple Rails plugin.

    If you’re a PHP developer and aren’t comfortable goofing around on the command line, you’re going to find it difficult to install, as it’s a PHP extension and requires a daemon to be installed running alongside your web server. However, some PHP cloud platforms, like PHPFog offer NewRelic integration out of the box.

    This is unfortunate in my mind, as it’s a hurdle for most people. I hope NewRelic are currently looking to partner with more commodity web hosting providers, so that their product is more accessible to a wider audience. There’s literally no tool like it on the market at present, and they should be making it easy for all PHP developers to use.

    If you’re using existing hosting, you’ll need to at least be on a VPS and have root access for the PHP agent. Being completely fair, to spin up a VPS from a provider like Linode, and installing Apache, PHP, MySQL and NewRelic is a short process, but it does requires some comfort and know-how in a shell.

    The best way to get started using PHP and NewRelic is to use a tool like Oracle VirtualBox, install Linux, set up Apache and PHP and then install the agent. Then you’ll be able to use NewRelic in your local development environment, at the very least.

    I personally haven’t had any experience with the Python agent, and I’ve heard third-hand that the .NET component is easy as pie to get up and running.

    How Envato Uses NewRelic

    Envato has been using NewRelic since 2008. We’ve used it in the following products with good (and sometimes interesting) results:

    The Marketplaces

    Initially, we discovered roughly three major slow spots in unexpected places in the marketplaces. We discovered what our highest trafficked requests were, and focused on optimizing them specifically. If 80% of our time was spent in one spot, making it twice as fast increased capacity and saved us from allocating more funds to hardware. We’ve spotted unusual traffic (such as spammers and hackers) allowing us to take precautionary measures sooner than later, thus improving the experience for our real customers. We use it daily to monitor the performance of all our new and existing code.

    The Tuts+ Blogs

    In 2009-2010, Envato’s blog network had serious stability problems due to a number of architectural problems. It was my job to step in and solve the issues. After performing an architectural analysis and a redesign of it, we plugged in the (then beta!) PHP monitor. We discovered many, many undesirable things!

    • 20% of requests were hits to feeds (which should have been cached or sent to FeedBurner)
    • 3 SQL queries were routinely taking more than 5 seconds to return results
    • Long-running WP-Cron tasks were tying up our web worker pool
    • 404 pages were taking more than 1 second to generate!

    Over the course of 2010-2011, we progressively sorted out the issues until they were, more or less, all solved. To this day, we still monitor the PHP blogs using NewRelic. And now, thankfully, the blog network is nice and stable.

    The Tuts+ Premium Redesign

    When we launched the Tuts+ Premium redesign, we used NewRelic to debug performance problems before the actual launch, on the actual servers they were to run on. This allayed any fears of disaster upon launch. We continue to monitor the site’s performance, using NewRelic.

    Today, any important application at Envato has a NewRelic agent plugged in. It honestly has saved us heaps of time and money, and allowed us to provide quality of service to our users and customers.

    Other Tools Envato Uses to Augment NewRelic

    It wouldn’t be fair to not mention the other tools we use to look after our applications. We currently use ScoutApp for finer-grained server monitoring (it supports user contributed ‘plugins’ so we can monitor specific services like HAProxy, Nginx, etc). We also use AirBrake which logs and aggregates our errors in our Ruby on Rails applications.

    Lastly, we have rolled some of our own specialized, custom tools that check things like cache hits, backend requests, revenue, sign ups, notifications when a significant deviation from the trends occur. For example, revenue halting or dropping might mean our payment integration is broken; a change in sign ups means we might have been targeted by spammers creating ghost accounts for later use.

    Wrapping Up

    If you work on any kind of web application that is business critical, or are tasked with fixing a not-quite-working app, NewRelic is going to be invaluable to you.

    If you have any questions, ask away in the comments and I’ll do my best to answer them. Particularly, if there’s interest in a screencast on how to set up a VPS or VM with NewRelic, I’m sure we could arrange one for you.

    Become a programmer superhero; use NewRelic!


  • Permalink for 'Web Dev PSA: Your Favorite Tools Have Been Updated'

    Web Dev PSA: Your Favorite Tools Have Been Updated

    Posted: February 13th, 2012, 2:13pm MST by Siddharth

    The last week was a bit of a whirl with many of our favorite tools receiving updates and tweaks.

    Usually, I’d save the announcement for our monthly “Recently in Web Development” piece, but considering how much, and how often, we use the tools below, it’s only fair that you be informed as quickly as possible.

    HTML Boilerplate

    First on our list is the venerable HTML5 boilerplate, or h5bp to its cushy fans. But what exactly is this ‘boilerplate’ thingy, you ask?

    HTML5 Boilerplate is the professional badass’s base HTML/CSS/JS template for a fast, robust and future-safe site.

    If you’re still lost, I suggest taking a look at this excellent guide by Paul Irish.

    If you’re like me and need to look at what has changed precisely, you can take a look at the complete changelog here.

    Well, the big news is that h5bp has been updated to version three. Here are some of the highlights in this version:

    • The build script has now been exported to its own project.
    • h5bp has been put on a diet. This version is noticeably smaller in size
    • The build system has been forked into a separate project.
    • In a touch of whimsy, the design of the 404 page has been improved
    Modernizr

    A full eight months after version 2.0 comes 2.5 of Modernizr – an extremely handy JavaScript library.

    It’s a common misconception that Modernizr miraculously upgrades all browsers to allow for HTML5 and CSS3 support. Unfortunately, this isn’t the case. However, instead, it detects support, which provides us with a lot of power!

    Version 2.5 ships with a massive set of changes, which you can view here, but here are the important ones.

    • More than 60 additional feature detects added.
    • html5shiv and yepnope added to core.
    • Respond.js removed from core
    • A polyfill for Function.prototype.bind is baked in by default.
    yepnope.js

    The work of Ralph Holzmann and yayQuery’s Alex Sexton, yepnope, a utility that aids you in smartly loading your JavaScript and CSS code, just got updated to version 1.5.2.

    yepnope is an asynchronous conditional resource loader that’s super-fast, and allows you to load only the scripts that your users need.

    This nifty resource loader, which is only 1.7KB minified and gzipped, is bundled with Modernizer and is great for loading polyfills, preloading or “priming” the user’s cache, or as a simple asynchronous resources loader / filter! You can read up more here.

    html5shiv

    Your spiffy new HTML5 elements, in all their glory, are impervious to CSS rules in IE. This is where html5shim comes to the rescue. Simply include it in your page’s <head> section and you will be able to style the new HTML5 elements perfectly.

    The new versions of html5shiv ship with some radical performance improvements, with some tests running 10 [!] times faster.

    html5shiv is built into Modernizr.

    Mobile Boilerplate

    As a mobile alternative to h5bp, the mobile boilerplate ships as an intelligent set of defaults for mobile sites and web apps. Version three brings it up to date with the recent versions of Modernizr and closely follows the changes made to its HTML5 counterpart.

    Go Check ‘em Out!

    ’nuff said! The staff at Nettuts+ use almost all of these on a daily basis and we think they’re worth your time as well.


  • Permalink for 'Do You Exclusively Use webkit Prefixes?'

    Do You Exclusively Use webkit Prefixes?

    Posted: February 10th, 2012, 9:55am MST by Jeffrey Way

    You’ve undoubtedly read about the vendor prefix web development drama of the week. If not, the W3C mailing lists have been on fire ever since it was discussed (and essentially announced) that Microsoft, Opera, and Firefox will begin to adopt and style webkit-prefixed properties. One of the reasons behind this decision is that we developers aren’t being responsible when coding our stylesheets; we’re applying too many webkit-specific properties, without considering other browsers.

    Upon hearing this, I was left thinking to myself: is this really true?

    Huh? What’s Going On?

    To catch up on the hot drama, gives the following articles a read:

    The basic gist is that non-webkit vendors are planning to recognize and style the -webkit prefix on a number of CSS3 properties. This is partially due to the fact, they say, that too many developers have been lazy, relying too much on Webkit, and not updating older projects (especially so for mobile designs). As these competing browsers see it, they have no choice; their hands are being forced.

    It’s one thing to toy around with non-standard, Webkit-specific properties for fun (such as -webkit-text-stroke); we’ve even posted similar articles on Nettuts+. However, it’s another thing entirely if developers are, for example, exclusively using Webkit’s prefix when applying CSS gradients or transitions.

    Prefixing Services

    An often-touted excuse for not properly prefixing all CSS3 properties is that it can be considerably difficult to keep track of which prefixes are necessary for any given property. This is certainly true, but has our community not provided a variety of solutions?

    Can I Use CanIUse

    To begin with the manual, look-up route, CanIUse.com is a fantastic reference when we need to determine if a particular browser supports a CSS3 property. If it is supported, but requires a prefix, CanIUse will tell you.

    It’s an essential bookmark for all web developers (and is not limited to only CSS).

    Compass Compass

    Compass is a framework for Sass that, among other things, will automatically handle the process of prefixing your CSS3 properties. For instance, to apply cross-browser, sanity-saving box-sizing to a website, with CSS, we’d write:

    * {
       -webkit-box-sizing: border-box;
       -moz-box-sizing: border-box;
       -ms-box-sizing: border-box;
       box-sizing: border-box;
    }
    

    However, when using Compass, we can simply include a mixin, like so:

    * {
      @include box-sizing(border-box);
    }
    

    This way, designers never need to concern themselves with whether or not a particular browser provides a prefixed version of a new property; Compass does it for you.

    Nettuts+ Prefixr Nettuts+ Prefixr

    At Nettuts+, we’ve, also, provided an easy way to “auto-prefix.” Either use the website or its API in your favorite code editor to automatically filter through your stylesheet, and update any CSS3 properties that are missing a prefixed version. This can even be integrated into your build script, so that you only ever code using the official syntax.

    The difference between Prefixr and Compass is that the former doesn’t require a preprocessor, if you prefer to code all CSS by hand. Simply feed Prefixr a stylesheet, and it’ll do the rest.

    Prefix-Free Prefix-Free

    Lea Verou’s Prefix-Free is a neat solution as well. It’s unique in that it’s a JavaScript-based solution that dynamically determines which browser is being used, and then assigns the necessary prefixes to the stylesheet. Simply import Prefix-free, use the official syntax for the new CSS3 properties, and it’ll take care of the rest.

    While some may view the fact that it depends on JavaScript to function as a disadvantage, a considerable bonus to this method is that your stylesheets become both smaller and more maintainable. For development purposes, it’s a great choice; however, for production, you might consider using a different tool, as there can be considerable performance consequences.

    CSS3 Please CSS3 Please

    CSS3Please is a nifty service that provides copy-and-paste, cross-browser CSS. Adjust the values according to your needs, and you instantly have a snippet that will correctly target all applicable browsers.

    Are You Not Using These?

    If you’re a preprocessor user who prefers to create his or her own CSS3 mixins, then fantastic; however, otherwise, are some of you not using these services? If so, why not? It’s understandable that Firefox and Microsoft may feel forced into supporting the webkit prefix for some properties, despite their better judgment. Particularly for older and smaller projects, we’re not always great about updating the stylesheets as needed. This is precisely why prefixed properties have hung around for so long, despite the fact that properties like border-radius have long since been supported, unprefixed. Webkit doesn’t want to “break” these websites.

    So what’s the deal? Are we not being responsible?

    Christian Heilmann has launched a project, called Prefix the Web; it encourages developers to update GitHub projects to include all necessary browser prefixes. Unfortunately, the initiative may be too late. What do you think?


  • Permalink for 'Using JavaScript’s Prototype with MVC'

    Using JavaScript’s Prototype with MVC

    Posted: February 9th, 2012, 1:01pm MST by Jeffrey Way

    In this article, we will review the process of using JavaScript, from an MVC-based perspective, to manipulate the DOM. More specifically, we’ll engineer our JavaScript objects, their properties and methods, and their instantiations parallel to the intended behavior of our Views (what the user sees).

    Consider Your Views As Objects, Not As Pages

    At any point in the development of a web page, we are using a language that naturally promotes either class-based development or object-based development. In strongly-typed languages like Java and C#, we are usually writing our views in classes – giving them state, scope, and context. When we are working with languages like PHP or newer view engines, like Razor for ASP.NET, our views may simply be markup (HTML/CSS) mixed with templating. However, this does not mean we have to change our perception on how the view behaves as its own stateful entity.

    Within Views, we are primarily working with HTML, which consists of nested elements; these elements have attributes which describe what their semantic purpose is or how they appear when rendered. These elements then have children or parent elements that inherit/provide cascading (through CSS) and block/inline behaviors. These elements can naturally be viewed from an OOP (Object-Oriented Programming) perspective. Consider, for example, the following markup:

    		div.container {
    			border: 1px solid #333;
    			padding: 5px;
    			color: red;
    		}
    		
    			<div class="container">
    				<h2>About Our Company</h2>
    			</div>
    		
    Result : Our header inherited a red border through CSS cascading

    As you can see above, the header inherited its font color property from its parent container though the CSS behavior of cascading. This behavior is quite similar to the concept of inheritance in OOP. We can also see that the header is a child of the container, inheriting certain properties, based on the behavior of the element. When we see our elements from this perspective, we have a better definition of what we intend to do with our view elements and can encapsulate styles and functionality better.

    Inside a view, we will have markup. However, this markup may have nested partial views like sidebars, a header, a footer, a right (or left) rail, and one or more content sections. All of these partial views should be viewed as their own entity, capable of having their own state, context, and scope.

    “When you conceive your views and partial views as objects, it makes writing your client-side code much easier.”

    Translating This Concept Into Your Styles and Scripts

    Many developers tend to write JavaScript from a procedural or functional point of view, and often neglect to consider the natural tendencies offered in view-based development approaches and parallel instantiation (creating a new instance of the view as we create a new instance of a JavaScript object corresponding to that view) when working in MVC Frameworks. It’s often the case that I run into JavaScript files that are just one method after another. Though this behavior works, and is common, it is not very efficient for code maintenance, debugging, or extension of current or future code when you are working extensively with views.

    To get away from this habit and begin writing better behavioral code, when you begin to lay out your View’s scripting and styles, follow these general rules:

    Golden Rules of View-based JavaScript Development
    • Every view that is rendered from an action on a controller should have its own JavaScript object.
    • Every Partial View that is loaded inside a View should have its own JavaScript object.
    • Name your objects the same as your views (or partial views). This will make more sense for you and everyone else that touches your code.
    • Use Pascal case for all objects (i.e. About, Sidebar, etc.). Your views should already, so why not do the same for your JavaScript objects?
    • All constants of these objects should be stored in the constructor. This means if your view has properties that will be used in multiple methods, these methods can all access these properties.
    • All methods that will be called on a view (or partial view) should be bound to the prototype of the object that corresponds to that view.
    • All event bindings for the view (or partial view) should be contained within their own event binding’s method, which is placed on the prototype.

    Consider the following diagram:

    Our MVC Layout viewed with styles and scripts

    I generally create view-specific scripts and styles and then grab what I need from the main stylesheets and script libraries I’ve created that would be used on many views. This also reduces the amount of code that is used.

    Creating View-based Objects

    In this article, we will be laying out the structure for the About Us page on an MVC-based site. To start, we will create the structure as shown above in the previous diagram. From there, we will create an About object, and begin adding methods to the prototype. First, consider the following visual layout:

    Sample About Us Page Layout

    This is a very logical and commonly used layout for a webpage. We can segment our page into seperate visual objects. For each of these views, we can create a logical object that will correspond to it. I generally omit the repetitive information in the filename or classname that is used by MVC to determine the URI from the route and instead stick with something that is easy to keep consistent.

    For page views, I generally call my JavaScript objects by the name of the view. Here is an example of my AboutView Object:

    		// View Filename: AboutView.cs (.NET MVC 1.0), About.cshtml (.NET MVC 3.0), or AboutView.php (PHP)
    
    		var About = function(pageTitle) {
    			this.pageTitle = pageTitle;
    			// binding events as soon as the object is instantiated
    			this.bindEvents();
    		};
    		

    In the above example, we created a JavaScript object in the function format, giving it the capacity to serve as an Object constructor for all methods called for the about view. By choosing this format, we can instantiate a new instance of this, just as we do with our view Server-Side (by saying new AboutView();). From here, we can assign properties and methods to this object. In order to assign methods to this object, we will need access to the object’s prototype.

    JavaScript’s Prototype is your Friend

    Developers are often thwarted by the elusiveness (and ambiguity) of JavaScript’s Object Prototype.

    Developers are often thwarted by the elusiveness (and ambiguity) of JavaScript’s Object Prototype. For many, it can be confusing to use and understand and adds another dimension to coding. As JavaScript becomes more event-driven with HTML5, AJAX, and web 2.0 concepts, JavaScript tends to lean naturally to procedural development that is easy to develop but hard to maintain, scale, and replicate.

    Think of the word Prototype as a misnomer for now. When I think Prototype, I think of a “rough draft” or a base for inheritance, but this isn’t exactly the case.

    ” In reality, the better perspective for Prototype would be the Object’s Pointer in memory.”

    When we create an object, we then instantiate a new instance of it. When we do that, we create a place in memory that the object can be referenced (remember, Objects in JavaScript are reference types, not primitive types; creating another variable equal to that object and then changing its values will actually change the original object in the pointer). When we create an object, instantiate a new instance of it, and then modify its “Pointer,” or Prototype, we add fields and methods to that object in memory directly (obviously we want to add all of these things before instantiation).

    Here’s an example of creating methods on the About object’s prototype:

    		var About = function(pageTitle) {
    			this.pageTitle = pageTitle;
    			// binding events as soon as the object is instantiated
    			this.bindEvents();
    		};
    
    		var About.prototype.bindEvents = function() {
    			 // Current context: 'this' is the About object
    			 // Place all your event bindings in one place and call them out
    			 // in their own methods as needed.
    			 $('ul.menu').on('click', 'li.search', $.proxy(this.toggleSearch, this));
    		};
    
    		var About.prototype.toggleSearch = function(e) {
    			  //Toggle the search feature on the page
    		};
    		

    As you can see above, we have contained the properties of the About object within the constructor, have created a single point of reference for binding events (in this case we are using jQuery to create the event bindings, but you can use any framework or JavaScript itself), and have placed the toggleSearch method on the prototype of the About object to contain that method to that object. We have also called the bindEvents() method in the object so that it is called on instantiation.

    Now, consider the following code for the Sidebar Partial View:

    		var pSidebar = function(pageTitle) {
    			this.pageTitle = pageTitle;
    
    			// call the bindEvents method on instantiation of the pSidebar object.
    			// this will bind the events to the object
    			this.bindEvents();
    		};
    
    		var pSidebar.prototype.bindEvents = function() {
    			 //current context: 'this' is the Sidebar object
    			 $('ul.menu').on('click', 'li.has-submenu', $.proxy(this.toggleSubMenu, this));
    			 $('input#search').on('click', $.proxy(this.openSearch, this));
    		};
    
    		var pSidebar.prototype.toggleSubMenu = function(e) {
    			// toggle the submenus
    			// current context:  'this' is the pSidebar obj
    		};
    		

    NOTE: I called the object pSidebar because this is a partial view, not a full view. This is my preference to distinguish between the two, but makes things clearer.

    The beauty of using this approach is – we can use the same method names we used in the About object and we will have no conflicts. This is because these methods are bound to the object’s prototype itself, not the global namespace. This simplifies our code and allows for a sort of “templating” for future scripting.

    Instantiate Only as Needed

    Once you have created your objects, calling them is simple. No longer do you need to depend on your framework to fire events when your document is loaded or ready. Now, you can simply instantiate your object and its events will be bound and executed as needed. So, let’s instantiate our About object:

    Inside your view where you would call your view specific scripts (dependent upon your templating language), simply call a new instance of your object and include the file as follows:

    		<script src="/path/to/scripts/views/about.js"></script>
    		<script>
    			new About("About Us");
    		</script>
    		

    As you can see, I passed in the page title for the view (which can be any argument for any need – even Model Data. This gives you excellent context over your model data and allows you to manipulate that data in JavaScript very easily.

    Just like your About Object, calling your partial views is just as easy. I would highly recommend calling new instances of your partial view JavaScript objects within the object’s constructor – this ensures that you are only calling these as needed and that they are collectively in one place.

    		var About = function(pageTitle) {
    			this.pageTitle = pageTitle;
    
    			//assigning a new instance of the Sidebar Partial View to be referenced later
    			this.sidebar = new pSidebar(pageTitle);
    
    			//NOTE:  If you don't need to reference a partial view after the fact,
    			//you can simply instantiate an instance of it without assigning it within the object's constructor, as so:
    			new pSidebar(pageTitle);
    
    			//doing the same for the Partial Footer View
    			this.footer = new pFooter();
    
    			// binding events as soon as the object is instantiated
    			this.bindEvents();
    		};
    		

    As you can see, by referencing the Sidebar object as a local property of the About object, we now bind that instance, which is a very natural behavior – this instance is now the About Page’s Sidebar.

    If you don’t need to reference a partial view after the fact, you can simply instantiate an instance of it without assigning it within the object’s constructor, as so:

    		var About = function(pageTitle) {
    			this.pageTitle = pageTitle;
    
    			new pSidebar(pageTitle);
    
    			// binding events as soon as the object is instantiated
    			this.bindEvents();
    		};
    		

    From here, all we need to do is add another script to our scripts called in our view:

    		<script src="/path/to/scripts/views/about.js"></script>
    		<script src="/path/to/scripts/partials/sidebar.js"></script>
    		<script>
    			new About("About Us");
    		</script>
    		
    Why This Technique is Beneficial

    Once this structure is in place, we can then tailor our JavaScript object to match our view and apply the needed methods to that object to maintain scope. By creating a view-parallel object and working off that object’s prototype, we see the following benefits:

    1. The nomenclature makes it easier to navigate through code
    2. We naturally namespace our objects, reducing the need for long method names and too much use of anonymous closure.
    3. Little to no conflict in other code because our methods are on the prototype of the object, not on the global level
    4. When instantiating our partial views within our View’s object constructor and assigning them to a local variable reference, we effectively create a locally bound copy of that Partial View’s object.
    5. We have a firm definition of context and are able to use the keyword ‘this’ without worry.
    6. Debugging becomes clear because all methods shown in the stack are bound in one place.
    Conclusion

    As the MVC Design Pattern continues to become more popular in the design world, the development of JavaScript Objects to accompany DOM Element manipulation will change to be more tailored towards view-specific and event-specific manipulation. By tailoring our JavaScript objects to instantiate in parallel with our Views, we can have a hand-in-hand stateful relationship between the two – one that is symantically in good taste, easy to step through, simple to maintain, and perfect for expansion as the view grows or changes, creating a permeable and expandable relationship between markup and scripting.

    By utilizing an Object’s Prototype, we are able to maintain a precise context on our View’s scripting object and expand that object with a repetitive development frame-of-mind. We can then replicate this format through our partial views, saving us time, brain power, and risk of bugs and unexpected behavior.


  • Permalink for 'Easy Script Loading with yepnope.js'

    Easy Script Loading with yepnope.js

    Posted: February 8th, 2012, 7:00am MST by Nikola Malich

    Officially released by Alex Sexton and Ralph Holzmann in late February of 2011, the yepnope.js resource loader features asynchronous, conditional loading and preloading of both JavaScript and CSS resources. This makes managing dependant, conditional code a breeze.

    March of 2011

    This nifty resource loader, which is only 1.6KB minified and gzipped, is now bundled with Modernizer and is great for loading polyfills, preloading or “priming” the users cache, or as a simple asynchronous resources loader / filter!

    For those of you unfamiliar with polyfills, they are essentially plugins, or shims, that enable the use of new or future technologies in older browsers, e.g. web sql databases, CSS3 transformations etc.

    Yepnope now also supports a number of prefixes and filters, which, when prepended to the resource url, add another layer of fine tuning or customization to its core functionality. As if this weren’t already great, yepnope also provides you with a mechanism to define your own prefixes and filters. Let’s have a look at what yepnope.js can do!

    Background – Asynchronous Script Loading YepNope

    Before we delve into yepnope and its features, it’s important to understand a bit about how asynchronous script loading works, why it’s useful and how it’s different from vanilla script loading.

    Asynchronous loaders remove the inherent blocking nature of a script.

    Typically, JavaScript files loaded with the <script> tag, block the download of resources as well as the rendering of elements within the web page. So, even though most modern browsers tend to support the parallel download of JavaScript files, image downloads and page rendering still have to wait for the scripts to finish loading. In turn, the amount of time a user has to wait for the page to display increases.

    This is where asynchronous loaders come in to play. Using one of several different load techniques, they remove the inherient blocking nature of a script, which allows for parallel downloading of both the JavaScripts and resources while not interfering with page rendering. In many cases, this can reduce – sometimes drastically – page load times.

    Most loaders preserve the order in which scripts are executed while providing a callback for when the script is loaded and ready.

    Asynchronous loading doesn’t come without its caveats, though. When scripts are loaded the traditional way, inline code is not parsed or executed until the external scripts are fully loaded, sequentially. This is not the case with asynchronous loading. In fact, inline scripts will usually parse / execute while the scripts are still being downloaded. In like manner, the browser is also downloading resources and rendering the page as the scripts are being loaded. Thus, we can arrive at situations where inline code, which is perhaps dependant on a script / library being loaded, is executed before its dependency is ready or before / after the DOM itself is ready. As such, most loaders preserve the order in which scripts are executed while providing a callback for when the script is loaded and ready. This allows us to run any dependant inline code as a callback, perhaps, within a DOM ready wrapper, where applicable.

    Also, when dealing with a small or well optimized page, the DOM can actually be ready or even loaded before the scripts themselves have finished loading! So, if the page in question isn’t progressively enhanced, in that it relies heavily on JavaScript for styling, there may be a FOUC or flash of unstyled content. Similarly, users may even experience a brief FUBC or flash of unbehaviored content. It’s important to keep these things in mind whenever you use a script / resource loader.

    Step 1 – The yepnope Test Object

    The yepnope test object has seven basic properties, any of which are optional. This object includes the actual test, resources which will be loaded as a result of the test, resources which will be loaded regardless of the test as well as callbacks. Here’s a look at the yepnope test object’s props:

    • test:

      A boolean representing the condition we want to test.

    • yep:

      A string or an array / object of strings representing the url’s of resources to load if the test is truthy.

    • nope:

      A string or an array / object of strings representing the url’s of resources to load if the test is falsey.

    • load:

      A string or an array / object of strings representing the url’s of resources to load regardless of the test result.

    • both:

      A string or an array / object of strings representing the url’s of resources to load regardless of the test result. This is, basically, syntactic sugar as its function is generally the same as the load function.

    • callback:

      A function which will be called for each resource as it is loaded sequentially.

    • complete:

      A function which will be called once when all of the resources have been loaded.

    Now, to get an idea of the syntax, let’s take a look at the simplest possible use of yepnope: loading a single resource.

    	yepnope('resources/someScript.js');
    			

    … or perhaps loading an array of resources.

    	yepnope([
    		'resources/someScript.js',
    		'resources/someStyleSheet.css'
    	]);
    			

    How about an object literal so that we can use named callbacks later?

    	yepnope({
    		'someScript'	 : 'resources/someScript.js',
    		'someStyleSheet' : 'resources/someStyleSheet.css'
    	});
    			

    Remember, these resources will be loaded asynchronously as the page is downloading and rendering.

    Step 2 – Conditions – Testing for the Features of the Future!

    So, we can load resources asynchronously! That’s great, but, what if some pages don’t require a certain resource? Or, what if a resource is only needed in a particular browser which doesn’t support a cutting edge new technology?

    No problem! This is where yepnope’s underlying purpose comes into focus. Using the test property, we can conditionally load resources based on need. For example, let’s assume that the Modernizer library is loaded.

    For those of you unfamiliar with Modernizer, it’s a nifty test suite used for detecting HTML5 and CSS3 feature support in browsers.

    Modernizer adds appropriate classnames to the pages html element, representing the features supported and not supported, e.g. “js flexbox no-canvas” etc. Additionally, you can access each of Modernizer tests, which return boolean values, individually, within your code.

    So, using Modernizer, let’s test for hashchange event support as well as session history support!

    Here’s a look at our test:
    	yepnope({
    		test : Modernizr.hashchange && Modernizr.history
    	});
    			

    This test will, of course, return true only if the browser supports both of these features.

    Step 3 – Loading Resources Conditionally

    With our test condition set, we’ll now define which resources to load based on the result of this test. In other words, if you only need to load a specific resource when the browser lacks a feature, or the test fails, you can simply define that resource in the nope clause. Conversely, you can load resources when the test passes, within the yep clause.

    So, assuming the browser doesn’t support one of these two features, we’ll load up Ben Alman’s jQuery hashchange plugin, which enables hashchange and history support in older browsers which don’t support either of these features.

    Let’s load up the hashchange plugin:
    	yepnope({
    		test : Modernizr.hashchange && Modernizr.history,
    		nope : 'resources/jquery.ba-hashchange.js'
    	});
    			

    In the above example, we won’t use the yep property as we’re only providing a shim should it be needed.

    To illustrate the yep clause, though, let’s test for CSS3 transformation support and then load a stylesheet for browsers which support transformations and a vanilla stylesheet for browsers that don’t. Additionally, we’ll load a jQuery plugin which mimics CSS3 transformations as well.

    Using both yep and nope:
    	yepnope({
    		test : Modernizr.csstransforms,
    		yep	 : 'resources/cssTransform.css'
    		nope : ['resources/noTransform.css', 'jQuery.pseudoTransforms.js']
    	});
    			

    Note that both of these examples will load all resources asynchronously as the rest of the page downloads and renders!

    Step 4 – Loading Resources Regardless of the Test Condition

    Yepnope also provides a way to load resources independently of the test results by way of the the load property. The load function will always load any resource it’s fed, regardless of the test result. Similarly, the both prop, which is, again, essentially just syntactic sugar, also loads resources regardless of the test result, or more accurately, on either result.

    Loading by default:
    	yepnope({
    		test : Modernizr.hashchange && Modernizr.history,
    		nope : 'resources/jquery.ba-hashchange.js',
    		load : 'resources/somethingWhichIsAlwaysLoaded.css',
    	});
    			

    Loading on both conditions, syntactic sugar :
    	yepnope({
    		test : Modernizr.hashchange && Modernizr.history,
    		nope : 'resources/jquery.ba-hashchange.js',
    		both : 'resources/somethingWhichIsAlwaysLoaded.css',
    	});
    			

    In both of the above examples, resources will be loaded, asynchronously, no matter what.

    Step 5 – Callbacks – Dependent Code After the Load

    As mentioned earlier, we can’t write in-line code in the usual manner if that code is dependant on one of the scripts being loaded. Thus, we’ll use yepnope’s callback function which fires once for each resource after it has finished loading. The callback function accepts three parameters which are assigned the following:

    • url

      This string represent the url of the resource which was loaded

    • result

      A boolean representing the status of the load.

    • key

      If using an array or object of resources, this will represent the index or the property name of the file which was loaded

    Let’s take a look at a simple callback with the hashchange plugin example from earlier. We’ll use jQuery’s bind method to bind a handler to the hashchange event of the window:

    A simple callback:
    	yepnope({
    		test : Modernizr.hashchange && Modernizr.history,
    		nope : 'resources/jquery.ba-hashchange.js',
    		callback : function(url, result, key){
    
    			$(function(){
    				$(window).bind('hashchange', function(){
    					console.info(location.hash);
    				});
    			});
    
    		},
    	});
    			

    Regardless of what state the DOM is in, this callback, which in this particular case is within a document ready wrapper, will fire as soon as the resource is loaded.

    Let’s say, however, that we are loading more than one script and that we need to fire off a callback for each script as it loads. Specifying the code we need to run in the above manner would create a redundancy as the callback is fired each time a resource is loaded. Yepnope, however, provides a great way to handle callbacks for each resource, independently of any other callbacks.

    By using an object literal to define the resources we are loading, we can reference each resource key, individually, within the callback.

    Let’s take a look at an example where we load jQuery as well as the jQuery hashchange plugin, which is dependant on jQuery being loaded first. This time, however, we’ll use object literals!

    	yepnope({
    		test : Modernizr.hashchange && Modernizr.history,
    		nope : {
    			'jquery' : 'resources/jquery-1.5.1.min.js',
    			'hashch' : 'resources/jquery.ba-hashchange.js'
    		},
    		callback : {
    			'jquery' : function(url, result, key){
    				console.info('I will fire only when the jquery script is loaded');
    			},
    			'hashch' : function(url, result, key){
    				console.info('I will fire only when the hashchange script is loaded');
    
    				// This code will be added to jQuerys DOM ready call stack
    				$(function(){
    					$(window).bind('hashchange', function(){
    						console.info(location.hash);
    					});
    				});
    			}
    		}
    	});
    			

    Using the above example as a reference, you can implement your own callbacks for each resource load in an orderly manner.

    Step 6 – Complete – When all is Said and Done!

    Lastly, we have the complete callback which is only called once, after all the resources have finished loading. So, for example, if you’re “bootstrapping” a web application and the code you need to run is dependent on all the files you’re loading, rather than specifying a callback for each resource, you would write your code within the complete callback so that it’s only fired once, after all its dependencies have loaded. Unlike the callback function, complete doesn’t take any parameters or have access to the url, result or key props.

    The complete callback:
    	yepnope({
    		test : Modernizr.hashchange && Modernizr.history,
    		nope : [
    			'resources/jquery-1.5.1.min.js',
    			'resources/jquery.ba-hashchange.js'
    		],
    		complete : function(){
    
    			console.info('I will fire only once when both jquery and the hashchange script are loaded');
    
    			// This code will be added to jQuerys DOM ready call stack
    			$(function(){
    				$(window).bind('hashchange', function(){
    					console.info(location.hash);
    				});
    			});		
    
    		}
    	});
    			

    So, essentially, the complete callback is useful for anything which needs to be done once all the resources are loaded.

    Step 7 – Yepnope Plugins, Prefixes and More!

    Yepnope also provides us with another nifty little feature: prefixes and filters! The default prefixes provided by yepnope, which are always prepended to the beginning of a resource url, are used for defining a file as CSS, preloading a resource or targeting Internet Explorer or one of its versions, respectively. Let’s have a look:

    • css!

      This prefix is used for forcing yepnope to treat a resource as a stylesheet. By default, yepnope treats .css files as stylesheets and everything else as a JavaScript file. So, if you’re serving up CSS dynamically, this prefix would force yepnope to treat that resource as a stylesheet.

      	yepnope('css!styles.php?colorscheme=blue');
      					

    • preload!

      This prefix allows you to load / cache a resource without executing it.

      	yepnope('preload!userInterface.js');
      					

    • ie!

      There may be circumstances where you need to load specific resources only if you’re working with Internet Explorer or a particular version of Internet Explorer. Thus, the ie prefixes help you target resource loading to ie or specific versions of it. Here’s a list of the supported ie prefixes where gt stands for “versions greater than” and lt stands for “versions less than”.

      • Internet Explorer:
        ie!
      • Internet Explorer by version number:
        ie5!, ie6!, ie7!, ie8!, ie9!
      • Internet Explorer versions greater than:
        iegt5!, iegt6!, iegt7!, iegt8!
      • Internet Explorer versions less than:
        ielt7!, ielt8!, ielt9!

      All of these filters are chainable and serve as a sort of OR operator in that if one of them evaluates to true the resource will be loaded. So, should we need to target ie7 and ie8, we would simply prepend the appropriate filters to the url of the resource as follows:

      	yepnope('ie7!ie8!userInterface.js');
      					

    Creating your own filters!

    Should you ever need to, yepnope also provides the means with which to create your own filters and prefixes by way of the addFilter and addPrefix methods. Any filter or prefix you create is passed a resourceObject containing a number of useful props. Remember, though, to return the resourceObject as yepnope requires that you do so. Here’s a look at the resourceObject:

    • url:

      The url of the resource being loaded.

    • prefixes

      The array of applied prefixes.

    • autoCallback

      A callback which runs after each script loads, separate from the others.

    • noexec

      A boolean value which forces preload without execution.

    • instead

      An advanced function which takes the same parameters as the loader.

    • forceJS

      A boolean which forces the resource to be treated as javascript.

    • forceCSS

      A boolean which forces the resource to be treated as a stylesheet.

    • bypass

      A boolean which determines whether or not load the current resource

    Let’s say, for example, you want the ability to toggle resource loading between your CDN and web server, on the fly. Can we do that, though!? Yep! Let’s create two prefixes, one for loading from the CDN and the other for loading from your web server.

    	yepnope.addPrefix('local', function(resourceObj) {
    
    		resourceObj.url = 'http://mySite/resources/' + resourceObj.url;
    		return resourceObj;
    
    	});
    
    	yepnope.addPrefix('amazon', function(resourceObj) {
    
    		resourceObj.url = 'http://pseudoRepository.s3.amazonaws.com/' + resourceObj.url;
    		return resourceObj;
    
    	});
    			

    Using these prefixes, we can now easily switch between our CDN and web server!
    	yepnope([
    		'local!css/typography.css',
    		'amazon!defaultStyle.css'
    	]);
    			

    Step 8 – A few Caveats

    So, while maintaining a very small footprint, the yepnope conditional loader is power-packed with a number of useful features! There are, however, a few things you should be aware of before using it.

    • No document.write

      As with any asynchronous loader, you can’t use document.write.

    • Internet Explorer less than 9 and callback execution

      Internet Explorer versions less than nine don’t guarantee that callbacks run immediately after the related script fires.

    • Be careful with the DOM

      Your script may be loaded and executed before the DOM is ready. So, if you’re manipulating the DOM, it’s advisable to use a DOM ready wrapper.

    • You should still combine where you can

      Just because you’re using an asynchronous loader doesn’t mean that you shouldn’t combine your resources where you can.

    • Internet Explorer asynchronous load limits

      Older versions of Internet Explorer can only load two resources from the same domain at the same time, where as other versions can load up to six. So, if you’re loading multiple files, consider using a sub-domain or CDN.

    Conclusion – Thoughts on yepnope.js

    All in all, I found yepnope to be a great utility! Not only does it support the asynchronous loading of both scripts and stylesheets, but it provides you with a nice, clean way to load HTML5 and CSS3 polyfills conditionally. The callback mechanism is well thought out and the ability to add your own prefixes and filters is just great! Performance wise, I found yepnope to be somewhat on par with other loaders, such as Getify Solutions’ LABjs and James Burke’s require.js. Obviously, each loader is different and suits a different need but if you haven’t yet, I encourage you to give yepnope.js a go!


  • Permalink for 'Turbocharge your Website with Memcached'

    Turbocharge your Website with Memcached

    Posted: February 6th, 2012, 10:49am MST by Nicolas Sebban

    Your latest PHP/MySQL website is finally online. And it’s awesome. But it’s not as fast as you want it to be, because of the many SQL queries running every time a page is generated. And above that, you have the feeling it will not scale well under heavy loads. And you are most likely right.

    In this tutorial, we will see how you can greatly improve your website’s responsiveness, and help it scale to handle many simultaneous visitors, by implementing a cache layer between your code and your database. The good news is it is fairly easy, and can be done in a few minutes!

    Introducing Memcached

    Memcached is a high-performance in-memory data caching system.

    Modern websites and web applications use a lot of data, and it’s not uncommon to count as many as 20 or even 30 SQL queries in a single page generation. Multiply this amount by a big number of visitors, and you often get an overloaded database, and pages that take seconds to be generated and sent to the client.

    The tool we are going to use today to improve performance is called Memcached. It’s a high-performance in-memory data caching system. Or to put it another way, a very fast application that runs on your server and uses a fraction of the available memory to store an associative array of data. You can ask Memcached to do two things :

    • Store the value V with the key K
    • Retrieve the value V stored with the key K

    This looks minimalist, but there’s a lot you can do thanks to these two features, as we will see very soon. In fact, Memcached can do a few more things, but they’re all tied to storing or retrieving data.

    Installing Memcached on modern Linux distributions is quite simple :

    • Ubuntu : sudo apt-get install memcached
    • Gentoo : sudo emerge install memcached
    • Redhat : sudo yum install memcached

    Once installed, Memcached will be automatically started every time your server boots. You can set the amount of memory reserved for Memcached, along with other options, in the configuration file (/etc/memcached.conf). 64Mb is allocated by default. The configuration file also contains the IP address and the port Memcached will be bound to. Default values (127.0.0.1 and 11211) are fine for a standard setup.

    Accessing Memcached from PHP

    We want to store and retrieve data from your PHP scripts. This means we are going to need a way to connect to Memcached from PHP. For that, we’re going to install the “Memcache” extension for PHP. As it is a PECL extension, it is very easy to install with the “pecl” by typing the following command :

    sudo pecl install memcache
    

    There are two PHP extensions related to Memcache : “Memcache” and “Memcached” (notice the “d” in the second one). Both are very similar, but the first one has a smaller footprint. In this tutorial, we will use the lighter Memcache. Once installed, this extension should be enabled and the Memcache-related functions should now be available to your PHP scripts.

    How does Caching Work?

    Our work here is based on the following assumptions:

    • retrieving data from the database takes resources (CPU + i/o)
    • retrieving data from the database takes time
    • we often retrieve the very same data over and over

    We also want to store our data it in a way that allows us to retrieve it efficiently.

    Generally speaking, we want to save our data in a persistent environment (our MySQL database for instance). But we also want to store our data it in a way that allows us to retrieve it efficiently, even if the storage is non-persistent. So in the end, we will have two copies of our data : one being stored in MySQL and the other being stored in Memcache.

    Here are the steps we have to take to make this happen :

    • Every write operation (SQL INSERTs and UPDATEs) will be performed in both MySQL and Memcached
    • Every read operation (SQL SELECTs) will be performed in Memcached, and will fall back to MySQL in case of error

    At this point, you probably see which parts of your code need to be modified : parts where you write data and parts where you read data. If your PHP code is well structured, you should have wrapped your data access code in functions or —even better— classes. If so, updating your site should be very fast. If not, you might have a little more work.

    Connecting to our Cache Server

    First of all, let’s create a connection to our Memcached server. Here is the code you should use, early in your PHP scripts :

    	// Connection constants
    	define('MEMCACHED_HOST', '127.0.0.1');
    	define('MEMCACHED_PORT', '11211');
    
    	// Connection creation
    	$memcache = new Memcache;
    	$cacheAvailable = $memcache->connect(MEMCACHED_HOST, MEMCACHED_PORT);
    

    At this point, we have established a connection to our Memcache server. It may have failed, but we know so thanks to the $cacheAvailable variable.

    Storing Data in our Cache

    Let’s dive into data storage. We are going to take an example to make things clearer – an online shop. We have a script called edit_product.php whose purpose is to save a product’s data into our database. Each one of our products has the following information:

    • id
    • name
    • description
    • price

    At some point in our edit_product.php code, we run an INSERT or UPDATE SQL query whose purpose is to write this product’s data to our MySQL database. It could look just like this :

    	// We have validated and sanitized our data
    	// We have escaped every risky char with mysql_real_escape_string()
    	// Now we want to save it into our database
    	$sql = "INSERT INTO products (id, name, description, price) VALUES ($id, '$name', '$description', $price)";
    	$querySuccess = mysql_query($sql, $db);
    

    As I mentioned above, we want to store our data both in our MySQL database and Memcached server. Here is how we are going to proceed :

    	// We have validated and sanitized our data
    	// We have escaped every risky char with mysql_real_escape_string()
    	// Now we want to write them to our database :
    	$sql = "INSERT INTO products (id, name, description, price) VALUES ($id, '$name', '$description', $price)";
    	$querySuccess = mysql_query($sql, $db);
    
    	// We have written our data into our database
    	// Now let's store the product name, description and price into our cache
    	// The method "set" tells our Memcached server to store the data associated to a specific key
    	if ($querySuccess === true)
    	{
    		// We build a unique key that we can build again later
    		// We will use the word 'product' plus our product's id (eg. "product_12")
    		$key = 'product_' . $id;
    
    		// We store an associative array containing our product data
    		$product = array('id' => $id, 'name' => $name, 'description' => $description, 'price' => $price);
    
    		// And we ask Memcached to store that data
    		$memcache->set($key, $product);
    	}
    

    At this point, both our database and cache contain our product data.

    Retrieving Data from our Cache

    In case our cache is unavailable, we want to fall back to MySQL.

    Now let’s retrieve our data. In the same example, let’s say our online shop has a script called product.php that displays a specific product. Accessing the page product.php?id=12 will display the product whose identifier is 12.

    At some point in our product.php code, we run a SELECT SQL query whose purpose is to retrieve a product’s data from our MySQL database. It could look just like this :

    	// We have validated and sanitized our data
    	// We have escaped every risky char with mysql_real_escape_string()
    	// Now we want to read from our database :
    	$sql = "SELECT id, name, description, price FROM products WHERE id = " . $id;
    	$queryResource = mysql_query($sql, $db);
    	$product = mysql_fetch_assoc($queryResource);
    

    As we said above, we want to retrieve our data from our Memcached server if possible, because it’s faster than getting it from MySQL. But in case our cache server can’t be reached, or if it simply doesn’t store the data we need, we want to fall back to MySQL. Here is how we are going to proceed :

    	// Initialize our $product variable
    	$product = null;
    
    	// First we check that our cache server is available
    	// The $cacheAvailable variable was initialized when we connected to our cache server
    	if ($cacheAvailable == true)
    	{
    		// We build the key we associated to our product data
    		$key = 'product_' . $id;
    
    		// Now we get the data from our cache server
    		$product = $memcache->get($key);
    	}
    
    	// do we need to access MySQL ?
    	if (!$product)
    	{
    		// In case we do...because our $product variable is still null
    		// We have validated and sanitized our data
    		// We have escaped every risky char with mysql_real_escape_string()
    		// Now we want to read from our database :
    		$sql = "SELECT id, name, description, price FROM products WHERE id = " . $id;
    		$queryResource = mysql_query($sql, $db);
    		$product = mysql_fetch_assoc($queryResource);
    	}
    

    At this point, we have retrieved the data we needed. It was most likely done from our cache, but could be from MySQL if the cache was not filled or couldn’t be accessed for some reason.

    Conclusion

    We have seen how Memcached can be used to speed up your website and limit your database load. Our example above was based on PHP and MySQL because these techologies are widely deployed, but this principle is universal and works just the same with many other technologies : C/C++, Java, Python, Ruby, Perl, .Net, MySQL, Postgres, Erlang, Lua, Lisp, Cold Fusion, Ocaml and io are listed along with PHP on the official Memcached wiki.

    As I briefly mentioned earlier, Memcached provides more features than the simple set and get methods we’ve seen above. Two useful additional features are increment/decrement updates, and the ability to set an expiration time to a specific stored data. Both are available in PHP, along with a few others, as you can see in the Memcache documentation.

    Have fun implementing this on your websites, and enjoy the —free— performances improvement. Thank you so much for reading and please let me know if you have any questions in the comments below.


  • 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:

    • $graph_path – this is the Facebook graph path, which is essentially the “URL” to the open graph object we want to access. This can be any graph object on Facebook, like a Post (e.g. ‘/<post_id>’), a Comment (e.g. ‘/<comment_id>’), or even a User (‘/me’ is a shortcut for the current user whom the $access_token belongs to. It can also be ‘/<user_name>’ or ‘/<fb_uid>’, but the $access_token you’re using must have access to that user, or you’ll only be able to get the user’s public information).
    • $method – this is the kind of method you want to do. It’s usually GET when you’re trying to “get” information, and POST when you’re trying to “post” or update information and DELETE if you want to remove information. If you’re not sure, the Graph API documentation tells you which method to use for specific API calls.
    • $params – these are the parameters that come with your API request. Usually for GET methods you only need to supply the user’s $access_token. For POST methods though, you’ll also need to provide other parameters. For example, if you want to post a new status update, you’ll provide the status update message here.

    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
    • id – this is the Post‘s ID
    • from – contains information about the user who posted the message
    • message (red) – the message component of the post
    • picture (orange) – a link to the photo attached to the post
    • name (blue) – the “title” of the Facebook post
    • link (also blue) – the link to where the name goes to when clicked
    • caption (purple) – a few words to describe the link
    • description (pink) – more than a few words to describe the link
    • icon (grey) – a link to the icon image used
    • actions – Facebook actions you can do to the post, such as Liking it or Commenting on it.
    • privacy – the privacy of the post
    • type – the type of the post. A post can be a status, link, photo or video.
    • created_time – the time when the post was created
    • updated_time – the time when the post was updated
    • comments – comments on the post

    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:

    • access_token – the access token of the account we are publishing for
    • message – the message to publish
    • picture (optional) – a link to the photo of the post
    • name (optional) – the “title” of the post
    • link (optional) – a link to where the name will go to when clicked
    • caption (optional) – a few words to describe the link/name
    • description (optional) – more than a few words to describe the link/name

    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:

    • CSS3 Essentials – In this course, we’ll cover the essentials of what you absolutely must know about CSS3. This means we’ll review the basics, like border-radius and box-shadow; but, we’ll also work our way up to more advanced techniques, such as using animations to add flair to your designs.
    • 30 Days to Your First Website Design – Ready to design your first website but not sure how to start? Ian Yates, Editor of Webdesigntuts+ and veteran web designer, walks you through every step of getting your first web design up and running. From the planning stages up until the pages go live, you’ll get expert guidance on how to make sure your first design gets done… and done right.
    • 30 Days to Learn HTML and CSS – Even if your goal is not to become a web designer, learning HTML and CSS can be an amazing tool to have in your skill-set – both in the workplace, and at home. If this has been on your to-do list for some time, why don’t you take thirty days and join me? Give me around ten minutes every day, and I’ll teach you the essentials of HTML and CSS. And don’t worry…we start at the beginning!
    • Create Killer Build Scripts with Phing – In this 12-part Premium screencast course, I’m going to teach you exactly how to work with the popular build script tool, Phing. Phing allows us to automate so many of the things we do manually for each project, such as compressing and concatenating code, FTPing files, and pushing projects to GitHub. When you’re ready to dig in, just push play!

    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.

    • Should designers use CSS preprocessors and frameworks, like Sass and Compass, respectively, before learning the ins and outs of CSS?
    • Is it okay for a Ruby developer to use CoffeeScript without first learning JavaScript?
    • Should you use Modernizr before learning how to write a single feature test?
    • Is it okay to use CodeIgniter if you’ve only just learned PHP?

    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:

    • Learn jQuery; get excited.
    • Realize that you have no clue what this refers to in different situations. Learn JavaScript, and incrementally improve your old jQuery code.
    • (Optional) Advance your skills to the point where you need a more comprehensive framework for building large applications. Begin reviewing additional tools, such as Dojo.

    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:

    • Normalize browser quirks
    • Write less code
    • Benefit from as many minds as possible
    • Meet real deadlines, and get the job done

    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:

    • NLM XML content will be uploaded via the CMS and converted to PDF and HTML.
    • Linking from citing articles, Google Scholar and CrossRef
    • A Reader needs to be integrated for the journals.
    • Usage for subscribers and also pay-per-view
    • Usage report for stats

    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:

    • name — the unique spark id
    • version — current version
    • compatibility — minimum CodeIgniter version
    • dependencies — (optional) other sparks required by this spark
    • tags — (optional) tags that describe this spark

    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:

    • config
    • helpers
    • libraries
    • views

    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:

    • configs
    • helpers
    • libraries
    • models
    • views
    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:

    • First, the address of the Twitter RSS feed is generated. Config outlined a username (twitter) and an endpoint (twitterURL); now, the two are combined using sprintf.
    • Next, the RSS data in each feed are retrieved using the loadURL function the atomizer library. This function returns an “AtomizerFeed” object that provides some useful functions for manipulating RSS data.
    • Finally, AtomizerFeed’s convolve operation is used to combine the two feeds’ items into a single feed, which is returned.
    • At this point, we’re almost ready to fire up dovecote in a live application. We just need to check to make sure that our application includes all of dovecote’s dependencies and that the spark itself will load correctly.

      Step 4: Dependencies

      When we wrote spark.info, recall the line where we described dovecote’s dependencies:

      Dependencies:
         Atomizer: 0.0.1
      

      This means that dovecote relies on another spark—Atomizer—to function. Once sparks are committed to the getsparks.org repository, the manager utility will download dependencies automatically. While we remain in local development, however, we’ll need to do this ourselves.

      If you’re using the sparks manager, you can install Atomizer by navigating to your CodeIgniter directory and invoking the manager’s install function:

      php tools/spark install -v0.0.2 atomizer
      

      Note: If you’re on Windows, you will need to invoke php tools\spark install -v0.0.2 atomizer instead.

      If you aren’t using the manager, or if the installation didn’t complete successfully, you can download Atomizer from Github and extract it into your application’s sparks directory next to the folder containing dovecote.

      Step 5: Autoloading

      Before dovecote will be available to other parts of the application, we’ll need to make sure that it will load correctly. Return to the config folder in your spark directory and paste the following into a new file called autoload.php.

      <?php /** config/autoload.php **/
      
      // load default configuration
      $autoload['config'] = array( 'dovecote' );
      
      // load dependency
      $autoload['sparks'] = array( 'atomizer/0.0.2' );
      
      // load library
      $autoload['libraries'] = array( 'dovecote' );
      ?>
      

      Whenever CodeIgniter loads a spark, it will attempt to load all the resources listed in autoload.php as well. This allows sparks authors to define the resources that users should have immediate access to whenever they load the spark. Because the dovecote library is specified here, for instance, we will have immediate access to the retrieve function as soon as the spark is loaded.

      It’s worth mentioning that the resources described in autoload.php need not reside in the spark directory. As long as they’re located somewhere in CodeIgniter’s search path, the application should be able to find them. Notice atomizer is being loaded in the example above; it wouldn’t do much good to list a spark’s dependencies but be unable to load them!

      Save the autoload file, and let’s load it all up. In the welcome controller in your main application (/application/controllers/welcome.php), add the following:

      public function dovecote() {
          $this->load->spark( 'dovecote/0.0.1' );
          $this->dovecote->retrieve();
          $this->dovecote->publish();
      }

      Let’s walk through that:

      1. We ask CodeIgniter to load dovecote, knowing that all the resources requested in config/autoload.php will be loaded as well
      2. dovecote’s retrieve function is used to get copies of the RSS feeds described in config/dovecote.php
      3. The combined timeline produced by retrieve is served up as an RSS feed using dovecote’s publish function
      See it in Action

      Browse to welcome/dovecote in your browser, and you should be greeted with an RSS feed chronicling the tweets and articles that dovecote has collected.

      Step 6: Building on the Spark

      Let’s make dovecote a little more useful. First, we’ll create a basic view template to show the title of each article in our timeline:

      <?php /** views/dovecote_timeline.php */ ?>
      
      <h3>Recent Happenings:</h3>
      <ol>
      <?php foreach ($items as $item): ?>
          <li><?php echo $item->title; ?></li>
      <?php endforeach; ?>
      </ol>
      

      Next, we’ll make the view accessible by providing a helper function that other parts of the application can use to render the timeline in HTML.

      <?php /** helpers/dovecote_helper.php */
      
      function dovecote_timeline() {
      
          $ci = &amp;get_instance();
      
          $feed = $ci->dovecote->retrieve();
      
          $data = array(
              'items' => $feed->items()
          );
      
          $ci->load->view( 'dovecote_timeline', $data );
      }
      
      ?>
      

      The dovecote_timeline function and its eponymous view can now be used to render the timeline anywhere in our application. But in keeping with CodeIgniter’s only-what-you-need philosophy, we won’t make it automatically available via autoload.php. Instead, we’ll need to load the helper manually whenever it is needed. Return to your application’s welcome controller, and update the dovecote function to generate an HTML version of the feed:

      public function dovecote() {
          $this->load->spark( 'dovecote/0.0.1' );
          $this->load->helper( 'dovecote' );
      
          $this->dovecote->retrieve();
      
          // call the helper function
          echo dovecote_timeline();
      }
      

      Refresh your browser, and you should now see a list of all the items in dovecote’s timeline.

      An HTML version of the dovecote timeline Wrapping Up

      Congratulations! You’re now the owner of a very simple spark, but there’s plenty more that can be done. Before sending dovecote out for action, you may consider writing additional functions. The details are up to you, but some useful features might include:

      • caching of API responses
      • views for beautifying the data retrieved
      • data persistence to save older timeline items (check the feed license, first!)

      This tutorial offers the barest outlines of what can be done with sparks and introduces the advantages that sparks can provide in minimizing repetition and speeding up development.

      Working on a spark of your own? Having issues getting started out? Share a little more in the comments below and thank you so much for reading!


  • 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:

    • specify criteria that MUST match. i.e., an AND clause
    • specify criteria that CAN optionally match. i.e., an OR clause
    • specify criteria that MUST exist
    • and much more…
    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:

    • Ascending: -1
    • Descending: 1

    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:

    • What Mongo is
    • How to install it
    • How to create, find, update and delete records

    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
    
    • The $pdo data member is the PHP Data Object used to query the database.
    • The $phpExcel data member is the PHPExcel object used to build and manipulate the spreadsheet.
    • The $sql_pagesarray holds the SQL Statement and the page formating/naming information.
    • The constructor (not shown) initializes the PDO and PHPExcel data members.
    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:

    • Django – We’re going to use this today. It has a huge set of features, but remains simple to use. The documentation is also excellent, so if you get stuck, you’ll have the easiest time solving your problem with Django.
    • Grok – Another framework with a feature set that comes close to Django. If you decide you don’t prefer Django, this is a good alternative.
    • WebPy – A much more lightweight framework. It doesn’t have as many features, though it did power Reddit for a period of time!
    • TurboGears – Though previously having a reputation for poor documentation, TurboGears has improved substantially in the last year.

    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?

    • __init__.py tells Python that this folder is a Python package. We learned about these in the third lesson; it allows Python to import all of the scripts in the folder as modules.
    • manage.py isn’t actually part of your website; it’s a utility script that you run from the command line. It contains an array of functions for managing your site.
    • settings.py contains your website’s settings. Django doesn’t use XML files for configuration; everything is Python. This file is simply a number of variables that define the setting for your site.
    • urls.py is the file that maps URLs to pages. For example, it could map yourwebsite.com/about to an About Us page.

    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.