19 Important Features to Look for in a Web Host

July 24th, 2010
by Programmers.biz Admin


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)

PHP developer in India- Enhances Online business Revenues through CMS and CRM

July 22nd, 2010
by Programmers.biz Admin

Internet is a highly competitive place for the online businesses. Millions of websites compete with each other for top page rankings to gain greater visibility on the net. Better online visibility enh…

Posted in Programming Articles | Comments (0)

Make Your Website Impressive Via a CPA Accountant Web Developer

July 22nd, 2010
by Programmers.biz Admin

The modern world of the Internet is full of new creations and surprises. People keep adopting different ways to make their web sites look more impressive and user friendly. Whatever services we enjoy on websites are generally provided by database web applications. Now, there have been dramatic changes in the marketing techniques employed by CPA accountants also. One of the greatest changes is the use of the Internet and user friendly websites.

Posted in Programming Articles | Comments (0)

20+ Required Windows Apps: Web Designer’s Choice

July 22nd, 2010
by Programmers.biz Admin


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)

10 Mistakes Developers at a Web Development Company Should Avoid

July 20th, 2010
by Programmers.biz Admin

Why it happens that some websites look and feel really good while some lack the same look and feel. The answer is simple how well a website looks and feels depends to a large extent on the web develop…

Posted in Programming Articles | Comments (0)

3 Obstacles to Going Into DotNET Application Development

July 20th, 2010
by Programmers.biz Admin

Have you considered getting into .NET application development? Here are 3 obstacles that you will need to overcome to be successful.

Posted in Programming Articles | Comments (0)

Deciphering Magic Methods in PHP

July 20th, 2010
by Programmers.biz Admin


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)

Ecommerce Web Solution for Improving Your Sales and Profits

July 18th, 2010
by Programmers.biz Admin

Whether it’s hosting solutions and commerce, SQL database or custom design development, searching for a company that can handle all well is an intricate task, but proves out to be worthy in the end…

Posted in Programming Articles | Comments (0)

If You Are Struggling to Build Websites Or Just Want to Make a Few Extra Dollars Online, Read This!

July 18th, 2010
by Programmers.biz Admin

Not everyone is able to adopt the whole internet marketing mindset and most people struggle to build their websites and often cant make a few extra dollars online. Maybe that is why more than 90% of internet marketers have dormant ClickBank accounts that are just collecting cyber dust, accounts that have money in them, but due to the fact that ClickBank requires you to make a minimum of 5 sales before you can receive your first paycheck - Many newbie affiliates NEVER make any money at all.

Posted in Programming Articles | Comments (0)

Take Advantage of CSS3 to Achieve Subtle Design

July 18th, 2010
by Programmers.biz Admin


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)