NETTUTS

Syndicate content NETTUTS
Web Development & Design Tutorials
Updated: 6 hours 32 min ago

Incredible Services and Products

Wed, 2010-07-28 16:08


Okay, okay; this may be a thank you posting for the wonderful sponsors of our massive HTML5 competition, however, it’s important for me to note that I refused to accept sponsors of any product that I didn’t honestly feel was fantastic. What this means is that, as the editor of Nettuts+, I fully endorse each and every one of the following services and products, and, in fact, use many of them on a daily basis! That’s why I asked these companies to sponsor the competition!

1. TechSmith TechSmith

TechSmith has been extremely generous to Envato in the last few years. Luckily, that has no effect on the fact that the products they provide — everything from Camtasia Studio to Jing Pro, are amazing.

Did you know that I personally use their products every single day? When you watch screencasts from Nettuts+, they were recorded with Camtasia Studio for Mac. When I send out quickie videos and images, I use Jing Pro to distribute them on Twitter. Not only that, but they’re constantly updating their products, and support both Windows and Mac.

“We’ve stayed on top of the screen capture and recording game since the launch of Snagit nearly 20-years-ago.”

2. Media Temple Media Temple

In addition to being my personal web host of choice, Media Temple is hugely respected around the web as being one of the premier web hosts. Whether hosting jQuery, or Starbucks, or even Django’s site, MediaTemple can handle the load! They come highly recommended.

Media Temple hosts websites. Big and Small. For years we’ve taken complex technology and simplified it for the everyday website owner. Our products are designed to be powerful, affordable and relevant. Please take a look around; perhaps (mt) is a good choice for your next project.”

3. FormStack FormStack

Do we recommend FormStack? Well consider this; the submission form to enter the HTML5 competition…was created with FormStack. Their service is incredibly simple to use.

“Formstack’s easy form builder gives businesses and organizations an easy way to build any type of online form, integrate it with their website and begin collecting data. ”

4. Wufoo Wufoo

At Envato, we use Wufoo as well. If you haven’t heard Chris, from CSS-Tricks praise Wufoo enough, let us assure you that their service comes with the highest recommendation from Nettuts+. I even use them on my own personal sites!

“What is Wufoo? Wufoo strives to be the easiest way to collect information over the Internet. Our HTML form builder helps you create contact forms, online surveys, and invitations so you can collect the data, registrations and online payments you need without writing a single line of code.

5. FusionCharts Fusion Charts

FusionCharts has long been regarded as the premier solution for rendering animated graphs and charts for your business. Just browse through their various demos if you don’t believe me!

“FusionCharts v3 helps you create animated and interactive Flash charts for web and desktop applications. It livens up your applications by converting monotonous data into exciting visuals. “

6. Pagelime PageLime

We’ve published PageLime tutorials a couple of times on Nettuts+ recently. The huge advantage with their service is that zero coding is required on your part. This makes it significantly appealing to non-tech savvy folks. Most recently, they’ve launched a reseller program, as well as a new navigation manager.

Pagelime is a brandable CMS that lets your clients manage their content. No installation, no coding to integrate, and no wasted time. Just add the cms-editable CSS class to any HTML element on your site and Pagelime does the rest.”

7. Campaign Monitor Campaign Monitor

There’s a reason why Facebook, Ebay, and Twitter utilize Campaign Monitor’s services: they’re the best! In fact, their email CSS guide has been proven to be a bible for me, when creating designs optimized for email. They even contributed a tutorial to Nettuts+ not too long ago on the state of CSS3 in email designs.

Send beautiful email campaigns, track the results, and manage your subscribers.”

8. Snippets Snippets

If you’ve watched my tutorials, you might have noticed a little scissors icon in my menu bar. That’s for Snippets. It’s an incredible code snippet management tool for Mac, that I use on a daily basis. Even better, it has support for Snipplr uploading — which Envato recently purchased!

“Snippets is a powerful application for Mac OS X that stores the most valuable pieces of code you can reuse in different projects many times.”

9. Querious Querious

In need of a kick-ass MySQL database management app for Mac? I was, and Querious proved to be the best tool for the job. I use it often in my SQL-based video tutorials.

“Querious is a MySQL database management application written from the ground up for Mac OS X. Unlike mindless Mac OS X ports of applications originally made for Windows or Linux, Querious works the way you’d naturally expect it to as a Mac OS X app.”

10. Miva Merchant Miva Merchant

Miva Merchant has been around for a long time, and is one of the top providers of e-commerce solutions on the web.

Miva Merchant is a leading supplier of e-commerce software and services to small and medium-sized businesses. We provide online merchants, developers, web designers and web hosts with the information and technology needed to be successful in today’s online selling environment.

11. Rockable Press Rockable Press

Envato’s publishing branch, Rockable Press, is in full force these days — especially with the release of our CEO’s newest book, “How to Build a Successful Blog Business,” which I’m currently reading through. To be objective…it’s fantastic.

“At Rockable Press, we produce simple, straight forward how-to guides and resources for web and creative professionals. We are a small web publishing outfit operated by Envato with authors based around the world. ”

12. jQuery Enlightenment jQuery Enlightenment

To this day, jQuery Enlightement holds the spot as my most recommended book on jQuery. Written by Cody Lindley, the book is succinct, and cuts out all of the fluff. As a result, you learn everything you need to know…as quickly as possible. Not only that, but he utilizes JSBin to provide clickable code examples for all of the demos. This has proven to be an extremely smart decision on his part, and you’ll surely see others adopting this same method in the future.

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.”

13. WP Structure Theme WP Structure Theme

Chris Robinson is far and away one of the best authors on ThemeForest, and this theme is a perfect example of his talents.

“Months in development WP Structure is a highly flexible and heavily optioned premium theme, to be used for almost anything business, portfolio, blog, magazine & more!”

Categories: How-to's & Tutorials

CSS: Noob to Ninja – The Complete Video Series

Wed, 2010-07-28 09:58


This exclusive premium video series will take you from a state of absolute CSS “noobness,” all the way up to ninja-status, capable of taking advantage of the latest CSS3 techniques. The series begins with the basics: the syntax, properties, etc. However, each new video expands upon the previous, as you work your way up and improve your skills. In this final week, you’ll complete the series, as you gain access to Parts 8-12: five new episodes.

In these final video tutorials, you’ll learn about a variety of CSS3 techniques, how to use custom fonts, working with CSS frameworks, and how to extend CSS with applications like LESS. Don’t fall behind! Become a Premium member!

The Full Screencast Series: Exclusive to Premium Members
  • Part 1: Preparation
  • Part 2: CSS Properties
  • Part 3: Typography
  • Part 4: Floats
  • Part 5: Positioning
  • Part 6: Semantics, List Items, and Menus
  • Part 7: CSS Organizational Techniques
  • Part 8: Rounded Corners, Box Shadows, and Text Shadows
  • Part 9: CSS3 Gradients
  • Part 10: Custom Fonts with @font-face
  • Part 11: Taking Advantage of CSS Frameworks
  • Part 12: Extending CSS with LESS
Video Sample Join Net Premium NETTUTS+ Screencasts and Bonus Tutorials

For those unfamiliar, the family of TUTS sites runs a premium membership service. For $9 per month, you gain access to exclusive premium tutorials, screencasts, and freebies from Nettuts+, Psdtuts+, Aetuts+, Audiotuts+, and Vectortuts+! For the price of a pizza, you’ll learn from some of the best minds in the business. Become a Premium member!

Categories: How-to's & Tutorials

Start Using HTML5 WebSockets Today

Wed, 2010-07-28 07:54


One of the cool new features of HTML5 is WebSockets, which let us talk to the server without using AJAX requests. In this tutorial, we’ll review the process of running a WebSocket server in PHP, and then building a client to send and receive messages to it over the WebSocket protocol.

What are WebSockets?

WebSockets is a technique for two-way communication over one (TCP) socket, a type of PUSH technology. At the moment, it’s still being standardized by the W3C; however, the latest versions of Chrome and Safari have support for WebSockets.

What do WebSockets Replace?

Websockets can replace long-polling. This is an interesting concept; the client sends a request to the server – now, rather than the server responding with data it may not have, it essentially keeps the connection open until the fresh, up-to-date data is ready to be sent – the client next receives this, and sends another request. This has its benefits: decreased latency being one of them, as a connection which has already been opened does not require a new connection to be established. However, long-polling isn’t really a piece of fancy technology: it’s also possible for a request to time-out, and thus a new connection will be needed anyway.

Many Ajax applications makes use of the above – this can often be attributed to poor resource utilization.

Wouldn’t it be great if the server could wake up one morning and send its data to clients who are willing to listen without some sort of pre established connection? Welcome to the world of PUSH technology!

Step 1: Get the WebSocket Server

This tutorial will focus more on the client building rather than server implementation.

I’m using XAMPP on Windows 7 to run the PHP server locally. Grab a copy of phpwebsockets which is a WebSocket server in PHP. (Note: I experienced some problems with this version, I made some changes to it and will including it in the source files) There are various WebSocket implementations; if one doesn’t work, you can try another or just continue with the tutorial.

Start the Apache server Step 2: Change URLs and Ports

Change the server according to your setup, for example in setup.class.php:

public function __construct($host='localhost',$port=8000,$max=100) { $this->createSocket($host,$port); }

Browse through the files and make changes where appropriate.

Step 3: Start Building the Client

Lets get a basic template up; this is my client.php file:

<!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <title>WebSockets Client</title> </head> <body> <div id="wrapper"> <div id="container"> <h1>WebSockets Client</h1> <div id="chatLog"> </div><!-- #chatLog --> <p id="examples">e.g. try 'hi', 'name', 'age', 'today'</p> <input id="text" type="text" /> <button id="disconnect">Disconnect</button> </div><!-- #container --> </div> </body> </html>​

So in this code we’re creating a simple template: we have a box for the chat log, an input box, and one disconnect button.

Step 4: Add Some CSS

Nothing fancy, just space some elements out.

body { font-family:Arial, Helvetica, sans-serif; } #container{ border:5px solid grey; width:800px; margin:0 auto; padding:10px; } #chatLog{ padding:5px; border:1px solid black; } #chatLog p { margin:0; } .event { color:#999; } .warning{ font-weight:bold; color:#CCC; } Step 5: WebSocket Events

First, let’s try and understand the idea of WebSocket events.

The Events

We’ll be using three events:

  • onopen: When a socket has opened
  • onmessage: When a message has been received
  • onclose: When a socket has been closed

But how can we implement this?

First create a WebSocket object

var socket = new WebSocket("ws://localhost:8000/socket/server/startDaemon.php");

And checking for events is as simple as:

socket.onopen = function(){ alert("Socket has been opened!"); }

But what about when we receive a message?

socket.onmessage = function(msg){ alert(msg); //Awesome! }

However, let’s avoid using alert boxes, and actually integrate what we’ve learned into the client page.

Step 6: JavaScript

Ok, so let’s get started. First we put our code in jQuery’s document ready function, then we check whether the user has a WebSockets-enabled browser. If they do not, we append a link to Chrome in the HTML.

$(document).ready(function() { if(!("WebSocket" in window)){ $('#chatLog, input, button, #examples').fadeOut("fast"); $('<p>Oh no, you need a browser that supports WebSockets. How about <a href="http://www.google.com/chrome">Google Chrome</a>?</p>').appendTo('#container'); }else{ //The user has WebSockets connect(); function connect(){ //the connect function code is below } });

As you can see, if the user has WebSockets then we call a connect() function. This is the core of the functionality: we’ll start with the open, close and receive events.

We’ll define the URL of our server

var socket; var host = "ws://localhost:8000/socket/server/startDaemon.php";

Wait, where’s the http in that URL? Oh right, it’s a WebSocket URL, so it’s using a different protocol. Here’s a breakdown of the pieces of our URL:

Let’s continue with our connect() function. We will put our code within a try/catch block; so if something goes wrong, we can let the user know. We create a new WebSocket, and pass the message to a message function which I’ll explain later. We create our onopen, onmessage and onclose functions. Note that we also show the user the socket status; this is not necessary, but I’m including it here as it can be helpful for debugging.

  • CONNECTING = 0
  • OPEN = 1
  • CLOSED = 2
function connect(){ try{ var socket; var host = "ws://localhost:8000/socket/server/startDaemon.php"; var socket = new WebSocket(host); message('<p class="event">Socket Status: '+socket.readyState); socket.onopen = function(){ message('<p class="event">Socket Status: '+socket.readyState+' (open)'); } socket.onmessage = function(msg){ message('<p class="message">Received: '+msg.data); } socket.onclose = function(){ message('<p class="event">Socket Status: '+socket.readyState+' (Closed)'); } } catch(exception){ message('<p>Error'+exception); } }

The message() function is fairly simple, it takes in some text that we want to show the user and appends it to the chatLog. We create the appropriate class for paragraph tags in the socket event functions which is why there is only one closing paragraph tag in the message function.

function message(msg){ $('#chatLog').append(msg+'</p>'); } So Far…

If you’ve been following up to this point, well done! We’ve managed to create a basic HTML/CSS template, create and establish a WebSocket connection and keep the user updated as progress was made with the connection.

Step 7: Sending Data

Now rather than having a submit button, we can detect when the user presses return on their keyboard, and run the send function. The ’13′ you see below is the ASCII key for the enter button.

$('#text').keypress(function(event) { if (event.keyCode == '13') { send(); } });

And here’s the send() function:

function send(){ var text = $('#text').val(); if(text==""){ message('<p class="warning">Please enter a message'); return ; } try{ socket.send(text); message('<p class="event">Sent: '+text) } catch(exception){ message('<p class="warning"> Error:' + exception); } $('#text').val(""); }

Remember what you see above may be a chunky bit of code, but in reality, the code we really need is:

socket.send(); //Thanks JavaScript

The extra code is doing a number of things: detecting if the user didn’t enter anything but still hit return, clearing the input box, and calling the message functions.

Step 8: Closing the Socket

Closing the socket is fairly straightforward: attach a click handler to our disconnect button and we’re done!

$('#disconnect').click(function(){ socket.close(); }); The Completed JavaScript $(document).ready(function() { if(!("WebSocket" in window)){ $('#chatLog, input, button, #examples').fadeOut("fast"); $('<p>Oh no, you need a browser that supports WebSockets. How about <a href="http://www.google.com/chrome">Google Chrome</a>?</p>').appendTo('#container'); }else{ //The user has WebSockets connect(); function connect(){ var socket; var host = "ws://localhost:8000/socket/server/startDaemon.php"; try{ var socket = new WebSocket(host); message('<p class="event">Socket Status: '+socket.readyState); socket.onopen = function(){ message('<p class="event">Socket Status: '+socket.readyState+' (open)'); } socket.onmessage = function(msg){ message('<p class="message">Received: '+msg.data); } socket.onclose = function(){ message('<p class="event">Socket Status: '+socket.readyState+' (Closed)'); } } catch(exception){ message('<p>Error'+exception); } function send(){ var text = $('#text').val(); if(text==""){ message('<p class="warning">Please enter a message'); return ; } try{ socket.send(text); message('<p class="event">Sent: '+text) } catch(exception){ message('<p class="warning">'); } $('#text').val(""); } function message(msg){ $('#chatLog').append(msg+'</p>'); } $('#text').keypress(function(event) { if (event.keyCode == '13') { send(); } }); $('#disconnect').click(function(){ socket.close(); }); }//End connect }//End else }); Step 9: Run the WebSocket Server

We will need command line access. Luckily, XAMPP has a handy shell option. Click ‘Shell’ on the XAMPP control panel, and type in:

php -q path\to\server.php

You have now started a WebSocket server!

Finished

When the page loads, a WebSocket connection will attempt to be established (try editing the code so the user has connect/disconnect option). Then, the user can enter messages and receive messages from the server.

That’s it!

Thanks for reading; I hope you enjoyed this tutorial! Remember, as exciting as WebSockets may be, things may change. You can refer here to keep up to date on the W3C WebSocket API.

Categories: How-to's & Tutorials

Behind the Scenes of Nettuts with Collis!

Tue, 2010-07-27 23:51


Here at Envato we’re pretty famous for building a lot of successful blogs, like this one! We’ve done quite a few now, so last year I decided other people might find our techniques and systems useful. Today I’m really happy to announce my new book How to Build a Successful Blog Business which is a step by step guide to doing what we do, and it comes packed with case studies for our blogs including Nettuts!

The book covers everything from picking a niche to hiring staff, monetizing to building traffic. Like all my books it’s very practical, but I think the best part is the case studies because they include things like our income and expense graphs, detailed backstories about how our sites came to be, and much more. To give you a taste of what the book is like, I thought you might like to read a little part of the case study about Tuts:

Extract The Tuts Case Study

… Nine months after launching Psdtuts+, it was time to expand out the clearly successful formula to other types of tutorials. Beginning with web development and Nettuts+, we launched over the course of two years a total of seven more sites. Each one applies the same overall editorial concept into a different niche, with a different editor and different writers.

The plus side of this is that the Tuts+ franchise as a whole has now grown far beyond just Photoshop tutorials. The down side is that whenever our revenue looked like it was going to pass costs, we would launch a new site driving our costs up again.

To manage a suite of blogs also introduces an additional layer of complexity as you now need a business capable of:

  • Managing a team of editors each with a team of writers
  • Hiring, training and occasionally replacing editors
  • Handling hundreds of invoices from writers and freelance staff every month
  • Managing servers, installations and themes

These requirements meant we brought on first a Tuts+ manager by the name of Skellie, who was a former editor of FreelanceSwitch. Then secondly, we hired a WordPress developer named Derek Herman who took over building and managing the themes on all the blogs. Thirdly we hired a freelance and later a full-time PHP developer to manage the servers, optimize performance and handle emergencies.

Because Tuts+ is run as part of a larger startup, we have had the benefit of piggy-backing accounting, management and legal costs from our parent business Envato. For an independent blog business however these are significant costs not to be discounted.

Increasing Costs

As the network grew it also became apparent that we needed to pay our writers and contributors more. While the base submission payment is still $150, the payments for regular writers and special one-off contributors has increased so that we now pay a range of $200 – $800 per tutorial depending on the experience and fame of the author and the depth, length and quality of the content.

Similarly the additional burden of managing the growing enterprise also led to greater and greater costs as we hired more staff, more management overhead and of course the ever present hosting costs.

In fact by late 2009 our monthly bandwidth had passed 40 Terrabytes of data a month leading to hosting costs in the many thousands of dollars…

Extracted from How to Build a Successful Blog Business, by Collis Ta’eed

Read More Extracts

You can read more extracts from the other case studies over on FreelanceSwitch, Psdtuts+ and Mac.AppStorm (the other sites covered in the case studies). You can also read a sample chapter by heading to our sales page for the book.

Get the Book!

You can learn more about the book, as well as find out what top100 bloggers like Darren Rowse from Problogger and Daniel Scocco from DailyBlogTips are saying about it over on the epic sales page that we’ve constructed! Get Blog Business!

Also Envato Birthday Bundle 2010!

And while I’m here with news about my book, I thought I’d also mention that next month we’re running our annual Envato Birthday Bundle for 2010 and it’s going to be EVEN bigger than last year with over $400 of value selling for just $20! Find Out about Envato Birthday Bundle 2010.

So watch out, it’s going to be a big August!

Categories: How-to's & Tutorials

Build an Incredible HTML5 App: $7000 Competition

Tue, 2010-07-27 19:45


As HTML5′s popularity continues to increase, we at Tuts+ and CodeCanyon would like to do our part in promoting and rewarding those who are on the cutting edge of what’s possible with HTML5, local storage, geolocation, SVG, and CSS3. Not only that, but we’re also, at the conclusion of this competition, launching a brand new category on our coding marketplace, CodeCanyon, specifically for HTML5 apps.

We have $7000 worth of prizes from some of the most respected companies in our industry, but the creators of the best items will also profit by selling their HTML apps on CodeCanyon. Authors: you have one month to prepare the coolest, cutting edge HTML5 app that you’re capable of. What prizes are we offering??

Grand Prize Winner

I’m pleased to announce that I can personally recommend every single one of the following sponsors who offered items and services to this competition. We wouldn’t promote them if we didn’t feel that way!

2 Runners-Up Prizes How Does it Work?

The rules are quite simple. Using HTML5 technologies (and feel free to throw in some CSS3 goodness while you’re at it), we want you to build a cutting edge app. It could be similar to something along the lines of:

  • The recent HTML5 presentation app
  • An awesome cross-browser HTML5 video player, with full screen support, Flash fallback, etc.
  • A kick-ass to-do list with offline storage support.
  • An HTML5 website that people would swear was created with Flash
  • etc.

Feel free to combine all modern technologies when building your item, including HTML5, geolocation, offline storage, CSS3, SVG, and any other acronym that is applicable to your project. Once you have finished building your “app,” — and you have a month to make it — return to this page, where there will be a contest submission form to fill out.

Most Importantly: We want you to build an item that people will actually use. Particle effects are great, but unless you have an argument for why others would have a need for your particle item in their project, it most likely won’t be in the running for the grand prize spot. Think wide-spread, when building your app. A presentation app is wide-spread, video players are wide-spread. Use your imagination!

Selling on CodeCanyon

In late August, CodeCanyon.net will be launching a new “HTML5 Apps” category, which we fully expect to be monstrously popular. After we select the best items from this contest — including the ones that didn’t win one of the top three prizes — we will contact the authors about selling their items on CodeCanyon in this new category, where they’ll earn between 40-70% for each sale. Considering Envato’s 430,000 marketplace members, and the fact that many of these authors make thousands of dollars each month, you’ll do quite well if your item appeals to a wide variety of people. By entering this competition, you agree that, if your item is chosen, it will be uploaded to CodeCanyon under your account, and will help to serve as seed content for the category.

Frequently Asked Questions

Please note that this section will sporadically be updated as questions come in from the community.

  1. When is the deadline? You have until August 23rd, 2010, at 11:59 PM (USA Central Standard time).
  2. How do I enter? When ready, submit your item here.
  3. If I win the contest, how will my item be sold on CodeCanyon? At that point, we will contact you about creating your free author account (if you don’t already have one), and submitting your item. It’s quite easy. Plus, because your item will be part of the new category’s seed content, you’ll get a tremendous amount of exposure as we advertise the category like crazy!
  4. Can I submit to the upcoming “HTML5 Apps” category even if I don’t win? Absolutely…and I hope you do!
  5. Can Envato staff enter this competition? Unfortunately not.
  6. Must my item support all browsers? No; we fully understand that these are items that simply won’t work in all browsers. However, do your best to provide some level of support for as many browsers as possible.
Terms and Conditions
  • This competition is open to anyone and everyone, excluding Envato staff.
  • You have until August 23rd, 2010, at 11:59 PM (USA Central Standard time) to submit your item
  • The winners of the contest will be determined by a team of no less than three judges.
  • Items must officially be submitted here to be considered for the prizes.
Good Luck!!

We can’t wait to see what you come up with. There are a lot of prizes at stake here, so submit the best possible item you’re capable of! And remember, even if you don’t win, if your item is of a high quality, you can still profit from every sale on CodeCanyon. Many authors make thousands upon thousands of dollars each month by doing this!

The deadline is August 23rd. Ready…set…go!!

Categories: How-to's & Tutorials

Quick Tip: 4 Ways to Auto-Refresh your Browser when Designing new Sites

Tue, 2010-07-27 08:49


You know the drill: make some edits to your document, click save, switch over to your browser, refresh it, and then observe the changes. Wouldn’t it be convenient if there was to auto-refresh your browser at a provided interval? That way, for instance, every three seconds, the browser will automatically refresh. Granted, this isn’t too practical for heavy websites, however, when you’re first beginning the design of a new website, it’s quite convenient! I’ll show you a couple of ways of achieving this.

Premium Members: Download this Video ( Must be logged in) Subscribe to our YouTube page to watch all of the video tutorials! Prefer to watch this video on Screenr? Option 1: Meta Tag

Did you know that, with the addition of a single meta tag into your document, you can instruct the browser to automatically reload at a provided interval?

<meta http-equiv="refresh" content="3" />

Placed within the head tag of your document, this meta tag will instruct the browser to refresh every three seconds. Pretty nifty!

You must remove this tag before you launch your site! It should only be used for initial development purposes.

Option 2: TextMate Commands

Those of you who use TextMate, or E-Text-Editor on the PC, may not be taking advantage of commands as much as you should. Did you know that there is a shell script built in to TextMate that will also force the browser to reload as soon as you press the applicable key trigger?

Simply open the “Bundles” menu, and load the bundle editor.

TextMate Bundle Editor

Within the HTML tab, you’ll find a “Refresh Running Browsers” script. Memorize, or change the activation key (in my case, Apple + R), return to your document, and try it out. This is the preferred solution if you use either of these two code editors.

Option 3: XRefresh XRefresh

A Firefox Add-on, called XRefresh, will monitor your project folder, and, every time it detects a change to the source files, it’ll reload Firefox. This one works great, but requires a bit of work to get up and running.

Option 4: Coda: Lively

Coda users may not be familiar with one of my favorite plugins, called Lively. Like the options above, this allows Coda users to immediately observe the changes they make to their projects in real-time. If you use Coda, this is a must-have.

So what’s your preferred method? Personally, I tend to stick with options two and four. How about you?

Categories: How-to's & Tutorials

Magento for Designers: Part 6

Tue, 2010-07-27 08:06


Magento is a stunningly powerful e-commerce platform. In this miniseries, we’ll learn how to get started with the platform, get to know the terminologies, set up a store and all related aspects of it and finally learn how to customize it to make it our very own.

In this sixth part, we’ll be building one of the most reader requested feature: getting a featured product slider in the home page. Excited? Let’s get started!

The Full Series A Quick Recap

In the last part, we built the product information page and took a good look at how data is extracted and displayed in a typical Magento theme.

We also took a look at the various core methods that our theme uses to get various media and data about our product. I hope you remember at least a sliver of that information because we’ll be using it again today.

What are We Building Today?

Today, we’ll build the all important home page. As always, I’ll keep it as simple as possible and omit any extraneous features. Different stores have different content in their home pages. One of the most popular and definitely one of the most requested features is displaying a JavaScript powered content slider featuring special featured products. I know it sounds interesting and you’re itching to get started. Let’s get started!

Goals for the Page

As with our other pages, our goals for this specific page are relatively simple. We want a simple slider that displays specific products in a neat slider. Thus, I’ve drawn up a short list of elements that I think it needs:

  • JavaScript slider on the home page
  • Slider needs a catchy image on the left to attract attention to the product
  • In the right portion, we’ll be including the product’s name, price and a short description
  • A mini navigation within the slider to switch between different slides
  • And most important of all, not rely on an extension to obtain the featured items

That’s it. I want to keep it as simple as possible and thus opted to not over do it. We will of course need to work with both the front end and back end to accomplish all our goals.

The Basic Look

The page basically has to look like so:

Step 1 – The HTML

We’ll first look at the HTML for the content part alone. I’m assuming you’re fairly fluent in HTML and CSS so I’ll skip to the fairly important parts.

<div id="home-slideshow"> <div class="slide"> <div class="product-image"> <a href="#" title="Zonda F"> <img src="images/zonda.jpg" alt="Zonda F" title="Zonda F" /> </a> </div> <div class="product-details"> <h2>Zonda F</h2> <div class="price">700,000.00 </div> <p>The Pagani Zonda is a mid-engined sports car produced by Pagani in Italy. </p> </div> </div> <!-- More slides for successive products --> </div>

At this point, this is all pretty basic. home-slideshow is the container we’re wrapping the entire slideshow with and will be passed on to the JavaScript responsible for the slider.

Each slide is wrapped by a div called slide. Inside we have two floated containers: one for the image and the second for the information about the product itself.

That’s about all there is to it. We can move on to the styling part now.

Step 2 – The CSS /* Home page */ .slide { clear: both; overflow: auto; padding: 10px; width: 898px; border: 1px solid #E1E1E1; background: #F6F6F6; } .product-image { float: left; width: 650px; padding: 10px; border: 1px solid #E1E1E1; background: #FAFAFA; } .product-details { float: left; width: 190px; margin: 0 0 0 20px; } .product-details .price { margin: -15px 0 0 0; color : #7db000; } .product-details p{ margin: 10px 0 0 0; } #nav { position: absolute; top: 255px; right: 250px; z-index: 2000; } #nav a { margin-right: 10px; height: 5px; width: 5px; z-index: 1000; float: left; text-indent: -9999px; cursor: pointer; border: 1px solid #fff; background: #eee; } #nav a:hover { border: 1px solid #fff; background: #999; } #nav a.activeSlide { border: 1px solid #444; background: #333; }

Nothing fancy here. Very basic CSS to place the elements in position.

The only point to note is the declaration for the class activeSlide. This class is assigned to the current slide’s respective navigation anchor.

Step 3 – Setting up Our Store

The first thing we need to do is setup a separate category to which we can assign all the products that we need to appear on our slider. Click on the catalog menu and then on categories. Choose add new root category.

 Part VI

Key in a name of your choice and then choose no for the is active dropdown. We don’t want it displaying in other parts of the site.

 Part VI

Once the new category has been saved, you can find the ID it has been assigned to. Note this down. We’ll need it for later.

Step 4 – Creating Our Core Code

We’ll be using a single template file to pull out the relevant information, format it as needed and display everything. You have complete freedom regarding the name and location of this file but in the interest of keeping it simple, I’ve named it featured.phtml and placed it in catalog/product/featured.phtml. Remember, this goes into your template folder, not your layout folder.

The contents of the file looks like so. Don’t worry about the length, we’ll look at each part works after the code.

<?php $cat_id = "2"; $_productCollection = Mage::getResourceModel('catalog/product_collection') ->addAttributeToSelect(array('name', 'price', 'small_image', 'short_description'), 'inner') ->addCategoryFilter(Mage::getModel('catalog/category')->load($cat_id)); if(!$_productCollection->count()): echo $this->__('There are no products matching the selection.'); else: ?> <div id="home-slideshow"> <?php $i=0; foreach ($_productCollection as $_product): ?> <div class="slide"> <div class="product-image"> <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>"> <img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(650, 250); ?>" alt="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" /></a> </div> <div class="product-details"> <h2><?php echo $_product->getName(); ?></h2> <div class="price"><?php echo number_format($_product->getFinalPrice(),2);?> </div> <p><?php echo $_product->getShortDescription(); ?></p> </div> </div> <?php endforeach ?> </div> <?php endif; ?>

Here’s the first piece:

$cat_id = "2";

First, we’ll need to specify the ID of the category from which we want to pull in our products. In our case, this will be 2, the ID of the category we just created.

$_productCollection = Mage::getResourceModel('catalog/product_collection') ->addAttributeToSelect(array('name', 'price', 'small_image', 'short_description'), 'inner') ->addCategoryFilter(Mage::getModel('catalog/category')->load($cat_id));

This looks slightly complicated but let me assure you, it’s very simple. To put it in layman’s terms, we essentially pass in the ID of the category we need through the variable cat_id and ask Magento to retrieve the name, price, image and short description of the products that match. Right now, I’d advise you to not fiddle with the rest unless you’re well versed in MVC and other aspects of Magento’s architecture.

if(!$_productCollection->count()): echo $this->__('Sorry, no items matched your selection criteria'); else: ?>

We will need to check whether we have matching items, don’t we? That’s what we’re doing here. Just making sure we have matching items. If not, we display an error.

<?php $i=0; foreach ($_productCollection as $_product): ?>

Let’s start looping through our product collection!

<a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>"> <img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(650, 250); ?>" alt="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" /></a> <h2><?php echo $_product->getName(); ?></h2> <div class="price"><?php echo number_format($_product->getFinalPrice(),2);?> </div> <p><?php echo $_product->getShortDescription(); ?></p>

If you’ve read the previous part of this series, this code must be pretty familiar to you. We use Magento’s baked in methods to retrieve media pertaining to our product.

The second snippet may look a little different because instead of using slightly more abstracted methods, I used closer-to-bone methods to directly acquire the data we need.

If you’re feeling a little confused here, just go through the above code one more. The name of the methods are pretty explanatory. The only stumbling block should be how we acquire the image itself: we ask one of our helpers to acquire the image and resize it to the size we need. Nothing more to it.

Note that we open and close a slide div each time our loop runs. This is to encapsulate each product’s information with a container element to make it easy for us to create a slider later.

And with this, our base PHP code is complete.

Step 5 – The JavaScript

It makes no sense to completely reinvent the wheel here since the core focus of this series is on Magento. Thus, we’ll be using an excellent plugin to create our slider today: the jQuery Cycle plugin.

But first, go to root/js and create a folder named cirrus. Different people have different methods of organizing here. I prefer having a theme’s JS separate instead of organizing them by source. We’ll need a copy of jQuery [1.4 hopefully], the latest cycle plugin and a custom script file, which I’m naming mocha.

Here’s the content of our JS file.

(function($) { $(document).ready(function(){ $('#home-slideshow') .before('<div id="nav">') .cycle({ fx: 'fade', speed: 1500, timeout: 5000, pause: 1, delay: 5000, pager: '#nav' }); }); })(jQuery)

First up, notice that we’re wrapping everything inside a (function($) { //Code })(jQuery) block. This is make sure jQuery doesn’t conflict with any other included library.

The document ready block, as always, is to make sure that our code runs only after all the page’s assets are loaded since Magento likes to put our JavaScript files at the top.

Initializing the plugin is pretty simple. Just type in the ID of the main container, home-slideshow in our case, and away we go. I’ve just tweaked some of the options to make it do our bidding.

Something to take note of is that we’re dynamically creating and positioning our container for the navigation elements inside the DOM with JavaScriptS. This element is only needed if JavaScript is enabled. If it isn’t, we don’t want empty, useless code in our page.

We also pass in the selector the navigation container to the slider plugin.

That’s it. The JavaScript part of our code is done.

Step 6 – Setting up Our Home Page

Now that all our groundwork has been completed, we can finally configure our home page now.

 Part VI

Click on the CMS menu and choose the pages option. Click on home page in the resulting page.

 Part VI

The first tab should be pretty self explanatory. Make sure that our page is enabled.

 Part VI

In the content tab, make sure you enter the following after disabling the editor:

{{block type="catalog/product_list" block_id="featured.products" template="catalog/product/featured.phtml"}}

This is Magento’s method of including required blocks. We just give it an ID to refer it by and point it to our custom template.

 Part VI

In the design tab, change the layout template to 1 column since we’re using it for everything and then enter the following into the layout update xml field.

<reference name="head"> <action method="addCss"><stylesheet>css/home.css</stylesheet></action> <action method="addJs"><script>cirrus/jquery-1.4-min.js</script></action> <action method="addJs"><script>cirrus/cycle.js</script></action> <action method="addJs"><script>cirrus/mocha.js</script></action> </reference>

Remember how when building the product page, we included custom CSS in the page’s layout file to make sure the entire codebase isn’t loaded for every page? We’re doing essentially the same here. Instead of creating a XML file just for this, Magento lets us enter this directly through the interface.

We just load our custom CSS, our JS libraries and the script file that contains all our code.

Click on “save” to save up all our progress, empty Magento’s cache and watch the beautiful slider on your home page slide through in its excruciatingly lovely glory!

What We’ll be Building in the Next Part

.. is completely up to you. I’ve already covered almost all relevant information for customizing any view and going through each and every view is completely counter-intuitive. Thus, I’ve concluded that all that’s left is how to create a custom module and I think by then this series will have runs its course. I may write a quick Magento tweaks and optimization how-to if enough people show interest for such an article.

If you do feel that something else needs to be covered before this series comes to a close, don’t hesitate to leave a comment below to let me know!

The Last Word

And we are done! Today, we learnt how to create a custom home page complete with a slider displaying featured products. We also learnt to do all this without relying on a third party extension and instead coding all this ourselves. Hopefully this has been useful to you and you found it interesting. Since this is a rather new topic for a lot of readers I’ll be closely watching the comments section so chime in there if you’re having any doubts.

Questions? Nice things to say? Criticisms? Hit the comments section and leave me a note. Happy coding!

Categories: How-to's & Tutorials

Quick Tip: Improve Site Performance in 3 Easy Steps

Mon, 2010-07-26 09:36


We all know we should do it, but how many of us do? I’m talking about minifying JavaScript, CSS, and optimizing images to reduce load times. Today, I’ll show you three quick and easy methods that all of us should implement to improve our site’s performance.

Premium Members: Download this Video ( Must be logged in)

Subscribe to our YouTube page to watch all of the video tutorials!

So what other techniques do you use to improve load times?

Categories: How-to's & Tutorials

20 Steps to a Flexible and Secure WordPress Installation

Mon, 2010-07-26 07:57


A comprehensive WordPress installation, albeit simple to produce, often requires multiple steps — many of which can easily be omitted accidentally. How many times have you forgotten to customize your permalink structure? How about adding in a sitemap plugin? What about changing your timezone? If you’ve installed WordPress more than once, chances are you’ve missed something. Take the following steps and you’ll never miss anything again.

Step 1: Get WordPress from SVN

The number one mistake for a flexible WordPress installation happens right from the get-go. I’ve seen numerous developers manually download, unzip, and upload WordPress to their site. This is not only a waste of time, but it also reduces flexibility.

If you download WordPress from SVN, all you need to do is run the following in command-line:

svn co http://core.svn.wordpress.org/tags/3.0 .

Maybe you want the latest developer version. That’s even simpler:

svn co http://core.svn.wordpress.org/trunk/ .

Why is this so useful? For starters, all it takes is one command. Looking at WordPress in a long-term perspective reveals that SVN also provides the simplest, hassle-free way to update to a new stable version (or even downgrade). For example, let’s say you want to update to version 3.0. All you need to do is run the SVN switch command:

svn sw http://core.svn.wordpress.org/tags/3.0/ .

How easy was that? Note that if you’re using the developer version, updating is even easier:

svn up

That’s all it takes. If you ever need the URL to a new stable version repository, visit the WordPress Codex. You can also find full instructions on using SVN there.

“Looking at WordPress in a long-term perspective reveals that SVN also provides the simplest, hassle-free way to update to a new stable version (or even downgrade).”

Step 2: Secure .svn Directories Directory

Now that you’re using SVN, you must ensure that your .svn directories are protected from the public. One main reason lies in the .svn/entries file, which can give out sensitive information to attackers. For further information regarding this subject, please take a look at Smashing Magazine’s article on the SVN server admin issue.

To secure .svn directories using .htaccess, just apply the following redirect rule:

RewriteRule ^(.*/)?\.svn/ - [F,L] Step 3: Create wp-config.php

As outlined in the famous 5-minute WordPress installation, you’ll need to rename wp-config-sample.php to wp-config.php and add in your database information.

Step 4: Add a Unique Database Prefix and Authentication Keys Keys

Leaving your wp-config.php file only with database information and no other configuration is a security issue. Make sure to generate authentication keys, as outlined in the comments. To do so, visit https://api.wordpress.org/secret-key/1.1/salt/ and copy-paste the randomly-created keys into the file.

Note that you should also change the default WordPress database table prefix. This is to secure your installation against hacks, such as the recent outbreak of the Pharma Hack. Visit random.org to generate a random prefix string which you’ll need to set as the $table_prefix in wp-config.php. In addition, make sure to add an underscore at the end of the prefix.

Step 5: Install Using wp-admin/install.php

As usual, visit wp-admin/install.php in your browser and follow the instructions. When filling out the form, change the default administrator username (“admin”) in order to increase security. Note that most attackers will target a WordPress installation with default settings. Thus, changing this username is a must.

“Note that most attackers will target a WordPress installation with default settings.”

Step 6: Remove wp-admin/install.php

This is a commonly-omitted step which only takes a few seconds to execute. Simply remove the wp-admin/install.php script after installing WordPress for further security.

Step 7: Login to the Dashboard and Complete User Profile

Login to your WordPress installation at http://example.com/wp-admin, click your username in the top-right corner, and fill out your user profile.

Step 8: Edit Tagline and Timezone Timezone

Under the Settings > General tab, make sure to edit your blog’s timeline as well as timezone.

Step 9: Review Writing, Reading, and Discussion Settings

Although you might not have to change anything, looking over Settings > Writing, Settings > Reading, and Settings > Discussion is always a good idea. Ensure that the configuration meets your standards.

Step 10: Change Permalink Structure Permalink

A default WordPress installation comes with query-string permalinks that look like http://example.com/?p=1 for each article. Not only is this not search-engine friendly, but it’s also not even human-friendly. Change this to a permalink structure that contains the title of the post (%postname% if you’re using a custom configuration).

Step 11: Add .htaccess Rules

An .htaccess file is necessary for your WordPress site to function correctly. To begin, turn on the RewriteEngine:

RewriteEngine On

Disable directory listings for security purposes:

Options -Indexes

Add/Remove www to prevent content duplication (replace example.com with your domain):

# Add www (change www.example.com to example.com to remove www) RewriteCond %{HTTP_HOST} !^www.example.com$ [NC] RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

WordPress requires you to redirect all non-files and directories to index.php:

RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . index.php [PT]

Disable ETags:

Header unset ETag FileETag None

Suppress PHP errors (note that this might not work on all hosts):

php_flag display_startup_errors off php_flag display_errors off php_flag html_errors off php_value docref_root 0 php_value docref_ext 0

Control caching on files to speed up your site:

ExpiresActive On ExpiresDefault A0 <FilesMatch "\.(gif|jpg|jpeg|png|swf)$"> # 2 weeks ExpiresDefault A1209600 Header append Cache-Control "public" </FilesMatch> <FilesMatch "\.(xml|txt|html)$"> # 2 hours ExpiresDefault A7200 Header append Cache-Control "proxy-revalidate" </FilesMatch> <FilesMatch "\.(js|css)$"> # 3 days ExpiresDefault A259200 Header append Cache-Control "proxy-revalidate" </FilesMatch>

Secure the .htaccess file:

<Files .htaccess> Order Allow,Deny Deny from all </Files>

Secure the wp-config.php file:

<Files wp-config.php> Order Deny,Allow Deny from all </Files>

Secure .svn directories, as explained in step #2:

RewriteRule ^(.*/)?\.svn/ - [F,L]

If you would like to add more configuration for your website and are looking for a general tutorial, consider Nettuts’ Ultimate Guide to htaccess Files or Stupid htaccess Tricks on Perishable Press.

Step 12: Use gzip Gzip

Applying gzip can compress text files up to 80% and greatly save bandwidth. Making it active on your site only requires a PHP file and a bit of .htaccess. Note that the following code is referenced from a gzip tutorial on Lateral Code.

PHP (gzip.php): <?php if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) && substr_count( $_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip' ) && !preg_match( '/(load-styles|load-scripts)\.php/', $_SERVER[ 'SCRIPT_NAME' ] ) ) ob_start( 'ob_gzhandler' ); else ob_start(); ?>

This may look a bit daunting at first, but it really isn’t too bad. The large boolean expression checks whether gzip is available and, if so, it’s applied. Unfortunately, I have found that this gzip method doesn’t function well with WordPress’ load-styles.php and load-scripts.php. As a result, the preg_match is used to exclude them.

.htaccess: <FilesMatch "\.js$"> AddHandler application/x-httpd-php .js php_value default_mimetype "text/javascript" </FilesMatch> <FilesMatch "\.css$"> AddHandler application/x-httpd-php .css php_value default_mimetype "text/css" </FilesMatch> <FilesMatch "\.(htm|html|shtml)$"> AddHandler application/x-httpd-php .html php_value default_mimetype "text/html" </FilesMatch> php_value auto_prepend_file /absolute/path/to/gzip.php

This snippet adds the php handler to .html, .css, and .js files so that they can be gzipped. It also prepends the previously mentioned gzip.php file. Make sure to change /absolute/path/to/gzip.php to the correct path.

Step 13: Apply the 4G Blacklist

Perishable Press’ 4G Blacklist will prevent numerous attacks on your website through .htaccess. I’ve included the code below (edited for WordPress). You can learn about how it works by reading the article on Perishable Press:

### PERISHABLE PRESS 4G BLACKLIST ### # ESSENTIALS RewriteEngine on ServerSignature Off Options All -Indexes Options +FollowSymLinks # FILTER REQUEST METHODS <IfModule mod_rewrite.c> RewriteCond %{REQUEST_METHOD} ^(TRACE|DELETE|TRACK) [NC] RewriteRule ^(.*)$ - [F,L] </IfModule> # BLACKLIST CANDIDATES <Limit GET POST PUT> Order Allow,Deny Allow from all Deny from 75.126.85.215 "# blacklist candidate 2008-01-02 = admin-ajax.php attack " Deny from 128.111.48.138 "# blacklist candidate 2008-02-10 = cryptic character strings " Deny from 87.248.163.54 "# blacklist candidate 2008-03-09 = block administrative attacks " Deny from 84.122.143.99 "# blacklist candidate 2008-04-27 = block clam store loser " Deny from 210.210.119.145 "# blacklist candidate 2008-05-31 = block _vpi.xml attacks " Deny from 66.74.199.125 "# blacklist candidate 2008-10-19 = block mindless spider running " Deny from 203.55.231.100 "# 1048 attacks in 60 minutes" Deny from 24.19.202.10 "# 1629 attacks in 90 minutes" </Limit> # QUERY STRING EXPLOITS <IfModule mod_rewrite.c> RewriteCond %{QUERY_STRING} \.\.\/ [NC,OR] RewriteCond %{QUERY_STRING} boot\.ini [NC,OR] RewriteCond %{QUERY_STRING} tag\= [NC,OR] RewriteCond %{QUERY_STRING} ftp\: [NC,OR] RewriteCond %{QUERY_STRING} http\: [NC,OR] RewriteCond %{QUERY_STRING} https\: [NC,OR] RewriteCond %{QUERY_STRING} mosConfig [NC,OR] # RewriteCond %{QUERY_STRING} ^.*(\[|\]|\(|\)|<|>|'|"|;|\?|\*).* [NC,OR] # RewriteCond %{QUERY_STRING} ^.*(%22|%27|%3C|%3E|%5C|%7B|%7C).* [NC,OR] RewriteCond %{QUERY_STRING} ^.*(%0|%A|%B|%C|%D|%E|%F|127\.0).* [NC,OR] RewriteCond %{QUERY_STRING} ^.*(globals|encode|localhost|loopback).* [NC,OR] RewriteCond %{QUERY_STRING} ^.*(request|select|insert|union|declare|drop).* [NC] RewriteRule ^(.*)$ - [F,L] </IfModule> # CHARACTER STRINGS <IfModule mod_alias.c> # BASIC CHARACTERS RedirectMatch 403 \, RedirectMatch 403 \: RedirectMatch 403 \; # RedirectMatch 403 \= RedirectMatch 403 \@ RedirectMatch 403 \[ RedirectMatch 403 \] RedirectMatch 403 \^ RedirectMatch 403 \` RedirectMatch 403 \{ RedirectMatch 403 \} RedirectMatch 403 \~ RedirectMatch 403 \" RedirectMatch 403 \$ RedirectMatch 403 \< RedirectMatch 403 \> RedirectMatch 403 \| RedirectMatch 403 \.\. # RedirectMatch 403 \/\/ RedirectMatch 403 \%0 RedirectMatch 403 \%A RedirectMatch 403 \%B RedirectMatch 403 \%C RedirectMatch 403 \%D RedirectMatch 403 \%E RedirectMatch 403 \%F RedirectMatch 403 \%22 RedirectMatch 403 \%27 RedirectMatch 403 \%28 RedirectMatch 403 \%29 RedirectMatch 403 \%3C RedirectMatch 403 \%3E # RedirectMatch 403 \%3F RedirectMatch 403 \%5B RedirectMatch 403 \%5C RedirectMatch 403 \%5D RedirectMatch 403 \%7B RedirectMatch 403 \%7C RedirectMatch 403 \%7D # COMMON PATTERNS Redirectmatch 403 \_vpi RedirectMatch 403 \.inc Redirectmatch 403 xAou6 Redirectmatch 403 db\_name Redirectmatch 403 select\( Redirectmatch 403 convert\( Redirectmatch 403 \/query\/ RedirectMatch 403 ImpEvData Redirectmatch 403 \.XMLHTTP Redirectmatch 403 proxydeny RedirectMatch 403 function\. Redirectmatch 403 remoteFile Redirectmatch 403 servername Redirectmatch 403 \&rptmode\= Redirectmatch 403 sys\_cpanel RedirectMatch 403 db\_connect RedirectMatch 403 doeditconfig RedirectMatch 403 check\_proxy Redirectmatch 403 system\_user Redirectmatch 403 \/\(null\)\/ Redirectmatch 403 clientrequest Redirectmatch 403 option\_value RedirectMatch 403 ref\.outcontrol # SPECIFIC EXPLOITS RedirectMatch 403 errors\. # RedirectMatch 403 config\. RedirectMatch 403 include\. RedirectMatch 403 display\. RedirectMatch 403 register\. Redirectmatch 403 password\. RedirectMatch 403 maincore\. RedirectMatch 403 authorize\. Redirectmatch 403 macromates\. RedirectMatch 403 head\_auth\. RedirectMatch 403 submit\_links\. RedirectMatch 403 change\_action\. Redirectmatch 403 com\_facileforms\/ RedirectMatch 403 admin\_db\_utilities\. RedirectMatch 403 admin\.webring\.docs\. Redirectmatch 403 Table\/Latest\/index\. </IfModule>

A few of these rules are commented out or edited because they interfere with WordPress. If you are having problems with certain URLs, fix them by prepending a “#” (comment) to the corresponding rule.

Step 14: Activate Akismet

“Activating Akismet is a must in order to prevent comment spam.”

Activating Akismet is a must in order to prevent comment spam. Do so by registering for an API key at akismet.com. Note that a WordPress.com account API key will also work.

Once you obtain a key, visit Plugins > Akismet Configuration in your dashboard and paste it in the corresponding box.

Step 15: Download Plugins Plugins

The following plugins are a great help to any WordPress blog:

For further security, these plugins, referenced from DigWP’s WordPress lockdown article, are also important:

To make installation easy, you can run the following in command-line under your plugins directory:

wget http://downloads.wordpress.org/plugin/all-in-one-seo-pack.zip wget http://downloads.wordpress.org/plugin/google-sitemap-generator.3.2.4.zip wget http://downloads.wordpress.org/plugin/wordpress-file-monitor.2.3.3.zip wget http://downloads.wordpress.org/plugin/wp-security-scan.zip wget http://downloads.wordpress.org/plugin/ultimate-security-check.1.2.zip wget http://downloads.wordpress.org/plugin/secure-wordpress.zip find . -name '*.zip' -exec unzip {} \; rm *.zip

This will retrieve zip files for the plugins, unzip them, and delete the .zips

These download links may not be correct later on due to plugin updates. As a result, you can visit the wordpress.org plugin pages listed above in order to find the updated links.

After you finish installing the plugins, make sure to enable them through the WordPress dashboard.

Step 16: Configure All in One SEO Pack

Before All in One SEO Pack becomes active, you’ll need to configure it. Go to Settings > All in One SEO to do so. Make sure to mark the “enabled” radio button. In addition, add in a home title, description, and keywords. Finally, set the rest of the options to your liking.

Step 17: Generate a Sitemap

Visit Settings > XML-Sitemap to generate your first sitemap that will be sent to search engines. Before doing so, ensure that the options on the page are what you desire. For example, I often edit the change frequencies, as my posts are modified quite often.

Once you are ready, scroll to the top of the page and click the build link (“Click here”). You might have to create two blank files—sitemap.xml and sitemap.xml.gz—in your root directory depending on the directory permissions. Nevertheless, once you finish building it for the first time, it should automatically update as long as you have “Rebuild sitemap if you change the content of your blog ” checked.

Step 18: Add Security Security

At this point, you’ve already installed four security plugins. You should now put them into use.

Visit Settings > WordPress File Monitor and add wp-content/uploads in the exclude path. Change the other information if necessary. Note that this plugin will inform you whenever it notices a change in your file system.

Under Settings > Secure WP, check Error Messages and Windows Live Writer for extra protection.

Note that there is a new “Security” tab created by WP Security Scan. Fix items in red under Security > Security and Security > Scanner. When you visit Security > Scanner, make sure to chmod all of your individual plugins with 755 as well. Furthermore, you can use the password tool to generate a strong password.

Finally, fix the errors under Tools > Ultimate Security Check and ensure your site receives an A.

Step 19: Customize Theme and Sidebar

Now that you’ve setup a flexible, secure WordPress installation, you’ll need to make it comprehensive by customizing the theme and sidebar to fit your site’s needs. Of course, there is no set method to accomplish this; each site is unique in it’s own way. Make a theme that appeals to both you and your readers.

Step 20: Write Content Write

All that’s left now is to write genuine content that appeals to your user base. You now have a flexible, secure, and comprehensive WordPress installation. Use it wisely.

Congratulations! You now have a flexible, secure, and comprehensive WordPress installation. Use it wisely!

Categories: How-to's & Tutorials

19 Important Features to Look for in a Web Host

Fri, 2010-07-23 15:28


If you’re reading this, you probably develop websites. We don’t make websites to let them sit on our own computers: we set them free on the web. While it’s often more fun to create the website than to worry about hosting it, web hosting isn’t a decision you should make quickly. In this roundup, I’ll point out 19 things you should look for when choosing your web host.

1. Amount of Storage

Ive Drive Unibody External icon by The Iconfactory, Inc.

When choosing your web hosting, one of your primary concerns will obviously be “How much data can I store?” For most small and medium web sites, you’ll find that several gigabytes should be plenty of storage. Some hosts may offer “unlimited storage”: caveat emptor! If you read the fine print (usually, the Terms and Services) you’ll find that it’s unlimited until you go over the “normal site usage.” If you think you might be close to or over whatever “normal” is, make sure you know what you can use before buying … or go with a host that sets clear limits.

2. Amount of Bandwidth

When looking for a web host, you’ll often see storage and bandwidth hand in hand. What is bandwidth? It’s the amount of data that your host will let you and your visitors upload and download (cumulatively) in a given month. Say your website is 1 megabyte of data and your monthly bandwidth is 10 MB. At the beginning of the month, you upload the entire site; now you’ve used up one MB of bandwidth. If a visitor to your site views every page, they will have downloaded 1MB of data. That means you can have up to 9 visitors in that month (assuming each views your whole site). After that, your web host will either not allow any more visitors, or (more likely) charge you extra per MB. Of course, your bandwidth is something you’ll want to keep an eye on, especially if you run a fairly popular site or do something media intensive (like host your own video, or high-res photos). Just like storage, some hosts offer “unlimited” bandwidth; again, if you think you’ll be in a grey area, find out the limits or choose a host that sets the bar where all can see it.

3. Number of Domains and Subdomains

Once you’re running one site, there’s a good chance it won’t be long until you’ve got a second one up … and then a third. It would be a pain to have to manage a hosting account for each site you own, so make sure your web host will let you host multiple domains. Often, there will be a limit on how many domains you can have on one account; make sure it will accomodate you! Usually, there will be a section in the admin panel for adding your domains and choosing which sub-folders each one will point to. The same is true for sub-domains.

4. Email Accounts and Features

Many web hosts also offer email account for your domains. You’ll want to know how many email accounts they’ll let you set up; also, don’t forget to check out their selections for receiving that mail. Do they have a webmail interface? Multiple ones that you can select from? How about integration with Google Apps (for the Gmail interface)? Can you get your mail in your client of choice via IMAP, or do they only offer POP?

5. Database Support

Database icons (including post preview icon) by barrymieny

Now-a-days, even small websites seem to have a database on the back end. You’ll want to make sure you can use the type of database you’re comfortable with. Most hosts today offer MySQL; that’s probably enough for most people, but if you’d prefer PostsgreSQL, Oracle, SQL Server, or another flavour, don’t settle for anything less. Remember, if they aren’t advertising it, they probably don’t offer it!

6. Framework Support and Easy-Install

A lot of web hosts offer support for popular frameworks, blogging systems, or CMSes. I think it’s safe to say that the majority of Nettuts’ readers are WordPress fans: it’s always nice when your web host offers a one-click install (or at least a super easy set-up) for WordPress or your CMS of choice.

7. Mobile App or Website

For most people, this will probably be a nice extra; however, I’m sure there’s something who will find having a mobile app to access your site administration / statistics on the go indespensible. While I only know of two hosts (MediaTemple and SliceHost) that currently offer iPhone and Android apps (MediaTemple’s Android app is forthcoming ), I’m sure most hosts will follow their lead. Both offer mobile websites as well, and I’m sure other hosts have the same.

8. Tech Support

This one is very important: find out exactly what your prospective host offers for tech support: can you phone them? At what times? Do they have a support email address? A ticket system? What’s their promised response time? How about a live chat? Do they have a wiki or library of help articles / tutorials? Don’t choose a host until you know exactly what support they offer; you’ll be happy for it later, trust me!

9. Shell Access

If you’re a little more advanced, you might want to consider choosing a host that offers shell access: that’s logging into your server from the command line over SSH. You’ll be able to securely copy files up and down, change file permissions for whole groups of files quickly and easily, and perform a multitude of other tasks. If you want this feature, you’ll know all that you do with it!

10. .htaccess Files

Here’s another important one: you’ll want the ability to add your own .htaccess files to your directories. What’s a .htaccess file? It’s a configuration file used by Apache server. You can use them to password protect directories, re-write URLs, redirect pages, and more. Check out the many good tuts here on Nettuts+ to get familiar with them.

11. Cron jobs

Cron jobs are another great feature to have on your web host (and there’s a good chance you’ll have them if you’ve got shell access). Cron is a “time-based job scheduler” (thanks, Wikipedia) that you can use to perform tasks on the server at given times. To learn more about how to use Cron and what you can do with it, check out the great Cron tutorial we ran back in January.

12. Language Support

This should go without saying, but make sure the host you plan to choose offers support for the server-side languages you want to use. If you plan to pick up Ruby on Rails in the next few months, you probably want to see it on the list of supported frameworks. If you want to use Django, make sure there’s Python support. Don’t lock yourself into having PHP as your only option (unless you’re sure that’s all you’ll ever want or need!).

13. Free AdWords

While not a necessarily something you need, it’s something you’ll probably want to take advantage of: many hosts offer some Google AdWords credit (usually ~$50, I’ve found) or some other form of advertising. Even if you’d rather use another advertising proxy, you can’t beat free: you might as well use it!

14. Site Backup

Don’t think that your web host is any less suseptible to data loss than your own computers; remember, servers are just big computers that everyone can read files from! What backup options, if any, does your host provide? You’ll want to back up both your site files and databases. If they don’t offer backup, figure out how you’ll be able to do it yourself: this might be one of the places that shell access and cron come in handy!

15. Choice of OS

For most people, this won’t be a big issue. Of course, if you’re developing in ASP.NET, you’ll need Windows hosting; that’s a little harder to find, and often a bit more expensive, but if you’re a Microsoft developer, the extra cost will be worth it. (If you’re interesting in learning about ASP.NET, check out our great tuts on the subject.) If you’re using an open source language, you probably won’t need to worry about which Linux/Unix distribution you’ll get; however, some hosts give you options, and some developers may have preferences, so it’s worth mentioning.

16. Extra Applications

We already talked about content management systems, but sometimes you’ll want a something more. Several hosts offer set-ups for social features like forums, bulletin boards, mailing lists. If you’ll be running an online store, some hosts offer setups for eCommerce solutions.

17. Up-to-Date-ness

If you can, find out what software versions the host you are considering offers. Some hosts aren’t quick to upgrade to the latest offering, while others will let you choose which version you want. There are few things worse than signing up for a year of hosting only to discover your host is running PHP 4.x (yes, I’ve made that mistake).

18. Up-Time

I’m sure I don’t have to convince you that it’s important to know that your visitors will be able to get to your site when they try! Find out how reliable your prospective host is; when you’re doing this, it’s important to read the fine print. Often, hosts will stretch the truth a bit (claiming 99.9% uptime, not counting almost everything that could go wrong), so make sure you understand exactly what “100% uptime” means. It would be a wise move to google around and see what other users and reviewers have said about the host.

19. Free Domain

While you may already have a domain name, there’s no such thing as too many of them. Most hosts offer this, but all else being equal, a shiny new domain name is a good enough reason to go with one host over the other.

Conclusion: What’s your tip?

I’m sure you’ve got some great tips for choosing a web hosting solution. If you do, don’t hesitate to share them in the comments! Also, let us know what hosts you’ve found reliable and which ones have come back to bite you.

Categories: How-to's & Tutorials

Envato’s Newest Site: The Netsetter

Thu, 2010-07-22 19:06


If you’re a freelancer writer, web developer, illustrator, or anyone looking to make money online, then you need to check out The Netsetter.

The Netsetter

The Netsetter is part of the Plus Network, featuring other sites you’re familiar with such as WorkAwesome and FreelanceSwitch. The focus of The Netsetter is to help you achieve your goals of making a living through online business. We have a list of 50 Netsetters You Should Know About.

Make Money Online

If you’re a freelance web developer, then you’re also a businessperson, and maybe you’re struggling to land jobs. The Netsetter will give you what you need to take your business to the next level.

A netsetter is an entrepreneur who understands what the Internet means for making money, starting businesses and changing the way they live.

A new feature is the Netsetter Directory, listing people who have had influence over the internet, such as Envato founder and CEO, Collis Ta’eed, Envato publication manager Joel Falconer, Matt Lambert, the owner of Cardeo and contributor to many start up projects and many more. If you think you’ve got what it takes to be a Netsetter then tell us why you should be in the directory.

Visit The Netsetter today!

Categories: How-to's & Tutorials

A Deeper Look at Advanced Select Queries: New Premium Tutorial

Thu, 2010-07-22 18:32


To a SQL novice, JOINs can be intimidating and somewhat frustrating. Even when you think you have the query nailed, along comes an unexpected result which make you throw up your arms in surrender to the SQL gods. In this tutorial, we are going to build upon the excellent quick tip of working with MySQL and INNER JOIN recently posted and crack open the real power of a SELECT statement. Become a Premium member to access this tutorial, and all of the other fantastic articles and screencasts across all of the Tuts sites.

What you’ll Learn About:
  • Why being specific with your queries is so important
  • INNER JOINs
  • OUTER JOINs
  • Sub-Selects
  • UNIONs
  • …and plenty more
Join Net Premium "NETTUTS+

For those unfamiliar, the family of Tuts+ sites runs a premium membership service. For $9 per month, you gain access to exclusive premium tutorials, screencasts, and freebies from Nettuts+, Psdtuts+, Aetuts+, Audiotuts+, and Vectortuts+! For the price of a pizza, you’ll learn from some of the best minds in the business. Become a Premium member.

Categories: How-to's & Tutorials

How to Create Blog Excerpts with PHP

Thu, 2010-07-22 15:24


Ever visited a blog, and noticed that each posting’s overview only contained a hundred characters or so, which is then followed by “…”? Ever wondered how to do that yourself? It’s not quite as easy as you might think. What if character number 100 occurs in the middle of a word? Do you want to display half of a word on the page? Of course not. In this video tutorial, I’ll show you how to compensate for this, as well as a host of other neat little things, like working with MySQL’s LEFT() function, using PHP’s strrpos, and substr, creating the beginning’s of an actual blog, and more.

What You’ll Learn
  • Use MySQL’s LEFT() function to create temporary columns
  • Use PHP prepared statements to query the database
  • How to create an “excerpts” section for your blog
  • PHP’s strrpos and substr functions
  • The process of creating the beginnings of a blog

Premium Members: Download this Video ( Must be logged in) Subscribe to our YouTube page to watch all of the video tutorials!
Categories: How-to's & Tutorials

Interface Design – Creative Session Wrap

Thu, 2010-07-22 08:18


It’s a wrap. This session has covered a mix of interface design topics. We’ve looked at quite a bit of inspirational icon and graphic user interface design articles, after reviewing theory on topics like creating user friendly interfaces. We’ve reviewed both in depth detailed tutorials and case studies. This session posted across numerous Tuts+ sites: Nettuts+, Psdtuts+, and Mobiletuts+. We’ll continue to expand each session as we cover new topics and integrate your feedback. Let us know what you think of this session’s material.

Interface Design – CS Content
  • Getting Started with Interface Design

    In this article we look at five fields that you should aim to learn more about in order to rock at interface design. These fields include Experience Design, Interaction Design, Information Architecture, User-Centered Design, and Graphic User Interface (GUI) Design.

    Visit Article

  • Three Steps to Fostering a User-Centered Design Culture

    As responsible designers we must educate clients on the importance – both the validity as well as the viability – of the user-centered design process, one that gives due consideration to the needs of potential users. With the three steps that follow, we’ll go over techniques that you can use to get your team thinking about what’s really important with regards to the design of their websites you’ll help them create.

    Visit Article

  • Roughly Speaking: Working within Mobile UI Design Limitations

    Today we chat with two mobile user interface designers about how they design successful mobile interfaces and intuitive navigation solutions. We’ll learn how Sacha Greif works with the limited space of the iPad by using space saving UI Elements. Eryk Pastwa discusses how to design for multiple mobile sizes, and how to properly test designs for maximum real world uses. Take a peek at their workflows, and the best practices they both put into place in their projects.

    Visit Article

  • Showcase of Macintosh Dashboard Widget UI Designs

    This inspirational compilation post showcases a collection of 32 creative, unique and easy to use Apple Macintosh Dashboard Widgets, including a selection of default widgets that ship with your Apple Mac, and a good handful or two of third party widgets.

    Visit Article

  • Designing Realistic Interfaces – Part 1

    You have to be great in many areas of Photoshop to be good at interface design. So along with the actual steps needed to create this particular interface, in this series I will also provide as many references to other tutorials, resources and concepts as possible. That way, you can have access to some of the tools that will allow you to create completely original interfaces utilizing the same methods I teach in collaboration with your own creativity. Let’s get started with Part 1 of this two part series.

    Visit Tutorial

  • Designing Realistic Interfaces – Part 2

    You have to be great in many areas of Photoshop to be good at interface design. So along with the actual steps needed to create this particular interface, in this series I will also provide as many references to other tutorials, resources and concepts as possible. That way, you can have access to some of the tools that will allow you to create completely original interfaces utilizing the same methods I teach in collaboration with your own creativity. Let’s move on with Part 2 of this two part series.

    Visit Tutorial

  • Know Your Icons Part 1 – A Brief History of Computer Icons

    As with great works of art, you must look into the past to appreciate the future. With roots as far back as the 1970′s, the humble icon has come a long way. Following is a collection of icons though history. Although there have been many other operating systems in the time between 1981 – 2010, I’ve hand picked the ones of the most significance to modern icon design. These designs show just a small fraction of the icons in the many and varied User Interfaces throughout the years.

    Visit Article

  • Know Your Icons Part 2 – Modern Icon Design

    In the last installment you learned about the history of icon design and how it has evolved from black and white representations of office items into full colored, glassy, hyper-rendered, isometric representations of… office items. In this installment I will be delving further into the world of icons and exploring what icons mean to us today.

    Visit Article

  • Exploring Graphic User Interface Styles – from Minimal to Futuristic

    A user interface (UI) can come in many styles ranging graphically from very simple, all the way to extremely complex. In this article we are going to explore a range of styles demonstrating that there isn’t just one recipe for creating a good looking, and ultimately successful user interface. Of course, not every style is represented in this article; we will be exploring several high-quality examples, representing a wide range of graphical styles from simple to complex. Enjoy!

    Visit Article

  • iPad Magazine Interface Design

    A great magazine is more than just a collection of articles around a theme or idea, it’s a curated editorial experience. Through layout design and copy it can take you to different places and teach you new things. The release of the iPad has kicked off the latest chapter in the history of magazine design. I’ve been working with a startup, Sideways.com, to create our own magazine publishing platform and here is what we’ve done.

    Visit Article

Your Thoughts on this Digital Illustration Session

We’d love to here your feedback and suggestions on how to improve Creative Sessions. We’re actively working to improve this project, by consistently adding more high quality material, and new intensive two week sessions releasing each month. We look forward to your comments.

Categories: How-to's & Tutorials

20+ Required Windows Apps: Web Designer’s Choice

Wed, 2010-07-21 10:42


In April, Jeffrey Way provided us with a list of the “20 Mac Apps You’ll Use Every Day.” Not one to be biased, if you prefer Windows, this article rounds up the best programs available for boosting your productivity as a web designer.

1. Skybound Stylizer Skybound Stylizer

While I prefer to use Firebug, I’m finding this “out of the box” CSS editor to be really helpful. Skybound Stylizer has been out for a while, but the latest version, 4.0, is now out with a lot of incredible features to help you in the development process. One of the core features is that it supports Google Chrome, Firefox 2 – 3.6, and Internet Explorer 6 – 8.

Stylizer is an exotic visual CSS editor that keeps you in the drivers seat while delivering enormous productivity gains.

2. Notepad++ Notepad++

Notepad++ is by far my favorite text editor for Windows. It’s fast, flexible and offers a variety of plugins. If you want to increase your productivity with this editor, be sure to install the ZenCoding plugin. You can download the plugin here.

Notepad++ is a text editor and source code editor for Windows, one main advantage of Notepad++ over the built-in Windows text editor, Notepad, is tabbed editing, to easily work with multiple open files.

Alternative 3. IETester IETester

IETester is the most stable and useful IE test tool available for Windows. With tabbing navigation, a source code viewer, and the debug bar, it’ll help you through the process of “happy” IE debugging.

name of tut

IETester is a free WebBrowser that allows you to have the rendering and javascript engines of IE9 preview, IE8, IE7 IE 6 and IE5.5 on Windows 7, Vista and XP, as well as the installed IE in the same process.

Alternative 4. Filezilla Filezilla

Filezilla is the most popular and free FTP for Windows, and, of course, is my favorite FTP client for this platform. It’s lightweight and easy to use.

FileZilla Client is a fast and reliable cross-platform FTP, FTPS and SFTP client with lots of useful features and an intuitive graphical user interface.

Alternative 5. Dropbox Dropbox

Dropbox is a multi-platform sync system, which is available for Windows, Mac and Linux. You can use it as a backup folder to transfer files to your friends and family. It’s amazingly intuitive and fast.

Dropbox allows you to sync your files online and across your computers automatically.

6. Jing Jing

Jing is a great tool to share images or videos in the Windows platform. It’s free, but you can order the Pro version with even more features.

Use Jing to capture anything you see on your computer screen and share it instantly… as an image or short movie.

7. XAMPP Xampp

For PHP/MySQL development, Xampp automatically installs MySQL, Apache and PHP in your PC.

XAMPP is an easy to install Apache distribution containing MySQL, PHP and Perl. XAMPP is really very easy to install and to use – just download, extract and start.

Alternative 8. FoxitReader FoxitReader

FoxitReader is the primary PDF reader in my PC; it’s very fast, and supports tabs to read my PDF files.

Foxit Reader is a multilingual PDF reader. Both the basic and full version readers can be downloaded for free. Foxit Reader is notable for its short load time and small filesize, and has been compared favorably to Adobe Reader.

9. doPDF doPDF

Print-as-PDF isn’t installed by default on Windows. That makes this tool particular handy when you need to quickly send a document.

doPDF installs itself as a virtual PDF printer driver so after a successful installation will appear in your Printers and Faxes list. To convert to PDF, you just have to print the document to doPDF, the free pdf converter.

10. Breevy – Text Expander for Windows Breevy

Breevy is one of the most responsive, intuitive text expander applications for Windows. Whether you’re a web developer, blogger or {your-occupation-here}, you’ll find this one very useful. It’s not free, but will save you hours upon hours of typing! It’s worth the cost.

Breevy is a text expander and AutoText program for Windows that helps you type faster and more accurately by allowing you to abbreviate long words and phrases — saving you time and money.

Free Alternative 11. Everything Everything

Everything is a search program. As LifeHacker said, “It does what you really want when you hit Search in Windows.”

“Everything” is an administrative tool that locates files and folders by filename instantly for Windows, 20,000 files will take about 1 second to index. 1,000,000 files will take about 1 minute.

12. Miro Miro

Miro lets you play nearly every single video format in the world; but it’s not just a video player: you can even subscribe to podcasts, video channels, etc. It’s my video player of choice. And yes! It’s free!

Miro is the only internet TV you’ll need—it’s an application that brings together thousands of shows from all over the web. There’s TONS of great content, lots of it in HD, and fresh shows are added all the time. You can watch and organize video feeds when you’re offline or traveling, find TV programs on sites like Hulu, and download from sites like YouTube. Miro downloads in HD, whenever it’s available!

Alternative 13. KeePass KeePass

KeePass is a nice and lightweight password manager for Windows. The amazing thing about it is that you can sync the database with Dropbox – But what if I own a Mac as well? Okay, just install KeePassX. There are numerous cross-platform password managers available (even one more in this round-up), but KeePass is simple and effective enough to get the job done.

KeePass is a free open source password manager, which helps you to manage your passwords in a secure way. You can put all your passwords in one database, which is locked with one master key or a key file.

14. Sobees Sobees

Sobee is one of those applications you’ll always love. It allows you to get the most out of your social sites. You can choose multiple layouts to display your social data, as it offers LinkedIn, Facebook, Twitter and MySpace support — even a New York Trending News widget. Be sure to check this one out!

Enjoy the convenience of tracking all your different social networks and news from a single place and share, like or tweet what’s on your mind easily.

15. Aptana Aptana

Aptana is, in my humble opinion, one of the best Integrated Development Enviroments (IDE) for Windows. It has great HTML, CSS, and JavaScript intellisense, JavaScript debugging tools, built-in support for JavaScript libraries, a DOM outline viewer, file transfer & synchronization, live previewing (Safari and Firefox), and much more.

Aptana Studio is the industry leading web development environment that combines powerful authoring tools for HTML, CSS, and JavaScript, along with thousands of additional plugins created by the community.

(Available for Linux and Mac)

16. Picasa Picasa

Picasa is a must have if you want to organize and share your photos on the internet. It’s light-weight, free, and just works!

Picasa is free photo editing software from Google that makes your pictures look great. Sharing your best photos with friends and family is as easy as pressing a button!

(Available for Linux and Mac)

17. Google Talk Gtalk

If you’re one of the GMail lovers (like me), then Gtalk is the perfect Gmail notifier for you. And of course, you can chat with your buddies as well!

Google Talk (GTalk) is a free-of-charge Windows web-based application for instant messaging and voice over internet protocol (VOIP), offered by Google Inc.

18. Adobe Photoshop CS5 Photoshop

Adobe Photoshop CS5 is, for obvious reasons, the greatest tool available for graphics / web design available in the industry. Photoshop is open on all of my computers… at all times.

Adobe Photoshop CS5 software is the ultimate solution for advanced digital imaging, delivering all the editing and compositing capabilities of Photoshop CS4, plus breakthrough tools that let you create and edit 3D and motion-based content.

19. Pidgin Pidgin

Pidgin is a simple instant messenger. I use it to chat with my friends and family, similar to Adium for the Mac. AIM, MSN, Yahoo, and Facebook are supported.

Pidgin is an easy to use and free chat client used by millions. Connect to AIM, MSN, Yahoo, and more chat networks all at once.

20. InstallPad InstallPad

Although I don’t use InstallPad every day, it’s still a great tool, and is worthy of being listed here. It helps you to install all of your favorite Windows applications at once.

InstallPad takes a list of your favorite programs and will download and install the ones you pick. It doesn’t need to ask any questions, so you can go do more important things. InstallPad can resume downloads you’ve canceled, and can even try and find the latest version of your program online.

Alternative 21. 1Password PC (Beta) 1Password

The hugely popular Mac password manager, 1Password, is currently in Beta mode for Windows! Whether you need to store hundreds of website passwords, or track your software licenses, 1Password will do the trick!

“1Password for Windows has been a dream of ours for a long time and we’re thrilled to open beta testing to everyone!”

Free Alternative 22. Bubbles Bubbles

Mac users have access to a nifty app, called Fluid, which allows them to turn any website (Mint.com, Producteev.com, etc) into a desktop app. It’s very helpful. PC offers its own version of this service, via an app, called Bubbles.

“Bubbles is an application platform, based on Browser technologies. It detaches Web Applications from the classic Browser and offers them with the familiar accessibility, capabilities and always-on nature of Desktop applications.”

Conclusion

These are the applications I use nearly every day on my PC. Did I miss any? Don’t agree with me? What do you recommend?

Categories: How-to's & Tutorials

Quick Tip: The Best Way to Run Internet Explorer on your Mac

Tue, 2010-07-20 17:57


While Mac users do have a handful of resources available, when viewing new web designs in Internet Explorer, the quickest solution is to use Wine, which can create a “wrapper” for the native PC Internet Explorer app! Even better, an app, called Wine Bottler makes adding the IE icon to your dock amazingly simple. I’ll show you what to do in today’s video quick tip!

Premium Members: Download this Video ( Must be logged in)

Subscribe to our YouTube page to watch all of the video tutorials!
Prefer to watch this video on Screenr?

Be sure to check out our sister-site, MacAppStorm for the full details on how to work with Wine and Wine Bottler!

Categories: How-to's & Tutorials

Creating Custom Fields for Attachments in WordPress

Tue, 2010-07-20 15:49


Custom fields in WordPress make it easy to customize your theme in a variety of ways; plus, they are simple to implement for posts and pages. Attachments, on the other hand, take a bit more work to implement, requiring you to read through and decipher core source code in order to make them work. We’ll be walking through the use of a couple undocumented WordPress hooks in this tutorial to make this process much easier.

Preface: About The Hooks

Both these hooks have been around since WordPress 2.5, and are applied in wp-admin/includes/media.php, but remain underused in the community most likely because they’re undocumented in the Codex. Below is where the hooks are applied in the core code, letting us know what will be passed to the functions we add to each hook.

attachment_fields_to_edit function get_attachment_fields_to_edit($post, $errors = null) { // ... $form_fields = apply_filters("attachment_fields_to_edit", $form_fields, $post); // ... }
  • $form_fields is a special array which will be described in detail in a moment.
  • $post is the attachment as an object (attachments are treated as post objects in WordPress).
attachment_fields_to_save function media_upload_form_handler() { // ... $post = apply_filters("attachment_fields_to_save", $post, $attachment); // ... }
  • $post is the attachment as an array (attachments are treated as post objects in WordPress).
  • $attachment is the attachment part of the form $_POST which will include the fields setup through the attachment_fields_to_edit hook.

Note: Be careful in your code, as $post is sent to one function as an object and to the other as an array.

Custom Field Naming Tips

The new fields being added will be saved as post meta, just like the custom fields section of the post/page edit screen. Fields prefixed with an underscore (_my_custom_field) will not be listed in the drop down of available custom fields on the post/page screen; all other existing post meta fields will be listed. We can use this knowledge to hide the fields we’re adding to the media form, since they aren’t relevant for posts/pages.

There is a similar rule to keep in mind when choosing the $form_fields array key to use for your new field. Here, if you use an underscore ($form_fields['_my_custom_field']) your field will be skipped and will not be added to the form.

So in order to show our fields in the media form, but also not list them in the page/post custom fields drop down, we must combine both methods. This will invlove both the edit and save functions we’ll be creating. For the ‘attachment_fields_to_edit‘ hook we’ll set the $form_fields keys up to not have underscore prefixes, and for the ‘attachment_fields_to_save‘ hook we’ll prefix our fields with an underscore before saving them as post meta. This is a workaround worth doing in order to not muddy our users’ interface with unneeded info.

Hook 1: attachment_fields_to_edit

Below is an example of how to add your own custom fields to the attachment form.

/** * Adding our custom fields to the $form_fields array * * @param array $form_fields * @param object $post * @return array */ function my_image_attachment_fields_to_edit($form_fields, $post) { // $form_fields is a special array of fields to include in the attachment form // $post is the attachment record in the database // $post->post_type == 'attachment' // (attachments are treated as posts in WordPress) // add our custom field to the $form_fields array // input type="text" name/id="attachments[$attachment->ID][custom1]" $form_fields["custom1"] = array( "label" => __("Custom Text Field"), "input" => "text", // this is default if "input" is omitted "value" => get_post_meta($post->ID, "_custom1", true) ); // if you will be adding error messages for your field, // then in order to not overwrite them, as they are pre-attached // to this array, you would need to set the field up like this: $form_fields["custom1"]["label"] = __("Custom Text Field"); $form_fields["custom1"]["input"] = "text"; $form_fields["custom1"]["value"] = get_post_meta($post->ID, "_custom1", true); return $form_fields; } // attach our function to the correct hook add_filter("attachment_fields_to_edit", "my_image_attachment_fields_to_edit", null, 2);

The $form_fields array has several options for including different types of inputs and custom content. I’ve compiled the various methods below with notes and screenshots of how they render in the form.

Text Input // input type="text" $form_fields["custom1"]["label"] = __("Custom Text Field"); $form_fields["custom1"]["input"] = "text"; // this is default if "input" is omitted $form_fields["custom1"]["value"] = get_post_meta($post->ID, "_custom1", true);

Renders in the form as:

Textarea // textarea $form_fields["custom2"]["label"] = __("Custom Textarea"); $form_fields["custom2"]["input"] = "textarea"; $form_fields["custom2"]["value"] = get_post_meta($post->ID, "_custom2", true);

Renders in the form as:

Hidden Field

Hidden fields are compiled together and output at the end of the form.

// input type="hidden" // no need for a label $form_fields["custom3"]["input"] = "hidden"; $form_fields["custom3"]["value"] = get_post_meta($post->ID, "_custom3", true); Other Field Types

If you need an input type other than ‘text’, ‘textarea’, or ‘hidden,’ then use ‘html’ which allows you to pass your own custom content to use for the input element of your choice. When you create your own input html, it’s important to set the ‘name’ attribute on the element correctly, in order for the field to be passed to our save function later. You want something like this: name = "attachments[$post->ID][my_custom_key]" .

$form_fields["custom4"]["label"] = __("Custom Select"); $form_fields["custom4"]["input"] = "html"; $form_fields["custom4"]["html"] = " <select name='attachments[{$post->ID}][custom4]' id='attachments[{$post->ID}][custom4]'> <option value='1'>Option 1</option> <option value='2'>Option 2</option> <option value='3'>Option 3</option> </select>"; // another example $form_fields["custom5"]["label"] = __("Custom Checkbox"); $form_fields["custom5"]["input"] = "html"; $form_fields["custom5"]["html"] = "the html output goes here, like a checkbox: <input type='checkbox' value='1' name='attachments[{$post->ID}][custom5]' id='attachments[{$post->ID}][custom5]' />";

Renders in the form as:

Special Attributes

There are several special attributes you can add to your custom fields to enhance them.

helps – This attribute adds a help string to your custom field.

$form_fields["custom6"]["label"] = __("Custom Field with Helpful Text"); $form_fields["custom6"]["value"] = get_post_meta($post->ID, "_custom6", true); $form_fields["custom6"]["helps"] = "Put helpful text here.";

This renders in the form as:

required – This attribute will mark the field as required; but it is only a visual reference. We’ll have to write code later in the save function to enforce it.

$form_fields["custom7"]["label"] = __("Required Field"); $form_fields["custom7"]["value"] = get_post_meta($post->ID, "_custom7", true); $form_fields["custom7"]["required"] = TRUE; // default is FALSE

Renders in the form as:

extra_rows – This attribute lets you add an array of rows right after your custom field. The markup for each array item is shown below: the array key will become the class of the td, and the value is the content:

// extra_rows markup: // <tr> // <td></td> // <td class="{arrayItemKey}">{arrayItemValue}</td> // </tr> $form_fields["custom8"]["label"] = __("Custom Field with Extra Rows"); $form_fields["custom8"]["value"] = get_post_meta($post->ID, "_custom8", true); // extra_rows must be an associative array $cssClass => $content $form_fields["custom8"]["extra_rows"] = array( "cssClass1" => "If you need a few rows after your field...", "cssClass2" => "...to maybe explain something or add some imagery? <img src='".get_bloginfo("wpurl")."/wp-admin/images/align-left.png' /> <img src='".get_bloginfo("wpurl")."/wp-admin/images/align-center.png' /> <img src='".get_bloginfo("wpurl")."/wp-admin/images/align-right.png' />", );

Renders in the form as:

tr – While extra_rows only lets you add table cells directly under your custom field’s input element, this attribute lets you create entire rows.

The table we’re adding a row to has two columns, so keep that in mind when using this method. And this doesn’t have to be a form field, you could just add a row that explains the next few fields, add all of your fields manually, or something else entirely.

$form_fields["custom8"]["tr"] = " <tr id='MySpecialRow'> <td colspan='2' style='background:#000;color:#fff;'> Can do whatever you want, style it, add some fields, display a table of data...sky's the limit </td> </tr>";

Renders in the form as:

Hook 2: attachment_fields_to_save

Saving your custom fields is a much simpler process than adding them to the form; just check if your field is set and update its value as post meta. Remeber to prefix your field with an underscore when saving to hide it on the post/page edit screen.

/** * @param array $post * @param array $attachment * @return array */ function my_image_attachment_fields_to_save($post, $attachment) { // $attachment part of the form $_POST ($_POST[attachments][postID]) // $post attachments wp post array - will be saved after returned // $post['post_type'] == 'attachment' if( isset($attachment['my_field']) ){ // update_post_meta(postID, meta_key, meta_value); update_post_meta($post['ID'], '_my_field', $attachment['my_field']); } return $post; }

You can also add errors here that will automatically be displayed below your field in the form. The $post['errors'] array gets merged with the $form_fields array before being sent through the attachment_fields_to_edit hook.

/** * @param array $post * @param array $attachment * @return array */ function my_image_attachment_fields_to_save($post, $attachment) { if( isset($attachment['my_field']) ){ if( trim($attachment['my_field']) == '' ){ // adding our custom error $post['errors']['my_field']['errors'][] = __('Error text here.'); }else{ update_post_meta($post['ID'], 'my_field', $attachment['my_field']); } } return $post; }

Note Regarding Custom Errors: There are a couple long standing bugs in WordPress (as of version 3.0-RC3) that have to do with the display of custom errors.

  1. One will prevent your custom error messages from showing up on the single media edit page.
  2. The other bug is in the modal popup for media items used on the post/page edit screen. The errors do display
    here, it’s just the problem of initially seeing them. After saving you’re automatically switched to the
    ‘Gallery’ tab where there’s a minimized list of media items. If you click on ‘show’ to open your new item,
    you’ll see your error messages in the form. The problem is that if there are errors, that items form is supposed to
    be open by default. There’s a bug in the css where the class ‘startopen’ (which is present on the item if
    there are errors to show) has the value of ‘display:none’ in a few places in the core stylesheets.

I have submitted patches for both of these issues (#13810 & #13838), and have been told they should be reviewed and included by version 3.1. So for now, don’t rely on your error messages too much, just be glad you know how to work with them for when they become more useful in the near future.

Other Ideas

You may want to include some of your fields on only audio attachments, or just images attached to the front page. To further customize your attachment forms, just wrap your special fields in distinguishing statements for both the edit and save functions.

// for audio files if( substr($post->post_mime_type, 0, 5) == 'audio' ){ // add your custom fields for audio files } // OR for images on a specific page $page_id = 5; // set the id to whatever page you want these applied to if( $post->post_parent == $page_id && substr($post->post_mime_type, 0, 5) == 'image' ){ // add your image specific custom fields for this particular page }

If you think of any clever ways to use custom fields with attachments, share it with us in the comments!

Categories: How-to's & Tutorials

Deciphering Magic Methods in PHP

Mon, 2010-07-19 07:05


PHP provides a number of ‘magic’ methods that allow you to do some pretty neat tricks in object oriented programming. These methods, identified by a two underscore prefix (__), function as interceptors that are automatically called when certain conditions are met. Magic methods provide some extremely useful functionality, and this tutorial will demonstrate each method’s use.

Before We Begin

In order to fully understand magic methods, it’s helpful to see them in action. So let’s start with a base set of very simple classes. Here we define two classes: Device and Battery.

<?php class Device { public $name; // the name of the device public $battery; // holds a Battery object public $data = array(); // stores misc. data in an array public $connection; // holds some connection resource protected function connect() { // connect to some external network $this->connection = 'resource'; echo $this->name . ' connected' . PHP_EOL; } protected function disconnect() { // safely disconnect from network $this->connection = null; echo $this->name . ' disconnected' . PHP_EOL; } } class Battery { private $charge = 0; public function setCharge($charge) { $charge = (int)$charge; if($charge < 0) { $charge = 0; } elseif($charge > 100) { $charge = 100; } $this->charge = $charge; } } ?>

If words like “method” and “property” sound alien to you, you might want to read up on this first.

Device objects will hold a name, a Battery object, an array of data, and a handle to some external resource. They also have methods for connecting and disconnecting the external resource. Battery objects simply store a charge in a private property and have a method to set the charge.

This tutorial assumes you have a basic understanding of object oriented programming. If words like “method” and “property” sound alien to you, you might want to read up on that first.

These classes are pretty useless, but they make a good example for each of the magic methods. So now that we have our simple classes created, we can try out the magic methods.

Constructors & Destructors

Constructors and destructors are called when an object is created and destroyed, respectively. An object is “destroyed” when there are no more references to it, either because the variable holding it was unset/reassigned or the script ended execution.

__construct()

The __construct() method is by far the most commonly used magic method. This is where you do any initialization you need when an object is created. You can define any number of arguments here, which will be passed when creating objects. Any return value will be passed through the new keyword. Any exceptions thrown in the constructor will halt object creation.

class Device { //... public function __construct(Battery $battery, $name) { // $battery can only be a valid Battery object $this->battery = $battery; $this->name = $name; // connect to the network $this->connect(); } //... }

Declaring the constructor method ‘private’ prevents external code from directly creating an object.

Here we have declared a constructor that accepts two arguments, a Battery and a name. The constructor assigns each of the properties that the objects requires to function and runs the connect() method. The constructor allows you to ensure that an object has all the required pieces before it can exist.

Tip: Declaring the constructor method ‘private’ prevents external code from directly creating an object. This is handy for creating singleton classes that restrict the number of objects that can exist.

With the above constructor in place, here is how you create a Device called ‘iMagic’:

$device = new Device(new Battery(), 'iMagic'); // iMagic connected echo $device->name; // iMagic

As you can see, arguments passed to the class are actually being passed to the constructor method. You can also tell that the connect method was called and the $name property was populated.

Let’s say we forget to pass a name. Here’s what happens:

$device = new Device(new Battery()); // Result: PHP Warning: Missing argument 2 for Device::__construct() __destruct()

As the name implies, the __destruct() method is called when the object is destroyed. It accepts no arguments and is commonly used to perform any cleanup operations such as closing a database connection. In our case, we’ll use it to disconnect from the network.

class Device { //... public function __destruct() { // disconnect from the network $this->disconnect(); echo $this->name . ' was destroyed' . PHP_EOL; } //... }

With the above destructor in place, here is what happens when a Device object is destroyed:

$device = new Device(new Battery(), 'iMagic'); // iMagic connected unset($device); // iMagic disconnected // iMagic was destroyed

Here, we’ve destroyed the object using unset(). Before it is destroyed, the destructor calls the disconnect() method and prints a message, which you can see in the comments.

Property Overloading

Note: PHP’s version of “overloading” is not quite the same as most other languages, though the same results can be reached.

This next set of magic methods are about dealing with property access, defining what happens when you try to access a property that does not exist (or is not accessible). They can be used to create pseudo properties. This is called overloading in PHP.

__get()

The __get() method is called when code attempts to access a property that is not accessible. It accepts one argument, which is the name of the property. It should return a value, which will be treated as the value of the property. Remember the $data property in our Device class? We’ll be storing these “pseudo properties” as elements in the data array, and we can let users of our class access them via __get(). Here’s what it looks like:

class Device { //... public function __get($name) { // check if the named key exists in our array if(array_key_exists($name, $this->data)) { // then return the value from the array return $this->data[$name]; } return null; } //... }

A popular use of the __get() method is to extend the access control by creating “read-only” properties. Take our Battery class, for example, which has a private property. We can allow the private $charge property to be read from outside code, but not changed. The code would look like this:

class Battery { private $charge = 0; public function __get($name) { if(isset($this->$name)) { return $this->$name; } return null; } //... }

In this example, note the use of variable variables to dynamically access a property. Assuming the value ‘user’ for $name, $this->$name translates to $this->user.

__set()

The __set() method is called when code attempts to change the value a property that is not accessible. It accepts two arguments, which are the name of the property and the value. Here’s what that looks like for the “pseudo variables” array in our Device class:

class Device { //... public function __set($name, $value) { // use the property name as the array key $this->data[$name] = $value; } //... } __isset()

The __isset() method is called when code calls isset() on a property that is not accessible. It accepts one argument, which is the name of the property. It should return a Boolean value representing the existence of a value. Again using our variable array, here’s what that looks like:

class Device { //... public function __isset($name) { // you could also use isset() here return array_key_exists($name, $this->data); } //... } __unset()

The __unset() method is called when code attempts to unset() a property that is not accessible. It accepts one argument, which is the name of the property. Here’s what ours looks like:

class Device { //... public function __unset($name) { // forward the unset() to our array element unset($this->data[$name]); } //... } Magic Properties in Action

Here are all of the property related magic methods we have declared:

class Device { //... public $data = array(); // stores misc. data in an array //... public function __get($name) { // check if the named key exists in our array if(array_key_exists($name, $this->data)) { // then return the value from the array return $this->data[$name]; } return null; } public function __set($name, $value) { // use the property name as the array key $this->data[$name] = $value; } public function __isset($name) { // you could also use isset() here return array_key_exists($name, $this->data); } public function __unset($name) { // forward the unset() to our array element unset($this->data[$name]); } //... }

With the above magic methods, here is what happens when we try to access a property called name. Remember that there isn’t really a $name property declared, though you’d never know that without seeing the internal class code.

$device->user = 'Steve'; echo $device->user; // Steve

We have set and successfully retrieved the value of a nonexistent property. Well where is it stored then?

print_r($device->data); /* Array ( [user] => Steve ) */

As you can see, the $data property now contains a ‘name’ element with our value.

var_dump(isset($device->user)); // bool(true)

Above is the result of calling isset() on the fake property.

unset($device->user); var_dump(isset($device->user)); // bool(false)

Above is the result of unsetting the fake property. Just to make sure, here is our empty data array:

print_r($device->data); /* Array ( ) */ Representing Objects As Text

Sometimes you might want to convert an object to a string representation. If you simply try to print an object we’ll get an error, such as the one below:

$device = new Device(new Battery(), 'iMagic'); echo $device; // Result : PHP Catchable fatal error: Object of class Device could not be converted to string __toString()

The __toString() method is called when code attempts to treat an object like a string. It accepts no arguments and should return a string. This allows us to define how the object will be represented. In our example, we’ll create a simple summary:

class Device { ... public function __toString() { // are we connected? $connected = (isset($this->connection)) ? 'connected' : 'disconnected'; // how much data do we have? $count = count($this->data); // put it all together return $this->name . ' is ' . $connected . ' with ' . $count . ' items in memory' . PHP_EOL; } ... }

With the above method defined, here is what happens when we try to print a Device object:

$device = new Device(new Battery(), 'iMagic'); echo $device; // iMagic is connected with 0 items in memory

The Device object is now represented by a short summary containing the name, status, and number of stored items.

Cloning Objects

Objects, by default, are passed around by reference. So assigning other variables to an object will not actually copy the object, it will simply create a new reference to the same object. In order to truly copy an object, we must use the clone keyword.

This ‘pass by reference’ policy also applies to objects within objects. Even if we clone an object, any child objects it happens to contain will not be cloned. So we would end up with two objects that share the same child object. Here’s an example that illustrates that:

$device = new Device(new Battery(), 'iMagic'); $device2 = clone $device; $device->battery->setCharge(65); echo $device2->battery->charge; // 65

Here, we have cloned a Device object. Remember that all Device objects contain a Battery object. To demonstrate that both clones of the Device share the same Battery, the change we made to $device’s Battery is reflected in $device2′s Battery.

__clone()

The __clone() method can be used to solve this problem. It is called on the copy of a cloned object after cloning takes place. This is where you can clone any child objects.

class Device { ... public function __clone() { // copy our Battery object $this->battery = clone $this->battery; } ... }

With this method declared, we can now be sure the cloned Devices each have their own Battery.

$device = new Device(new Battery(), 'iMagic'); $device2 = clone $device; $device->battery->setCharge(65); echo $device2->battery->charge; // 0

Changes to one Device’s Battery do not affect the other.

Object Serialization

Serialization is the process that converts any data into a string format. This can be used to store entire objects into a file or database. When you unserialize the stored data, you’ll have the original object exactly as it was before. One problem with serialization, though, is that not everything can be serialized, such as database connections. Fortunately there are some magic methods that allow us to handle this problem.

__sleep()

The __sleep() method is called when the serialize() function is called on the object. It accepts no arguments and should return an array of all properties that should be serialized. You can also complete any pending tasks or cleanup that may be necessary in this method.

Tip: Avoid doing anything destructive in __sleep() since this will affect the live object, and you may not always be done with it.

In our Device example, the connection property represents an external resource that cannot be serialized. So our __sleep() method simply returns an array of all the properties except $connection.

class Device { public $name; // the name of the device public $battery; // holds a Battery object public $data = array(); // stores misc. data in an array public $connection; // holds some connection resource //... public function __sleep() { // list the properties to save return array('name', 'battery', 'data'); } //... }

Our __sleep() simply returns a list of the names of properties that should be preserved.

__wakeup()

The __wakeup() method is called when the unserialize() function is called on the stored object. It accepts no arguments and does not need to return anything. Use it to reestablish any database connection or resource that was lost in serialization.

In our Device example, we simply need to reestablish our connection by calling our connect() method.

class Device { //... public function __wakeup() { // reconnect to the network $this->connect(); } //... } Method Overloading

These last two methods are for dealing with methods. This is the same concept as the property overloading methods (__get(), __set(), etc), but applied to methods.

__call()

The __call() is called when code attempts to call inaccessible or nonexistent methods. It accepts two arguments: the name of the called method and an array of arguments. You can use this information to call the same method in a child object, for example.

In the examples, note the use of the call_user_func_array() function. This function allows us to dynamically call a named function (or method) with the arguments stored in an array. The first argument identifies the function to call. In the case of naming methods, the first argument is an array containing a class name or object instance and the name of the property. The second argument is always an indexed array of arguments to pass.

In our example, we’ll be passing the method call to our $connection property (which we assume is an object). We’ll return the result of that straight back to the calling code.

class Device { //... public function __call($name, $arguments) { // make sure our child object has this method if(method_exists($this->connection, $name)) { // forward the call to our child object return call_user_func_array(array($this->connection, $name), $arguments); } return null; } //... }

The above method would be called if we try to call the iDontExist() method:

$device = new Device(new Battery(), 'iMagic'); $device->iDontExist(); // __call() forwards this to $device->connection->iDontExist() __callStatic() (PHP 5.3)

The __callStatic() (available as of PHP version 5.3) is identical to __call() except that it is called when code attempts to call inaccessible or nonexistent methods in a static context.

The only difference in our example is that we reference a class name instead of an object.

class Device { //... public function __callStatic($name, $arguments) { // make sure our class has this method if(method_exists('Connection', $name)) { // forward the static call to our class return call_user_func_array(array('Connection', $name), $arguments); } return null; } //... }

The above method would be called if we try to call the static iDontExist() method:

Device::iDontExist(); // __callStatic() forwards this to Connection::iDontExist() Bonus: __autoload()

This is not a magic method, but it is still very useful. The __autoload() function is automatically called when a class that doesn’t exist is referenced. It is meant to give you one last chance to load the file containing the class declaration before your script fails. This is useful since you don’t always want to load every class just in case you need it.

The function accepts one argument: the name of the referenced class. Say you have each class in a file named ‘classname.class.php’ in the ‘inc’ directory. Here is what your autoload would look like:

function __autoload($class_name) { $class_name = strtolower($class_name); include_once './inc/' . $class_name . '.class.php'; } Conclusion

Magic methods are extremely useful and provide powerful tools for developing flexible application frameworks. They bring PHP objects closer to those in other object oriented languages by allowing you to reproduce some of their more useful features. You can read the PHP manual pages on magic methods here. I hope this tutorial was helpful and clearly explained the concepts. If you have any questions, don’t hesitate to ask in the comments. Thanks for reading.

Categories: How-to's & Tutorials

Take Advantage of CSS3 to Achieve Subtle Design

Fri, 2010-07-16 06:46


I hear this CSS3 thing is all the rage. Resources are flying around the tutorial world and blogosphere providing brilliant examples of creative new ways to design using CSS3 modules. However, it’s easy to over-implement and lose the brilliant subtlety of great user interfaces. Here are three quick tips for using powerful CSS3 techniques in subtle ways.

Preface: It Doesn’t Take Much

People are able to perceive and distinguish very small changes.

The bottom line here is that people are able to perceive and distinguish very small changes that they may not consciously notice or be able to recall. I doubt that this is new information to anyone. It is one of the more well-known concepts put forth by sensation and perception studies. Sometimes, one thing may be pleasing over another. And sometimes, you don’t even know why.

However, keep in mind that web design is a conscious process. Subtle design can be difficult because it is easy to think “that just needs a little more.” Before you know it, the subtlety is lost.

With that in mind, I would like to present three CSS3 techniques that can be used to provide varying forms of subtlety for web design.

1. Transition

Transition is a powerful tool, providing a way for CSS to essentially animate from one endpoint to another. The syntax packs a fairly rich toolset: property, duration, and easing. Each of these pieces can be varied to provide different levels of subtlety. Often, it just takes playing – as effects often do. In other words, play with the values until it seems right. Just don’t drive yourself crazy. It’s easy to get lost tweaking even such a short list of variables.

Example: Color Transitions

It’s not uncommon for navigation items to change color when the mouse is hovering. Transition can make that color change a little smoother.

.nav li a{ color:#282828; text-decoration:none; -webkit-transition:color .1s ease-in-out; -moz-transition:color .1s ease-in-out; -o-transition:color .1s ease-in-out; transition:color .1s ease-in-out; } .nav li a:hover{ color:#808080; }

The color change is not subtle here. It’s clearly noticeable. What is subtle is the smoothing of that color change.

The trick to keeping this subtle is the duration. If it’s too long, the effect will be far too noticeable. The navigation can quickly become burdensome to hover over and look amateurish.

View the demo.

Notes about the CSS

In case you haven’t delved into CSS3 just yet, it’s important to note the order in which the browser-specific declarations come. Actually, it’s just important to notice that the non-browser specific declaration comes last in the list. CSS takes the last declaration and makes it more important in the case of a conflict. Once an actual transition spec is released, presumably all browsers will implement the module without needing the proprietary prefix. Thus, your CSS becomes somewhat future-ready at no real cost to the current implementations.

Also, notice that the transitions are in the <a> element style, not its hover. This will provide the transition both on mouse-over and mouse-off.

2. nth-of-type (or nth-child)

The nth-of-type or nth-child selector allows patterns to be declared in a series of elements and apply styles accordingly. For example, in a table, nth-child could color every other row by using :nth-child(odd). Let’s look at an example that may not be quite as clear.

Example: Grouping

We’ll take a pretty standard navigation markup…

<ul class='nav'> <li><a href='#'>Home</a></li> <li><a href='#'>About</a></li> <li><a href='#'>Work</a></li> <li><a href='#'>Forum</a></li> <li><a href='#'>Blog</a></li> </ul>

…and apply some styling.

.nav li:nth-of-type(odd){ margin-top:5px; } .nav li:nth-of-type(even){ margin-top:12px; } .nav li:nth-of-type(2n+2){ margin-right:0; } .nav li:nth-of-type(2n+3){ margin-left:8px; margin-right:25px; }

This will create a staggered-looking menu with a few high items, a few low items, and a couple sets that look paired. The visual difference between this and an in-line menu is clear.

So what’s so subtle about it? The subtlety here is twofold.

  1. The higher items look more important. Perhaps this person wanted to showcase his or her portfolio and blog. Those, along with the Home link, have been pushed up to be slightly more prominent. People’s eyes will be drawn to those links first.
  2. Notice the grouping. About and Work have been grouped together, as have Forum and Blog. This styling groups similar pages in its navigation. Work and About are both viewable things pertaining to the person while forum and blog are more audience-driven and interactive.

So, perhaps a visitor first sees “Home”. That visitor will probably realize that he or she is already on the homepage. He or she may very well see “Work” next. *click*. After viewing some pieces of work, they may well have seen “Blog” next but perhaps the grouping ends up being stronger and their desire is pulled to “About”. The designer is now driving the visitor using a navigational layout. He or she has provided hints as to where visitors should go, sequentially.

Will this happen every time? Absolutely not. Will it happen sometimes? I would bet so.

That’s the point of subtlety. It doesn’t overwhelmingly influence the user, but it might provide some useful hints or motivations now and then.

3. Gradients

Here’s a simple way to introduce subtlety into a design. Ironically, it’s probably got the most complicated syntax out there. Not only that, but it also has significantly different syntaxes between browsers. Let’s take a look.

Example: Forms

Given a pretty simple contact form (email, message), here’s some styling:

form input[type=text], form textarea{ background-image:-webkit-gradient( linear, left bottom, left top, color-stop(0, rgb(255,255,255)), color-stop(1, rgb(248,248,248)) ); background-image:-moz-linear-gradient( center bottom, rgb(255,255,255) 0%, rgb(248,248,248) 100% ); outline:none; border:solid 1px #ccc; }

That’s quite a full declaration, isn’t it? And that only covers two browsers!

I’m not going to go into all of the syntax, because others have done that for me. Refer to “Understanding CSS Gradients” on Nettuts+ for a better understanding. When you’re finished, let’s talk about subtlety.

The gradient in these text areas is almost imperceiveable. However, if you play with the CSS and take out the border, I assure you it is there.

If you still can’t see it in that second image, take your head and move it to the side of your monitor, so that you are viewing the monitor at a pretty steep angle. See it now? If not, I refuse to be held accountable. I see it, so your monitor must be broken. :)

Anyhow, notice how close the rgb colors are in the css. The top of the text input and textarea are shaded ever-so-slightly. This is one example of very extreme subtlety. While filling out a form, it is unlikely anyone will ever notice this gradient. However, people may find your form just a little more appealing than others; even if they don’t know why.

Bonus: Browser Incompatibility

Well, we’ve almost made it through and entire CSS3 article without discussing browser issues. How did we manage that? For one thing, there wasn’t a lot of emphasis on code. More importantly, though, I was saving the best for last.

Subtle changes probably won’t be missed

If you take a look at the demo for this tutorial in a webkit browser, then compare that to a Firefox browser, you will notice some differences. If you step over to IE, you’ll notice even further differences. One nice thing about the use of subtlety is that if the subtle difference isn’t there, people probably won’t notice. In other words, the color change in the first example still works without the transition; it’s just a little less slick. If the only purpose of using nth-of-type was to group based on commonality, no visitor is going to care if that grouping isn’t there. The menu still works. And the gradient? Remember how hard you had to try to notice it even when being told exactly where it was?

That last demo example will definitely be noticed…

Make it an opportunity for creativity, instead of an insurmountable burden.

Probably the most rational opposition to the “different looks in different browsers” approach to web design is that many (perhaps most) clients will want the exact same website in any major browser. If there is no room for budging on this and you need to pay your electric bill, do whatever you need to in order to get that all-important rounded corner into all IE versions back to the dawn of time.

However, some clients can be educated and swayed as to some advantages of having one design in one place and another somewhere else. For example, accepting a slightly different appearance can dramatically cut down on HTTP requests and excess HTML elements, if a lot of images are being used to create borders and shadows and whatnot. Or, if you’re anything like me, you have some personal projects and enjoy a good challenge (like providing the same “experience” cross browser without always having the same layout). Or, maybe you have two different designs that you really like and can’t decide which one to implement. Here’s an opportunity to implement one in one browser and the other in another, driven out of a single stylesheet.

The overall point here is that browser incompatibility is a fact of the current web when trying to utilize CSS3. So, make it an opportunity for creativity, instead of an insurmountable burden.

But what is subtle about that last demo example?

The subtlety here isn’t exactly a design subtlety. Instead, it’s more of a designer subtlety. In my experience, most people only use one browser. Web professionals forget that sometimes, as we install three versions of five different browsers on every machine we come across.

So, if an IE-only user happens across your site and its content is clear and he or she enjoys the experience, you have succeeded in your design. If another user happens across your site in Chrome and enjoys their experience and the content is clear, you have succeeded in your design. And perhaps that visitor appreciated a few extra tid-bits. Kudos. Most importantly, though, if you ever get the opportunity to sit down and watch this happen simultaneously, you will have succeeded in having some subtle fun.

Categories: How-to's & Tutorials

How To Be A Rockstar WordPress Designer: WordPress 3 Revision!

Thu, 2010-07-15 20:44


With the recent release of WordPress 3.0, Rockable Press has just released an updated version of How to be a Rockstar WordPress Designer by Collis Ta’eed and Harley Alexander.

The updated version is FREE for all those who have already purchased the first edition of the eBook. All they’ll need to do is use the email which provided them the link from when they first purchased the book, and follow the instructions included in the email on how to re-activate the link. Once that’s done they can then re-download their new version of the book.

If you don’t have a copy of the eBook yet don’t worry! Rockable is also offering a $10 Discount Voucher for all those who don’t have the book yet!

Rockable $10 Discount Code: WP3Launch – Expires Monday 26th July 2010

During the course of the book you’ll build THREE WordPress themes, a blog, a portfolio site and a general site with menus and submenus. Each theme demonstrates different aspects of WordPress theming and all three are packaged in with the book so you’ll have Photoshop, HTML, CSS and WordPress PHP files to refer to.

Join the Rockin’ List Today!

The Rockin’ List is our irregular mailout about new books and products, discounts and offers and Rockable news. Signing up to the mailing list will get you a free copy of the Rockstar Personal Branding minibook by Skellie

The Rockin’ Guarantee

Like all Rockable Books, this one comes with the 100% Moneyback Guarantee. If you’re not satisfied, we’re not satisfied.

Categories: How-to's & Tutorials