Archive for the ‘Programming’ Category

Incredible Services and Products

July 30th, 2010


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

Posted in Programming | Comments (0)

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

July 28th, 2010


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.


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?

Posted in Programming | Comments (0)

19 Important Features to Look for in a Web Host

July 24th, 2010


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.

Posted in Programming | Comments (0)

20+ Required Windows Apps: Web Designer’s Choice

July 22nd, 2010


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?

Posted in Programming | Comments (0)

Deciphering Magic Methods in PHP

July 20th, 2010


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.

Posted in Programming | Comments (0)

Take Advantage of CSS3 to Achieve Subtle Design

July 18th, 2010


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.

Posted in Programming | Comments (0)

Web Dev Q&A #2 – PHP Sessions, HTML5 Doctypes, and Form Styling

July 16th, 2010


We’re back with the second entry in the Nettuts+ Q&A series. Today, we discuss the difference between LESS and Sass, how to pass server-side values to your JavaScript, how to work with PHP and cookies, and the HTML5 doctype. Here we go!


1. LESS and Sass.

Hey Nettuts+. I’m confused. What’s the difference between LESS and Sass? Are they the same?

There are advantages to using both; however, the truth is: both will get the job done wonderfully. It mostly becomes a case of preference, when it comes to the syntax and such. In the past, many preferred LESS, because it had a more friendly CSS-like syntax, though, as of Sass 3, they have a new syntax, known as SCSS (Sassy CSS), which is simply a subset of CSS3′s syntax.

The Envato devs use Sass. Other popular developer prefer LESS. I’d equate it to comparing the 960 CSS framework to Blueprint. They’re both great; so make up your own mind. There are no wrong answers!

Want to learn more about LESS on Nettuts+?


2. Server-side to Client-side

I’ve been trying to figure out how to pass the value of a PHP variable to my JavaScript. How do I do this? Thanks!

The quickest and easiest solution is to echo your desired variable from within your JavaScript. For example, you could query your MySQL database with PHP, and then pass the returned value to your JavaScript by doing something along the lines of:

<?php $myvar = 'some value'; ?>
<!DOCTYPE html>

<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Tut</title>
</head>
<body>

<script>
	var myvar = '<?php echo $myvar;?>';
	alert(myvar); // some value
</script>
</body>
</html>

3. Custom Stylesheets with PHP

How can I choose a color scheme stylesheet for my website dynamically?

So you want to, for instance, choose red.css, or blue.css, and that would load a different color scheme for your website. Is that what you mean? There are certainly several ways to accomplish this task, and the correct choice will depend on if you’re using a framework, a CMS, MVC, etc. Let’s keep things simple, and as bare-bones as possible. We can use PHP sessions. First, we need to add a select box, for the user to choose their desired color stylesheet.

<!DOCTYPE html>

<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Tut</title>
</head>
<body>
<h2> Choose your Stylesheet </h2>
<form method="post" action="">
	<select name="colors">
		<option value="default">Default</option>
		<option value="red">Red</option>
		<option value="green">Green</option>
	</select>
	<input type="submit" name="submit" value="Go" />
</form>
</body>
</html>
Custom stylesheets with PHP

Next, with PHP, we’ll listen for if the page has posted back — or if the Submit button has been clicked. With a simple page like this, we can use the helpful $_SERVER['REQUEST_METHOD'].

The “Request Method” determines which request method was used to access the page: ‘GET’, ‘HEAD’, ‘POST’, ‘PUT’”

At the top of your page, add the following:

<?php

if ( $_SERVER['REQUEST_METHOD'] == "POST" ) {
  // page has posted back
}
else {
  // user hasn't submitted the form
}

?>
<!DOCTYPE html>

Since we can now confirm when the page has posted back, we can then create a session, and store the value of whatever the user chose from the select box.

<?php
session_start();
if ( $_SERVER['REQUEST_METHOD'] == "POST" ) {
	$_SESSION['color_scheme'] = $_POST['colors'];
}
else {
      $_SESSION['color_scheme'] = 'default';
}
?>

Here, we’re first creating a new PHP session, with session_start(). Next, we create a new key, with $_SESSION, called “color_scheme.” Feel free to name this how you wish. By default, we set this to “default” (see the “else” statement). This means that, if the user hasn’t selected a stylesheet, we’ll use the default one. However, if they did make a choice, we need to determine which option from the select element they chose, and store it in a Session key.

Returning to the mark-up, you’ll find that we applied a name of “colors” to the select element.

<select name="colors">
	<option value="default">Default</option>
	<option value="red">Red</option>
	<option value="green">Green</option>
</select>

When the page posts back, the selected value of this select element will be available to us, via $_POST['colors']. For example, if I choose the “green” option, $_POST['colors'] will then be equal to “green.”

Without sessions and cookies, there would be no way to “remember” this user-selected value. That’s why they’re essential in this case. Now that $_SESSION['color_scheme'] stores our desired value, we only need to load the appropriate stylesheet.

<head>
	<meta charset="utf-8">
	<title>Tut</title>
	<link rel="stylesheet" href="<?php echo $_SESSION['color_scheme'];?>.css" />
</head>

4. Rounded Form Elements

Hi Nettuts+! How do I create rounded form inputs with CSS for all browsers?

So you want stylized, rounded inputs in all browsers, including Internet Explorer? Okie dokie. Consider the following simple mark-up:

<form>
	<label for="name">Name: </label>
	<input type="text" name="name" />

	<input type="submit" value="Go" />
</form>
Base markup

Using some simple CSS3, we can create rounded corners for those inputs. Because some browsers got a headstart on the spec, we need to use the -moz and -webkit vendor prefixes, as well as the official version of the “border-radius” property.

<style>
	input {
		border: 1px solid #666;
		-moz-border-radius: 4px;
		-webkit-border-radius: 4px;
		border-radius: 4px;
	}

	input[type=submit] {
		-moz-border-radius: 25px;
		-webkit-border-radius: 25px;
		border-radius: 25px;
	}
</style>
  • -moz: Mozilla browsers (Firefox)
  • -webkit: Webkit browsers (Safari, Chrome)
Rounded corners

By specifying atype attribute of submit, that last snippet will only target submit buttons, and will style accordingly.

That Blasted IE

Unfortunately, as you probably guessed, Internet Explorer is a jerk. While the upcoming IE9 has support for border-radius (without a prefix), the older versions are still at a loss. At this point, you have two choices:

  1. Ignore it. The world won’t end if your readers see 90 degree angles.
  2. Image Fallback. You can target Internet Explorer specifically, and apply a rounded background image.

Modernizr

I’m assuming the asker of this question requires consistency; so we’ll go with the second option. Let’s assume that you’re going to be working heavily with CSS3 and HTML5 in your project. In that case, rather than using an IE-only stylesheet, why not have some fun, and use the helpful Modernizr library?

First, download Modernizr, and reference the modernizr.js file within your project.

<head>
	<meta charset="utf-8">
	<title>Tut</title>
	<script type="text/javascript" src="modernizr-1.5.min.js"></script>
</head>

Next, apply a class of no-js to the Html element on your page.

<html lang="en" class="no-js">

When you view your project in the browser, Modernizr will apply a long string of classes to the Html element, which specifies exactly what your browser is capable of. Note that, obviously, this list of classes will vary, depending upon the browser.

Modernizr

This is a huge help! Now we can use the “cascade” effect to only target the form elements that are children of the html element with a class of “no-borderradius,” and style accordingly.

If the browser does not support a particular feature, the word “no” will be prefixed to the rule.

/* Only targets browsers which don't support border-radius */
.no-borderradius input {
	background: url(path/to/rounded/background/image) no-repeat;
}

And then we relax and have cake.


5. Doctypes

I noticed that you always use the HTML5 doctype. Don’t you think that’s dangerous, when all browsers don’t yet support HTML5?

No, it’s not dangerous at all. For those unfamiliar with the wonderfully simple HTML5 doctype, it’s:

<!DOCTYPE html>

Seriously…that’s it. That’s all there is to it. No more multi-line spats of attributes; just a plain-ole DOCTYPE – as it should be. In older browsers, this doctype will trigger them into standards-mode. …And if you’re still worried, note that even Google uses it! Need more? John Resig was talking about this 2.5 years ago!

“What’s nice about this new DOCTYPE, especially, is that all current browsers (IE, FF, Opera, Safari) will look at it and switch the content into standards mode – even though they don’t implement HTML5. This means that you could start writing your web pages using HTML5 today and have them last for a very, very, long time.”
-John Resig


Read Previous Q&A’s


Ask Nettuts+…

If you have a “not-too-complicated” web development question for us, you can:

  1. Email net@tutsplus.com, and write “Web Dev Q&A” as the subject of the email.
  2. Tweet us @nettuts, and hash “#askNettuts”.
  3. Leave a comment under any “Web Dev Q&A” posting with your new question.

Thanks for reading and watching!

Posted in Programming | Comments (0)

Three Steps to Fostering a User-Centered Design Culture

July 14th, 2010


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.


Shattering False Idols

Anyone who’s worked as a web designer or developer for a sizable length of time has had a client say “Hey, I’ve got a great idea for a website; can you help me build it?” While their enthusiasm is wonderful, this question is typically loaded with preconceptions (read: misconceptions). The process for creating a website is never as straightforward as even we would hope it to be.

It is with these projects that we must be most careful—the ones where clients seem to know exactly what they want. They probably have a particular layout in mind, perhaps some specific functionality that should be included. But more often than not, these images of perfection give little-to-no consideration for the users that will actually visit and use the final work product. What can we do with such steadfast clients?


Step One: Introduce Design Thinking

As with any collaborative endeavor, it is particularly important to ensure that all members of the team are fighting for the same goal. The earlier this is done, the better.

In effect, we want to move clients away from subjective goals (“I want it to look cleaner.”), towards measurable, objective ones (“I want it so clean that sales increase by 20%.”). By asking a few straightforward questions, you’ll find the design that client’s require isn’t littered with nearly as many obstacles.

To start the ball rolling, have your client jot down five things he wants his website to do for him (don’t be surprised when not-a-one of them has to do with end users). Next, inform clients how their goals will affect your design and development process.

Consider, too, forming an experience strategy.

An experience strategy is a clear set of experiential goals used to add cohesion to design and development endeavors. It should answer some fundamental questions, such as: What’s our eventual experience goal? Should user’s love our site? Should they feel that we’re really really good at something in particular? How should they feel about feature [x]?

Lastly, get a development strategy put in place. In formulating such a strategy, the questions you’ll address include:

What research and development methodologies work best for this project? What deliverables are best for any given stage of this project?

Although these questions are simple, they’re extremely important.

1

Suggested Reading


Step Two: Replace Bad Habits with Good Ones

Before hopping into sketching interfaces and pushing pixels, we must first ask the ever-important question: what do users need?

Remember: without user research, design is meaningless. Make sure your client knows this, too.

So, how do we answer such a question? Well, with design research. That’s how.

But you, the experience designer, already know this. The important part is getting the client and/or organization with which you’re working to understand why design research is so important, especially considering that they probably have some pretty bad design habits in place already.

Back in the old days, websites were born from functional specs—cold, heartless documents outlining every functional aspect of the website. Needless to say, this took users out of the development equation.

Utilize prototyping methods (such as sketching or storyboarding) and employ user-testing to show your client what kind of feedback they can expect from their new website. Once you tell him he’ll be saving both time and money by building his website with the results from your research findings, he won’t ever miss his functional spec.

Remember: without user research, design is meaningless. Make sure your client knows this, too. Providing even rudimentary research findings can help everyone on the team make informed decisions as we move our design process forward.

2

Suggested Reading


Step Three: Share the Wealth

Experience design is both a visual and physical process, so it clearly benefits from collaboration. As a designer, you likely have lots of research, wireframes, personas, and other deliverables filed away for the projects on which you’re working. Take them out and share them with your colleagues.

Foster a fertile environment for design growth.

Listen to their feedback and provide your own. Foster a fertile environment for design growth. Storyboarding is a great tool, introduced at Adaptive Path, for this kind of collaboration. Once previous design deliverables have been shared and passed about, team members collectively pitch design solutions to advance towards the aforementioned end goal. The final storyboard is yet another fantastic tool to prompt further conversation later on in the process.

Regardless of the specific techniques or deliverables that you employ, collaboratively working on and sharing user-centered design deliverables helps facilitate a shared design understanding amongst your entire team.

3

Suggested Reading


Moving Forward

In this article, we’ve explored three simple steps that you can follow to blaze the user-centered trail at your organization. Don’t take them the wrong way: these steps do not constitute some kind of magical collection of UX incantations; instead, they are merely illustrative of the way forward.

By drawing your project team’s attention towards the following aspects of design and development, your organization is much more likely to think about its challenges in holistic, user-driven fashion. The rest, as they say, is up to you.


Posted in Programming | Comments (0)

Making Sense of Color Codes

July 10th, 2010


HTML color codes are a common and crucial piece of modern web design. While most sites nowadays are designed largely in part with images, colors are particularly important when you need to come up with a color hex value on the fly while coding. In this guide, we will learn the fundamentals behind color coding, ultimately providing you the power to come up with colors without the use of a color picker.


Introduction: Color Codes

As you may know, there are two common ways to define a color in web design:

  1. rgb(___,___,___)
  2. #_ _ _ _ _ _

Both of these are most often implemented using CSS or HTML, as you can review below:

Text Here
Text Here
.foo {color: rgb(111,222,111);}

In the first code example, each “Text Here” text would show up as a light grey color. We’ll go over why that is later on; however, notice how even though the color methods appear to be quite different, in actuality, they are the exact same color.

In the second example, we just have some quick CSS code. It’s pretty straightforward — anything with a class of “foo” will have a text color of rgb(111,222,111). For the more curious, that would be a lime green-ish color.

So far, most of this should make sense to you. Let’s now get into exactly how we go from those relatively cryptic codes into something a bit more concrete.


Exhibit A: RGB

In RGB, each value between the commas can be a number from 0 to 255. For example:

rgb(10,137,29)

Since RGB stands for “Red Green Blue,” this means that there is a value of 10 for red, 137 for green, and 29 for blue. Inevitably these are a kind of irreducible fraction. Thus:

  • the red would be 10/255 (ten out of
    a maximum value of 255)
  • the green would be 137/255 (137 out of a maximum of 255)
  • and 29/255 for blue.

The higher the number, the more of that certain color there will be in the final result.

When set to zero, there is none of that particular color. At 255, the opposite of course proves true. Therefore:

  • rgb(0,0,0) = black
  • rgb(255,255,255) = white

This holds true because the RGB color system is based on color through light. This is much different from how you would normally create colors, for example, with paint or crayons. If you had a combination of rgb(255,255,255) using paint, you’d probably come out with something like murky brown, but certainly not white!


Exhibit B: Hexadecimal

Hexadecimal color is generally more difficult to explain than RGB. Fundamentally, they are the same. However, hexadecimal’s inner workings are undoubtedly more convoluted.

To explain hexadecimal color, we’ll first have to fall back into some binary and into the base sixteen number system in order to understand what something like this is really trying to “say”:

#554BFF

For those of you who do not know how either of these work, or what either of them are, here is a brief guide:

Binary 101

  • Binary is composed entirely of zeroes & ones.
  • A zero yields a value of zero, and one yields a value of one; but not always.
  • A bit is either a 1 or a zero. 1 is a bit. 0 is a bit. But 01 is not a bit — it’s 2 bits. 10 is not a bit either, it’s 2 bits as well.
  • Let’s imagine that we have four bits; this is cleverly named a nibble, or half a byte. Instead of this number equaling two, or 11, or 110, or whatever you might be guessing, it’s actually much different.
  • As more bits accumulate, the value of each bit doubles.
  • As the first bit has a maximum value of one, and an alternative value of 0, the second bit can be 2 or 0, the third can be 4 or 0, the fourth can be 8 or 0, and so on and so forth.
  • Using this system, you can actually create any normal (base 10) number. Any number at all.
  • Note: The accumulated values add together, depending on whether they are a 1 or a 0. Additionally, you should note that binary reads, in most cases, from right to left.

If that was slightly confusing, I suggest reading over it again. If it still doesn’t make sense after that, that’s perfectly okay–the following examples will help bolster your understanding.

Wait – How Does this Relate to Color Codes?

Hexadecimal, as the name implies, provides sixteen usable “values” for a number to take on. As you might have noticed earlier, a “nibble” can give you any number from 0-15: sixteen values total!

Proof of Concept

Assuming we have the following:

1111

And knowing that the binary values of each bit will become as follows:

8 4 2 1

The binary value of 1111 will become:

8+4+2+1

which is…

15

Likewise, if the binary number had been 0000, the final outcome would have just been zero, because 0+0+0+0 equals 0.

One More Example

binary: 0101

The values for each bit are 8,4,2, and 1 (in order). Add together the binary values of the ones:

0+4+0+1

Equalling 5.

Hopefully those quick examples are helpful. I encourage you to try some others quickly by yourself. I’ll even give you one:

Convert from binary to decimal: 1010
Hint: It’s between 9 and 11.


This may feel like it’s going nowhere in relation to web development, but trust me, we’re almost there.

In hexadecimal, there are sixteen different representations for a binary sequence: 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E, and F. These, in turn, represent the numbers 0-15 (16 numbers total). Both of these represent the same binary number. But quickly — stop and think — #FFFFFF yields white, correct? And you can never have a letter higher than F in an HTML color code. Keep that in mind.

Binary, Decimal, and Hexadecimal Relationships

Here’s a quick chart that maps the relationship between binary, decimal, and hexadecimal:

Decimal|Hex|Binary

This means that, if you wanted to create the number 15, you could write F in hexadecimal, or 1111 in binary. Additionally, if you wanted to make, say, 10, you would write A in hexadecimal or 1010 in binary.


Applying Hexadecimal to Color Codes

Now, we’re a bit closer to figuring out exactly how hexadecimal works. Quickly, let’s imagine an example of an HTML color code being divided into three parts:

#006699 to -> #00,66,99

Now that looks a little familiar; if you’re thinking what I’m thinking, you’re right. Hexadecimal is organized exactly the same way as RGB: it has a value for each red, green, and blue. The core difference is:

  • RGB can take up to three characters in order to define a number from 0-255.
  • Hexadecimal, on the other hand, only requires two to make a value from 0-255. This is partly why hex is the more common way of using colors in web development — simply because it is easier to type, requiring fewer characters.

We’ll now look into how you can create a value up to 255, since so far we’ve only learned how to create numbers up to 15.

  • Let’s say we have a number, like 66. The catch here is that 66 is written in hexadecimal, not in regular numerics. Therefore, this will not equal 66, it will equal something different, something larger.
  • First, let’s convert this problem into binary. According to our handy chart above, 6 in binary is 0110. This means that 66, in binary, would be 0110 0110 (or 01100110, same thing).
  • Since binary reads from right to left, we’d decode the farthest right portion first. As we know, the first 0110 would equal 6.
  • Then, the left. Since there are two hexadecimal characters linked together to make “66″, the far left binary digits would equal something different, and definitely not 6 again. Once again, we would continue doubling the value of each bit.
  • From left to right, the values of each bit (with 8 bits [which is one byte!]) would be: 128, 64, 32, 16, 8, 4, 2, 1. So considering the bits for the left side have a much larger value, we’ll be getting a much larger number:
Binary: 0110
Bit values: 128  64  32  16
Add together all that are true: 0+64+32+0
Yields: 96

We’ve found that the first nibble on the right equals six. And now, we have found that the second nibble on the left equals 96. So, what do you do with these? Just add them! 96+6 = 102. Therefore, the hexadecimal value of 66 is 102 in the normal decimal system.

What this means is that, in hexadecimal, the RGB equivalent of 66 (in hex) is 102. Accordingly, #666666 is equal to rgb(102,102,102).

Let’s do one more hex to decimal conversion:

Hexadecimal: FF
Binary: 1111 1111
Bit values: 128  64  32  16  8  4  2  1
Add: 128+64+32+16+8+4+2+1
Yields: 255

255 is the maximum value for any color. So, if we had #FFFFFF, which we all know to be white, it would be rgb(255,255,255), which is white also.

For comprehension’s sake, let’s do one final conversion. This time, we’re going to convert an entire hexadecimal color to RGB. Our color is #6AB4FF.

6A
------
Binary: 0110 1010
Add: 64+32  +  8+2
	96+10
Yields: 106
------
B4
------
Binary: 1011 0100
Add: 128+32+16  +  4
	176+4
Yields: 180
------
FF
------
(We have already done this, so we know that it's 255)

Conclusion: #6AB4FF is equivalent to rgb(106,180,255).

Now, you may be wondering how we get from these values to an actual color we can envision in our head. The next section will help cover that. So, now that we know how hexadecimal and RGB are related, and now that we know how hexadecimal actually works, we’ll now review how you can come up with a color on the fly in your own code, and help you to make any color without ever needing to use a color picker.


True Color

Quick Fun Fact: Since there are 8 bits in each value of red, green, and blue, that means there are 24 bits total in one RGB color (8*3 = 24). This is where we get the term 24-bit color, often referred to as “True Color”.

With 24-bit color, we are capable of creating up to 16,777,216–over sixteen million–colors. This is typically more than satisfactory for any project. 32-bit color, however, has started to become more prominent, but not necessarily in the area of web design. You can read more about color depth at Wikipedia.org in this article. Additionally, you can view an image of all ~16 million colors in one image here (David Naylor Blog). It’s quite fascinating, really! The image sizes of 4096×4096 make sense since 4096 is the square root of 16,777,216.


Finally: Applications

In order for this knowledge to be of any use to us, you’re going to need to learn how to make your own colors quickly and easily. We’ll start off as simple as possible, and then move into more difficult-to-articulate colors.

Lesson Exploration #1

Let’s say we want to make a grey color on the fly. Greyscale colors are common, and tend to be the most useful in many cases. So far we know the following: #000000 equals black,
and #FFFFFF equals white. Therefore, the more common of the grayscale colors are going to be increments between those two values. To make a shade of gray, we’d appropriately establish values between white and black.

Logically, a value closer to #FFFFFF will be a lighter tone of grey, and a value closer to #000000 will be darker. With that in mind, let’s make a fairly light grey color. Some quick thinking gives us the following resolution: #DDDDDD is comfortably far enough away from white, so it clearly will be a nice light grey for us.

Later on, we want to make a darker grey. Yet again, simple. Just do something like #333333. As you can see, grey values are very simple. If you find that you need an even more specific shade of gray, remember that, as a general rule of thumb,
if each value for red, green, and blue are all the same, or are almost similar, it will appear as grey. One such example of this is the color “Gainsboro” which has a color code of #DCDCDC. This means that it’s just one less than our #DDDDDD color in each value of red, green, and blue. You’ll probably not be able to differentiate between the two, but incrementing or decrementing by 1 will give you a bit more “grey precision.”


#DDDDDD paired with its dark gray counterpart, #333333

Lesson Exploration #2

The second most simple set of colors you can create are red, green, and blue (obviously). Let’s use red as an example. If we want to create pure RGB red, we will give the color value
the maximum value of red, with 0 green, and 0 blue. That makes sense right? To make red in hexadecimal, we’d just put #FF0000. Now we’ve got red.

Creating green and blue follow the exact same principle. To make pure green: #00FF00 (all green, nothing else). To make pure blue: #0000FF (all blue, nothing else).

Simple enough; however, these colors are, under most circumstances, absolutely hideous when used in a web design. Therefore, to put these colors to use we’ll need to shade them accordingly.

Fortunately, shading is easy too. Let’s use blue for this example. We already have #0000FF set up for us. In order to change the shade of our blue value, we merely need to change the last two characters of the hexadecimal color code. Since FF is the highest blue possible, at this point we really can only make it darker. As such, let’s do just that:

Changing #0000FF to #000055 (decreasing the amount of black, thus moving the blue closer to black) will yield a darker blue.

As you can see, shading red, green, and blue is far from difficult–it’s a simple matter of decreasing the quantity of a certain color. The same rule applies to red and green, not just black, so #005500 is a darker shade of green, and #550000 is a darker shade of red. (Of course, you can go lower or higher than 55 if you wish).


Regular red, green, and blue, next to some darker versions of themselves.

Lesson Exploration #3

I suppose you are probably thinking: so what about yellow, purple, and all the other colors? Well, fortunately it’s just a little bit more complex than the big three of RGB. Let’s start with yellow.

To create yellow, we’ll first need to think in terms of the color spectrum. A little mnemonic that people like to use is “Roy G. Biv”, which stands for “red, orange, yellow, green, blue, indigo, violet. Now the logic in this is somewhat confusing, but try to stick with me. To get yellow, we use the two main colors from red, green, and blue on either side of where yellow would be. In this case, it would be red and green. Thus, if we wrote #FFFF00, we would have yellow. Fantastic!

There are only a few other possible combinations using this method, so we’ll go over them quickly. Between red and blue on a color wheel, the code would be #FF00FF, and we would get pink, or magenta as it is traditionally called, Next, between green and blue (#00FFFF), we have cyan. And now, sadly, that is actually all of the simple combinations we can do. The rest requires some thought, which we’ll go over in a minute. First, let’s figure out how to shade these colors.

Simply enough, we’ll start shading cyan this time, which, as we remember, is #00FFFF. And…you probably guessed it, but to shade yellow, cyan, or pink, all you have to do is change any FF values to a smaller one. In this example, shading cyan down to a much darker variety, we could do something like #005555. One of the official HTML color names, DarkCyan, is #008B8B, so that one would be a little lighter than the one we just created. So there we have it: how to shade yellow, cyan, and pink.


Yellow, magenta, and cyan next to their darkened versions

End Note on Shading

In order to make a color lighter, it’s as simple as making the low values (the 00 values, typically) greater and leaving the FF (or other main colors) alone. For example, if we had green, and we wanted to make it lighter, we would start out with #00FF00. Then, to lighten it, we would simply increase the 00 values. #AAFFAA produces a nice, spring color green.

Additionally, in order to make #FF00FF (Pink) lighter, it’s the same process. Increase the low values: #FFAAFF. This produces a light pink color. Works like a charm!


Our spring green and light pink colors.

Applications 2: Logically Creating and Decoding Colors

So far, we’ve learned how to create the most simple of colors, but in most applications, this knowledge will not be helpful for a project. That’s where this second part comes into play.

Creating a Custom Color

In order to create a nice looking color, we’ll need to work off of what we know already, and think through what we are trying to create in a logical manner. Let’s create a scenario; we want to make a subtle orange color that fits our needs — sort of like a slightly darker shade of orange soda.

We’ll start with what we already know how to make, and that’s yellow: #FFFF00. We need to move it a bit closer to the orange area, so to do so, we’d alleviate some of the green “pull,” as I like to call it. Doing so increases the amount of red. I chose to change it to #FF5500. This quick and simple example gives you an idea of how you would go about creating a color. The last thing I’d like to mention is that you might be wondering why I didn’t start adding to the blue quantity, which we left at a value of 00. The reason is because, when you start adding blue slowly in increments of 11, 22, 33, et cetera, it still looks fairly orange. However, once you get past 55, you’ll see some issues. Especially, if we increase it all the way up to something like #FF5599. What happens is that it turns into a really pink color. Why is this? Well think back to when we originally created pink. The code was #FF00FF. The red is maxed out and the blue is maxed out. So, in our orange color, when you start changing #FF5500 to #FF5599, our red and green values are no longer the prominent values. Instead, it’s red and blue, which yield pink. In this fashion, the 55 value for green would simply be lightening our shade of pink, instead of moving it towards the orange area.


Our orange color. It looks like orange soda, huh?

Note to reader: creating complex color codes, admittedly, is quite impractical. In the time it would take you to create a sufficient color, you could have easily gotten several good colors out of a color picker. For a complex color, it would be best not to try and create it yourself. Instead, just leave it to the tried-and-true, and save yourself precious time. You will, however, want to use your skills to perform a simple task like darkening or lightening a color quickly on the go.

Decoding a Color

So you see this lovely color code, staring you in the face, but you have no idea what color it really is. Great! This is probably where the most fun comes in. The best way to teach you how to do this is by performing a simple test. I was once asked the following few questions on a test in one of my Information Technology classes.

1. #000000 represents the color ____.

  1. green
  2. black
  3. white
  4. red

2. #00FF00 represents the color ___.

  1. green
  2. black
  3. red
  4. white

3. #FFCC66 represents a shade of ___.

  1. blue
  2. red
  3. purple
  4. gold

Hopefully you were able to figure all of these out! Especially the first two. You should have been able to figure out that the answer to number one was black, or B. For the second question, the answer was also quite simple. Following the scheme of red, green, blue, we know that since every value except for green is set to 00, that the color will be some shade of green. Additionally, since the value for green is FF (or 255), we know that this color will be pure green. Thus, the answer will be A.

It seems like the only difficult-to-decipher color here would be number three, #FFCC66. This is understandable. Since the blue value (which is 66) is so much smaller than the other two numbers, it could be deemed relatively irrelevant. Thus, you could compare it to the color for yellow, #FFFF00. Between those two, they look somewhat similar. With this method, you can tack out the first three answers, since none of them are remotely close to yellow. Therefore the answer is D. The decreased green value of CC will shade the color slightly, and the increase of blue will push the color into being much more similar to gold.


Regular red, green, and blue, next to some darker versions of themselves.

The process of decoding color codes primarily includes thinking through it and comparing it to colors you already know!


One Laster Pointer

Here is one last quick tip on how you can speed up creating a color using the hexadecimal system. Using this method, you can cut some color codes down from seven characters down to four (e.g. #_ _ _ _ _ _ to # _ _ _ ). This method is called color shorthand, and the idea behind it is that it will take the value of each of the three main characters, and duplicate them invisibly. What I mean by that is this: if you had the color code #123, it would be the equivalent of #112233. You can do this for any color code where each hexadecimal value for red, green, and blue is the exact same character. Some more common shorthands are:

  • #000 for black(#000000)
  • #fff for white (#ffffff)
  • #f00 for red (#ff0000)
  • #0f0 for green (#00ff00)
  • #00f for blue(#00f)

Conclusion

Hopefully this article helped you to learn about how color codes really work. In many programs, like Photoshop, it will admittedly be easiest to use the built in color pickers. The core area where this skill will come in handy is when you are looking through some CSS source code, and want to simply figure out what kind of color it is without having to resort to another resource. Regardless of which method is quicker, as web developers and designers, these are things we should want know! Thanks so much for reading. This is an understandably difficult topic, so let’s talk more in the comments!

Posted in Programming | Comments (0)

A Beginner’s Guide to Design Patterns

July 8th, 2010


Ever wondered what design patterns are? In this article, I’ll explain why design patterns are important, and will provide some examples, in PHP, of when and why they should be used.


What are Design Patterns?

Design patterns are optimized, reusable solutions to the programming problems that we encounter every day. A design pattern is not a class or a library that we can simply plug into our system; it’s much more than that. It is a template that has to be implemented in the correct situation. It’s not language-specific either. A good design pattern should be implementable in most—if not all—languages, depending on the capabilities of the language. Most importantly, any design pattern can be a double-edged sword— if implemented in the wrong place, it can be disastrous and create many problems for you. However, implemented in the right place, at the right time, it can be your savior.

There are three basic kinds of design patterns:

  • structural
  • creational
  • behavioral

Structural patterns generally deal with relationships between entities, making it easier for these entities to work together.

Creational patterns provide instantiation mechanisms, making it easier to create objects in a way that suits the situation.

Behavioral patterns are used in communications between entities and make it easier and more flexible for these entities to communicate.

Why should we use them?

Design patterns are, by principle, well-thought out solutions to programming problems. Many programmers have encountered these problems before, and have used these ‘solutions’ to remedy them. If you encounter these problems, why recreate a solution when you can use an already proven answer?

Example

Let’s imagine that you’ve been given the responsibility of creating a way to merge two classes which do two different things based on the situation. These two classes are heavily used by the existing system in different places, making it difficult to remove these two classes and change the existing code. To add to this, changing the existing code requires that you’ll also need to test any changed code, since these sorts of edits, in a system which relies on different components, almost always introduce new bugs. Instead of doing this, you can implement a variation of the strategy pattern and adapter pattern, which can easily handle these types of scenarios.

<?php
class StrategyAndAdapterExampleClass {
	private $_class_one;
	private $_class_two;
	private $_context;

	public function __construct( $context ) {
			$this->_context = $context;
	}

	public function operation1() {
		if( $this->_context == "context_for_class_one" ) {
			$this->_class_one->operation1_in_class_one_context();
		} else ( $this->_context == "context_for_class_two" ) {
			$this->_class_two->operation1_in_class_two_context();
		}
	}
}

Pretty simple, right? Now, let’s take a closer look at the strategy pattern.


Strategy Pattern

The strategy pattern is a behavioral design pattern that allows you to decide which course of action a program should take, based on a specific context during runtime. You encapsulate two different algorithms inside two classes, and decide at runtime which strategy you want to go with.

In our example above, the strategy is based on whatever the $context variable was at the time the class was instantiated. If you give it the context for class_one, it will use class_one, and vice versa.

Cute, but where can I use this?

Imagine that you’re currently developing a class which can either update or create a new user record. It still needs the same inputs (name, address, mobile number, etc.), but, depending on a given situation, it has to use different functions when updating and creating. Now, you could probably just use an if-else to accomplish this, however, what if you need to use this class in a different place? In that case, you’ll have to rewrite the same if-else statement all over again. Wouldn’t it be easier to just specify your context?

<?php
class User {

	public function CreateOrUpdate($name, $address, $mobile, $userid = null)
	{
		if( is_null($userid) ) {
			// it means the user doesn't exist yet, create a new record
		} else {
			// it means the user already exists, just update based on the given userid
		}
	}
}

Now, the “usual” strategy pattern involves encapsulating your algorithms inside another class, but in this case, another class would be wasteful. Remember that you don’t have to follow the template exactly. Variations work as long as the concept remains the same, and it solves the problem.


Adapter Pattern

The adapter pattern is a structural design pattern that allows you to repurpose a class with a different interface, allowing it to be used by a system which uses different calling methods.

This also lets you alter some of the inputs being received from the client class, making it into something compatible with the adaptee’s functions.

How can I use this?

Another term to reference an adapter class is a wrapper, which basically lets you “wrap” actions into a class and reuse these actions in the correct situations. A classic example might be when you’re creating a domain class for table classes. Instead of calling the different table classes and calling up their functions one by one, you could encapsulate all of these methods into one method using an adapter class. This would not only allow you to reuse whatever action you want, it also keeps you from having to rewrite the code if you need to use the same action in a different place.

Compare these two implementations.

Non-Adapter Approach

<?php
$user = new User();
$user->CreateOrUpdate( //inputs );

$profile = new Profile();
$profile->CreateOrUpdate( //inputs );

If we needed to do this again in a different place, or even reuse this code in a different project, we would have to type everything all over again.

Better

That’s opposed to doing something like this:

<?php
$account_domain = new Account();
$account_domain->NewAccount( //inputs );

In this situation, we have a wrapper class, which would be our Account domain class:

<?php
class Account()
{
	public function NewAccount( //inputs )
	{
		$user = new User();
		$user->CreateOrUpdate( //subset of inputs );

		$profile = new Profile();
		$profile->CreateOrUpdate( //subset of inputs );
	}
}

This way, you can use your Account domain again whenever you need it—plus, you’d be able to wrap other classes under your domain class as well.


Factory Method Pattern

The factory method pattern is a creational design pattern which does exactly as it sounds: it’s a class that acts as a factory of object instances.

The main goal of this pattern is to encapsulate the creational procedure that may span different classes into one single function. By providing the correct context to the factory method, it will be able to return the correct object.

When can I use this?

The best time to use the factory method pattern is when you have multiple different variations of a single entity. Let’s say you have a button class; this class has different variations, such as ImageButton, InputButton and FlashButton. Depending on the place, you may need to create different buttons—this is where you can use a factory to create the buttons for you!

Let’s begin by creating our three classes:

<?php
abstract class Button {
	protected $_html;

	public function getHtml()
	{
		return $this->_html;
	}
}

class ImageButton extends Button {
	protected $_html = "..."; //This should be whatever HTML you want for your image-based button
}

class InputButton extends Button {
	protected $_html = "..."; //This should be whatever HTML you want for your normal button (<input type="button"... />);
}

class FlashButton extends Button {
	protected $_html = "..."; //This should be whatever HTML you want for your flash-based button
}

Now, we can create our factory class:

<?php
class ButtonFactory
{
    public static function createButton($type)
    {
        $baseClass = 'Button';
        $targetClass = ucfirst($type).$baseClass;

        if (class_exists($targetClass) && is_subclass_of($targetClass, $baseClass)) {
            return new $targetClass;
		} else {
            throw new Exception("The button type '$type' is not recognized.");
		}
    }
}

We can use this code like so:

$buttons = array('image','input','flash');
foreach($buttons as $b) {
    echo ButtonFactory::createButton($b)->getHtml()
}

The output should be the HTML of all your button types. This way, you would be able to specify which button to create depending on the situation and reuse the condition as well.


Decorator Pattern

The decorator pattern is a structural design pattern which enables us to add new or additional behavior to an object during runtime, depending on the situation.

The goal is to make it so that the extended functions can be applied to one specific instance, and, at the same time, still be able to create an original instance that doesn’t have the new functions. It also allows for combining multiple decorators for one instance, so that you’re not stuck with one decorator for each instance. This pattern is an alternative to subclassing, which refers to creating a class that inherits functionality from a parent class. As opposed to subclassing, which adds the behavior at compile time, “decorating” allows you to add new behavior during runtime, if the situation calls for it.

To implement the decorator pattern, we can follow these steps:

  1. Subclass the original “Component” class into a “Decorator” class
  2. In the Decorator class, add a Component pointer as a field
  3. Pass a Component to the Decorator constructor to initialize the Component pointer
  4. In the Decorator class, redirect all “Component” methods to the “Component” pointer, and
  5. In the Decorator class, override any Component method(s) whose behavior needs to be modified

Steps courtesy of http://en.wikipedia.org/wiki/Decorator_pattern

When can I use this?

The best place to use the decorator pattern is when you have an entity which needs to have new behavior only if the situation requires it. Let’s say you have an HTML link element, a logout link, that you want to do slightly different things to based on the current page. For that, we can use the decorator pattern.

First, let’s establish the different “decorations” we’ll need.

  • If we’re on the home page and logged in, have this link be wrapped in h2 tags
  • If we’re on a different page and logged in, have this link be wrapped in underline tags
  • If we’re logged in, have this link wrapped in strong tags

Once we’ve established our decorations, we can start programming them.

<?php
class HtmlLinks {
	//some methods which is available to all html links
}

class LogoutLink extends HtmlLinks {
	protected $_html;

	public function __construct() {
		$this->_html = "<a href=\"logout.php\">Logout</a>";
	}

	public function setHtml($html)
	{
		$this->_html = $html;
	}

	public function render()
	{
		echo $this->_html;
	}
}

class LogoutLinkH2Decorator extends HtmlLinks {
	protected $_logout_link;

	public function __construct( $logout_link )
	{
		$this->_logout_link = $logout_link;
		$this->setHtml("<h2>" . $this->_html . "</h2>");
	}

	public function __call( $name, $args )
	{
		$this->_logout_link->$name($args[0]);
	}
}

class LogoutLinkUnderlineDecorator extends HtmlLinks {
	protected $_logout_link;

	public function __construct( $logout_link )
	{
		$this->_logout_link = $logout_link;
		$this->setHtml("<u>" . $this->_html . "</u>");
	}

	public function __call( $name, $args )
	{
		$this->_logout_link->$name($args[0]);
	}
}

class LogoutLinkStrongDecorator extends HtmlLinks {
	protected $_logout_link;

	public function __construct( $logout_link )
	{
		$this->_logout_link = $logout_link;
		$this->setHtml("<strong>" . $this->_html . "</strong>");
	}

	public function __call( $name, $args )
	{
		$this->_logout_link->$name($args[0]);
	}
}

We should then be able to use it like so:

$logout_link = new LogoutLink();

if( $is_logged_in ) {
	$logout_link = new LogoutLinkStrongDecorator($logout_link);
}

if( $in_home_page ) {
	$logout_link = new LogoutLinkH2Decorator($logout_link);
} else {
	$logout_link = new LogoutLinkUnderlineDecorator($logout_link);
}
$logout_link->render();

We can see here how we are able to combine multiple decorators if we need them. Since all the decorators use the __call magic function, we can still call the original function’s methods. If we assume that we are currently inside the home page and logged in, the HTML output should be:

<strong><h2><a href="logout.php">Logout</a></h2></strong>

Singleton Pattern

The singleton design pattern is a creational design pattern which makes sure that you have one single instance of a particular class in the duration of your runtime, and provides a global point of access to the single instance.

This makes it easier to set up a point of “coordination” for other objects that use the singleton instance as well, since the singleton’s variables will always be the same for anything that calls it.

When can I use this?

If you need to pass a specific instance from one class to another, you can use the singleton pattern to avoid having to pass the instance via constructor or argument. Imagine that you have created a Session class, which simulates the $_SESSION global array. Since this class will only need to be instantiated once, we can implement a singleton pattern like so:

<?php
class Session
{
	private static $instance;

	public static function getInstance()
	{
		if( is_null(self::$instance) ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	private function __construct() { }

	private function __clone() { }

	//  any other session methods we might use
	...
	...
	...
}

// get a session instance
$session = Session::getInstance();

By doing this, we can access our session instance from different parts of our code, even in different classes. This data will persist throughout all getInstance calls.


Conclusion

There are many more design patterns to study; in this article, I’ve only highlighted some of the more prominent ones that I use when programming. If you’re interested in reading about the other design patterns, Wikipedia’s Design Patterns page has a plethora of information. If that’s not enough, you can always check out Design Patterns: Elements of Reusable Object-Oriented Software, which is considered to be one of the best design pattern books available.

One last thing: when you use these design patterns, always make sure that you’re trying to solve the correct problem. As I mentioned previously, these design patterns are a double-edge sword: if used in the wrong context, they can potentially makes things worse; but if used correctly, they become indispensable.

Posted in Programming | Comments (0)