Archive for April, 2010

« Older Entries |

Create an AJAX/jQuery/PHP Contact Form

Friday, April 30th, 2010

This tutorial uses XHTML, CSS, jQuery and a little PHP to make a pop-up/modal contact form that validates whatever is entered into the form and then uses AJAX to send the form without refreshing the page. Sounds complicated…actually it’s very simple!!

The code of this tutorial has been updated

The HTML Markup

The HTML layout of the contact form is very simple. You have your ‘normal’ webpage, whatever that may be. Somewhere within your website you’ll have a link with a class of modal.

The contact form requires two specific divs. Firstly a div with an id of #contact; and secondly an empty div with an id #mask.

All of the contact form, the alert boxes, the close link etc. go inside the #contact div. The form layout is simple: two text inputs, one textarea and one submit button (we’ll come back to this in the PHP section). These can be preloaded with values such as “Your name” which can be cleared for the user by setting the Javascript functions onFocus or onClick.

The #mask div must be empty. Although an empty div is not recommended practise, it’s a technique which works will for modal windows.

The modal window markup is based on this blog post from queness.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

<title>TutToaster AJAX Contact Form</title>

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />

<link rel="stylesheet" href="css/reset.css" type="text/css" />
<link rel="stylesheet" href="css/master.css" type="text/css" />

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="contact.js"></script>

</head>

<body>

<div id="container">

<h1>This is a web page</h1>

<p>This is the main body.</p>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur in lacus vitae tortor vehicula cursus a pretium odio. Suspendisse potenti. Phasellus semper nisl a massa vulputate at vulputate justo tempor. Quisque vel enim aliquam risus varius aliquam iaculis non odio. Pellentesque molestie, lorem vitae vestibulum porta, elit eros fringilla nunc, cursus ultricies nisi neque sed ipsum. Nam enim nisl, gravida sed consequat non, faucibus eget massa. Nullam pulvinar, diam et eleifend viverra, purus sem pellentesque sem, non tempor ante neque eu dolor. Quisque adipiscing, tortor ac feugiat feugiat, enim mi porttitor nunc, in bibendum diam sem eu leo. Morbi gravida, leo ut auctor cursus, urna nulla viverra eros, vitae dictum arcu quam sed odio. Proin eleifend urna a justo suscipit vehicula. Pellentesque vitae elit eros. Nulla vehicula velit nec dui vulputate viverra. Curabitur non dolor ac velit semper faucibus vel eget dolor.</p>

<p>A <a class="modal" href="#">contact link</a>.</p>

</div><!--end container-->

<!--contact form-->

<div id="contact">
	<div id="close">Close</div>

	<div id="contact_header">Contact</div>
	<p class="success">Thanks! Your message has been sent.</p>

  <form action="send.php" method="post" name="contactForm" id="contactForm">
  <p><input name="name" id="name" type="text" size="30" value="Your Name" /></p>
  <p><input name="email" id="email" type="text" size="30" value="Your Email Address" /></p>
  <p><textarea name="comment" id="comment" rows="5" cols="40">Enter your comment or query...</textarea></p>
  <p><input type="submit" id="submit" name="submit" value="Send" /></p>
 </form>
</div>

<div id="mask"></div>

<!--end contact form-->

</body>
</html>

Tags: , , , , , , , , , ,
Posted in Tutorials | 55 Comments »

15 Inspiring Vintage and Retro Web Designs

Wednesday, April 28th, 2010

Retro and Vintage Elements in Web Design are becoming more and more popular. Personally, I’m a big fan of vintage web design. I find it to be one of the most inspiring and appealing design styles out there and it’s a style that can definitely draw attention to a website if designed correctly. That said though, there is no Right or Wrong way to design a Retro / Vintage styled web site and as you’ll see below there are a few varied styles.

I have rounded up a selection of what I feel are the 15 most inspiring vintage and retro web designs to showcase.

Let us know which is your favourite design of the 15 that have been showcased and feel free to share some examples of vintage / retro web design that you feel are very inspiring and haven’t been featured.

All Star Lanes

All Star Lanes | Vintage / Retro Web Design

Anitique Piano Shop

Antique Piano Shop | Vintage / Retro Web Design

Brewery Lane

Brewery Lane | Vintage / Retro Web Design

Bullet PR

Bullet PR | Vintage / Retro Web Design

the Dollar Dreadful

The Dollar Dreadful | Vintage / Retro Web Design

Lather Bee Rich

Lather Bee Rich | Vintage / Retro Web Design

Michela Chiucini

Michela Chiucini | Vintage / Retro Web Design

Team Fannypack

Team Fannypack | Vintage / Retro Web Design

the New York Moon

the New York Moon | Vintage / Retro Web Design

Tomatic

Tomatic | Vintage / Retro Web Design

DNA to Darwin

DNA to Darwin | Vintage / Retro Web Design

Mom & Popcorn

Mom & Popcorn | Vintage / Retro Web Design

Ready Photosite

Ready Photosite | Vintage / Retro Web Design

I Am Todd

I Am Todd | Vintage / Retro Web Design

Lord Likeley

Lord Likeley | Vintage / Retro Web Design

Conclusion

As you can see there are quite a few varied styles of Vintage and Retro Web Design. Yet, they all have a unique vintage feel to them and each one has been designed with a lot of attention to detail.

For me, it’s the attention to detail that makes them so inspiring. What do you think?

Become successful web designer with test king online web designing course. Learn how to create inspiring web designs with testking 000-104 tutorials and testking 000-201 guide.

Tags: , , , , , , , , ,
Posted in Inspiration | 6 Comments »

Create a Cool Mask Transition Slideshow: Part 2

Monday, April 26th, 2010

Hope You’ll enjoyed part 1 of our Create a Cool Mask Transition Slideshow mini series,  it’s time to Move on with part 2, we are going to implement the effect by creating a jQuery plugin!

Tutorial Structure –

Setting up workspace for the plugin.

Before we can move forward, there are few things we need to look at.

How slideshow works ?

Basically every slideshow has a mechanism to iterate each image to front after an effect like fade is over. So in our plugin we will create a function that pushes each image to the front. Since images are stacked up, we will alter the z-index property of each li element to push the images to the front.

You may be wandering that we should be altering the z-index of the images not the list items, this is because if we had only images we could have done that but since we also have image description along each image so we will iterate the whole li element.

Concept behind the transition –

Since it is a mask transition, the main concept is put an element infront of the fading square, then fade out the square to give the masking effect. So what we are going to do is create an array of square divs of smaller size with the topmost image as the background image. We will adjust the background position of each div so that the the whole array of divs looks like same as the top image itself.

Then finally we will randomly choose a div, insert a div with a white background (you can choose yourself) at the current div position and when the mask div appears on top of the current div, we will remove the current div and fadeOut the mask div. We will repeat this procedure for all the divs available. Kinda of tricky, don’t worry when we will code the function you will get the point more easily.

HTML structure for usage

In the first part, we had created a structure for our slideshow, all the images and their correspond description were wrapped inside an unordered list. Which was then wrapped inside two divs. We will keep that in mind and create the plugin to handle them.

The CSS part –

Before we can start coding our plugin, we will style our slideshow a bit. All the images need to be at the top of each other, so we can iterate them later. So we will absolute position the elements and hide unnecessary area besides the length and width of the slideshow.

.active { position:absolute;z-index:10; } /* Class for element at top  */
.reset{ position:absolute;z-index:4;  } /* Class for the rest of the elements  */

#jMask-stage ul { list-style:none; display:block; margin:0px; padding:0px; float:left; }
#jMask-stage ul li { position:absolute; display:block; overflow:hidden;  }
#jMask-stage ul img { position:absolute;  }

Here we have styled all the elements within the scope of jMask-stage to avoid conflict with other elements of the page. We will wrap the ul later with jMask-stage.

Here .active class represents the image at the top of the slideshow and reset represents the images behind the main image.

Make sure that you have resetted the margin and padding of the elements to avoid unecessary gaps in the slideshow.

Step 1 – Creating the initial structure

We will start off by creating a basic plugin for jquery and wrap it in a function to prevent conflict with other plugins.

(function($) {

$.fn.jMask = function(options){

 };

		  })(jQuery);

Step 2 – Plugin options

A plugin should have lots of options to make it flexible as possible, here we will use 6 options.

(function($) {

$.fn.jMask = function(options){
	var defaults = {time:7000,width:600,height:500,bg:'#ffffff',border:'1px solid #ffffff',callback:function(){  } };
	var options = $.extend(defaults, options);
 };

		  })(jQuery);

Step 3 – Precaching variables.

It is a good practice to limit the use of $ and store the variables commonly used. Also when creating a plugin, it is best to wrap the widget in a div with plugin’s name as id to avoid conflict( Since we already have a div here so we will change it’s id).

var root = $(this);
var ul = root.find("ul:first");
var li = ul.find("li");
var images = li.find("img");
root.find("div").attr("id","jMask-stage");

Step 4 – Modularizing the plugin.

It is a good practice to modularize the plugin, so that in the future if upgrade is necessary only the required module can be changed without altering the whole plugin. We will be needing the following modules for our current plugin.

Step 5 – Declaring variables to be used in the plugin.

Now we will declare variables that we will use in the plugin.

var list_array = $.makeArray(li);
var image_timer,arr,index,block,w,h,src,parent,im;

li.css({"width":options.width,height:options.height,display:"block"});
$("#jMask-stage").css({"width":options.width,height:options.height});
$(list_array[list_array.length-1]).find("span , h1,p").show();

Here we have converted the li items into an array so that we can use them in the increment (flipping images) module. Finally we will set the height and width parameters of the slideshow and show the image description of the last image.

You should note that we are showing the image description of last image because our slideshow starts from last image and goes anticlockwise.

Step 6 – Creating an increment function

Every slideshow needs a mechanism to flip the images after any effect. The basics of this is by changing the z-index of each images, after each transition. So here we are going to create a incrementz function which flips the li items.

function incrementz()
 {

	var th,sr,temp =  list_array.pop();
	list_array.unshift(temp);
	if($(list_array[0]).hasClass('active'))
		$(list_array[0]).toggleClass('active reset');
		$(list_array[0]).find("span , h1,p").hide();
		$("#ribbon-left").hide();

		$(list_array[list_array.length-1]).toggleClass('active reset');
			$(list_array[list_array.length-1]).find("span , h1,p").show();
			$("#ribbon-left").show();
		$(list_array[list_array.length-2].firstChild).css({display:"block",opacity:1.0});
		$(list_array[list_array.length-1].firstChild).css({display:"block",opacity:1.0});

	options.callback(list_array[list_array.length-1].firstChild);
 };

Here what we are doing is that since we start from the last li, after each transition we will pop the item and insert it in the first place. Now the first item will be always the one, on which effect has been done and last element of the array will be the item coming next. So we will remove active class of the first item and add it to the last item. This way each element iterates through the array as well as in the slideshow. Finally we will make sure the images that are gone after effect are visible. We will also call the callback with the current image(last one) as parameter.

Step 7 – Creating the actual effect.

Now we will create the actual effect. Since we have seen how the transition works, now we will implement the logic.

Here first we will get the reference of the image in the im variable, then we calculate the width and height of the squares which are relative to the dimensions of the slideshow. You can give them absolute values. After that we have create a div block with top image as the background image. Then we will create our mask div and then insert the array of divs in the images’s parent while constantly changing their background position.

 function cubeout(image)
	{
		 im = $(image);
		 w = Math.floor(options.width/7);
		 h = Math.floor(options.width/7);
		 parent = im.parent();
		 arr = new Array();
		 i =0;
		 j =0;
		 var index = 0;
		 src = im.attr("src");
		 block = $("
<div>",{
					css:{
						position:"absolute",
						width:w,
						height:h,
						'background-image':'url('+src+')',
						'background-color':options.bg,
						'border':options.border

						}

							});
		 var temp,mask = block.clone();
		 mask.css({'background-image':'',display:"none"});
		 while(i<options.width)
		 {

		    j=0;
			while(j<options.height)
			{

				arr[index] = block.clone().css({left:i ,top:j,backgroundPosition:-i+"px "+-j+"px" });
				parent.append(arr[index++]);
			j = j + h;
			}

			i = i + w;
		 }

      }

Now we are going to append the mask div and then call a function to start fading out the divs. We will initialize i to 0 for indexing our div array.

Here we have used a 500 millsec delay because IE8 is not as fast as other browsers and the animation lags behind. Then we are going to get an array of random nos to randomly fadeout divs.

 		i=0;
var pos;
parent.append(mask);
setTimeout(function(){ im.hide(); doit(); },500);

var random_no = random_array(arr.length);

Step 8 – Creating the fading out function.

So far we have added the divs, inserted the mask div. Now we will fade out the divs randomly. So what we are going to do is create a timer and in that –

 function doit(){

	var timer = setInterval(function(){

	 if(i&gt;=arr.length)
		{

			clearInterval(timer);
					setTimeout(function(){
									incrementz();

								},2000)
			image_timer = setTimeout(function() {
										  		  effects(); },options.time);

		}

	  pos = $(arr[random_no[i]]).position();

	 if(pos!=null){
	 temp = mask.clone().css({top:pos.top,left:pos.left});
	 temp.fadeIn(300,function(){
									   $(arr[random_no[i]]).css('background-image','');
									   $(this).remove();
									   $(arr[random_no[i++]]).fadeOut(700,function(){

													 $(this).remove();

													  });

									   });

	 }

								 },90);

	};
};

Step 9 – creating the effect module

The transition should not be called directly. So we will create a function effects that is called after the mask transition is over. Note that in the cubeout function we are passing the image as parameter( firstChild).

function effects()
 {

	 cubeout(list_array[list_array.length-1].firstChild);
 };

Step 10 – creating the random number generator

Now we are going to create a function that generates an array of random numbers. We have used this in the cubeout function earlier.

function random_array(maxn)
 {

    var array = new Array();
	var temp,i,flag=true;
	var index =0;
	 while(index&lt;maxn)
	 {
		 flag = true;
		 temp = Math.floor(Math.random() * maxn);
		 for(i=0;i<array.length;i++)
		 {
			 if(temp==array[i])
			 {
				flag=false;
				break;
			 }
		 }

		 if(flag==true)
		 array[index++] = temp;
	 }

	 return array;
 };

Step 11 – Making it work on all the browsers

On webkit browsers (chrome and safari) plugin sometimes behaves buggy because webkit loads js and css in parallel. This may cause some problems, so we will wrap our code inside a function proceed and we will check if the browser is a webkit one then call the proceed function after the window has been loaded else call the function straight away.

Step 12 – calling the effect funtion

Finally we will initialize our slideshow.

image_timer = setTimeout(function() {   effects(); },4000);
</pre>
<h3>Final Code</h3>
Finally our code looks like -

<pre lang="javascript">
 (function($) {

$.fn.jMask = function(options){
	var defaults = {time:7000,width:600,height:500,bg:'#ffffff',border:'1px solid #ffffff',callback:function(){  } };
	var options = $.extend(defaults, options);
	var root = $(this);

	var ul = root.find("ul:first");
	var li = ul.find("li");
	var images = li.find("img");

	 root.find("div").attr("id","jMask-stage");

	 if($.browser.webkit)
	 {
		 $(window).load(function(){ proceed(); });
	 }
	else
	 proceed();

	function proceed(){

	var list_array = $.makeArray(li);
	var image_timer,arr,index,block,w,h,src,parent,im;

	li.css({"width":options.width,height:options.height,display:"block"});
	$("#jMask-stage").css({"width":options.width,height:options.height});

	 $(list_array[list_array.length-1]).find("span , h1,p").show();

	 function incrementz()
	 {

		var th,sr,temp =  list_array.pop();
		list_array.unshift(temp);
		if($(list_array[0]).hasClass('active'))
			$(list_array[0]).toggleClass('active reset');
			$(list_array[0]).find("span , h1,p").hide();
			$("#ribbon-left").hide();

			$(list_array[list_array.length-1]).toggleClass('active reset');
				$(list_array[list_array.length-1]).find("span , h1,p").show();
				$("#ribbon-left").show();
			$(list_array[list_array.length-2].firstChild).css({display:"block",opacity:1.0});
			$(list_array[list_array.length-1].firstChild).css({display:"block",opacity:1.0});

		options.callback(list_array[list_array.length-1].firstChild);
	 };

	 function effects()
	 {

		 cubeout(list_array[list_array.length-1].firstChild);
	 };

	function cubeout(image)
	{
		 im = $(image);
		 w = Math.floor(options.width/7);
		 h = Math.floor(options.width/7);
		 parent = im.parent();
		 arr = new Array();
		 i =0;
		 j =0;
		 var index = 0;
		 src = im.attr("src");
		 block = $("
<div>",{
					css:{
						position:"absolute",
						width:w,
						height:h,
						'background-image':'url('+src+')',
						'background-color':options.bg,
						'border':options.border

						}

							});
		 var temp,mask = block.clone();
		 mask.css({'background-image':'',display:"none"});
		 while(i=arr.length)
			{

				clearInterval(timer);
						setTimeout(function(){
																			incrementz();

									},2000)

						image_timer = setTimeout(function() {

												  		  effects(); },options.time);

			}

		  pos = $(arr[random_no[i]]).position();

		 if(pos!=null){
		 temp = mask.clone().css({top:pos.top,left:pos.left});
		 temp.fadeIn(300,function(){
										   $(arr[random_no[i]]).css('background-image','');
										   $(this).remove();
										   $(arr[random_no[i++]]).fadeOut(700,function(){

														 $(this).remove();

														  });

										   });

		 }

									 },90);

		};
	};

	image_timer = setTimeout(function() {   effects(); },4000);

	}

}

function random_array(maxn)
 {

    var array = new Array();
	var temp,i,flag=true;
	var index =0;
	 while(index<maxn)
	 {
		 flag = true;
		 temp = Math.floor(Math.random() * maxn);
		 for(i=0;i<array.length;i++)
		 {
			 if(temp==array[i])
			 {
				flag=false;
				break;
			 }
		 }

		 if(flag==true)
		 array[index++] = temp;
	 }

	 return array;
 };

		  })(jQuery);

Putting it all together.

Finally our plugin is ready to use. Just import the css file and our plugin. Usage is just like any other jquery plugin.

 $("#slideshow").jMask({width:680,height:380});

You can download the source files, along with the PSD. Feel free to use it for personal and commericial purposes, just refer a link back to this article.

Tags: , , , , , , ,
Posted in Tutorials | 12 Comments »

97 Beautiful Navigation’s for your Inspiration

Sunday, April 25th, 2010

Navigation is one of the key elements of designing a website. It is very important to have a very clean, informative and easy to follow navigation. Navigation is what keeps the user from going insane and helps them navigate around the site.

It is necessary as users are engaging in the site and navigation provides their destination. If they need to go to the home page, contact form or information about the website, it is almost next to impossible for them the find it easily without a navigation menu. As more users are visiting new websites, it has become even more essential have a clean, elegant and brief navigation.

Now, we also have entered the new era of web 2.0, so the navigation needs to enhanced in some way and made unique. So, here are some of the best navigation menus that follow these principles.

Alexarts

Candybar

Club Sites

Tutorial9

Attack of the Web

Sushi & Robots

Delibar

Gap Medics

Thibaud

Getraenke-Krukal

Mission Bicycle Company

Oink!

Clearleft

GETINVISION

Southern Media

Curious Generation Group

Utahtravel

f claire baxter

Gpacheco

Narwhal. Co

Jason Dorn

Delete

Jeffrey Sarmiento

Small Stone Recordings

Cassys Design

HANDCRAFTED CSS

Christmas Tweets

Ballpark

Custom Tshirts UK

XIXI NO BANHO

Microsoft

Carsonified

AdaptD

Sky Larkin

Ctrln

Lucia Soto

Dreamling

Neotelos

Gisele Jaquenod

Artcore-Illustrations

Mystery Tin

Netwise

Loodo

Tapbots

Checkout

Somos la pera limonera

marcusK

Joe Nyaggah

DFW Usability Professionals’ Association

Mailchimp

Web Design NJ

JP3 DESIGN

LemonStand

MetaLab

MacRabbit

Yorkdale

Jiri Tvrdek

Flicka

Graphik

Dreamer Lines

PixelResort

N.Design Studio

Media Temple

Kulturbanause

Diego Latorre

Fluxiom

Apple

Culinaryculture

Yodaa

Mimeo

Dpivision

Adidas

tap tap tap

Serigraphics

Mint

Inspire Image Design Labs

Lomotek Polymers

Jarnheimer Productions

Bert Timmermans

Kevadamson

Redvelvetart

Pampaneo

Taufiq Ridha

The Invoice Machine

The Great Bearded Reef

Ashes & Milk

Boloco

Freckle

Gugafit

BambooBali Arquitetura em Bambu

Indofolio

Elitewebmaster

ARIN s. r. o.

Stone Skipper

Global Creative Designs

David Hellmann

Dragon Interactive

Conclusion

As you can see, the examples were excellent and each was outstanding because it was unique. They look and follow the new trends of web 2.0. Many designers showed their creative side and displayed show magnificent navigation menus. Designers made it visually attractive so users are instantly drawn towards it.

The navigation menus are not cluttered and some navigation menus go in more detail by providing more sub-categories. I hope you got inspiration on navigation menus from this post and will apply these principles to make your website look better. This post is proudly sponsored by Sponsor: Windows 8 Themes. Please feel free to share your favorite ones in the comments below.

Download the latest Testking 646-671 design tutorials and Testking 70-643 videos by experts to get up to date information on web designing/development. Become expert with Testking 642-504 course.

Tags: , , , , , , ,
Posted in Inspiration | 12 Comments »

21 Tips to Make Your PHP Code Better

Friday, April 23rd, 2010

The most used and well documented programming language for web development is PHP, but it has some problems as a language (every language does). The most important problem is it’s too much permissive, and we can make some common mistakes that can hide our program’s behaviour beyond the limit, instead of writing a clean and easy readable code.

The “limit” is something abstract and we can’t draw the line. But there are many other things and habits we can do and get into of right now to be better developers, 20 of those things are right here.

1. The var_dump is your friend

This function lets you know the value of a variable. Yes, I know, it can sounds pretty obvious, but because PHP is a dynamic language the debugging process can be hard ( it could cover a whole tutorial, actually) and just see the value with a function can help us for “debugging” in an easy way.

This is the specification of such an useful function. Just in case you don’t get the point, we can pass it more than one variable!

var_dump

If you are just using this function and not showing anything more you can pass as the first parameter the string “<pre>” and the output will be easier to understand.

2. Measure the time

When we are developing, we all need to know how much is going to “cost”, because that price must be paid by the user and by our server. Actually is very easy, let’s see a way to do this.

<?php
function timer_start() {
	global $timeparts,$starttime;
	$timeparts = explode(" ",microtime());
	$starttime = $timeparts[1].substr($timeparts[0],1);
	$timeparts = explode(" ",microtime());
}

function time_end() {
	global $timeparts,$starttime;
	$endtime = $timeparts[1].substr($timeparts[0],1);
	return bcsub($endtime,$starttime,6);
}
?>

These functions are required and a very clean way to do this. We can have them in a file, include it whenever we need to measure the time and just echo the result. Here is how:

<?php
include('time_helper.php');

time_start();

// here the code you want to measure
echo 'Hi over there!';

echo time_end();
?>

3. Respect your style

Everyone has his own style, the problem comes when sometimes we have to write code together, or worst, a guy after us have to do it, the point is he has no idea about how we think.

An important fact here is our brain learns better through patterns, so if we respect the same style, we have crossed the first door to get a cleaner code. But, what am I talking about when I say style? The following two examples have different style. Take a look at them.

<?php
function test($var1)
{
	if ($var1)
	//Checking if var1 is ok
	{
		echo "Var1 is Ok";
	}
}
$var2=5;
?>
<?php
function test($var1){
	//Checking if var1 is ok
	if ($var1){
		echo "Var1 is Ok";
	}
}

$var2 = 5;
?>

Yes, I know it could look pointless, but the position of comments or braces have to respect a pattern. Remember, our brain learns faster if we do that.

4. Naming with strong meaning

Spiderman, a man who is almost like a spider, easy right? Well, the name of our functions or variables must be too. Whenever we name something we have to think about its functionality and name it accordingly.

You have to be able to have a clue about the role of the function or variable every time you use it. So don’t name a variable with something like “$a” or “$a1″, better “$request_result” or “$first_element”, for example.

5. Research into the field

It’s important, as a developer, know the tools you have on your table. Maybe you are thinking about how to do a function to sort an array because you don’t know if it has already been made. Of course there isn’t a function for every single case, but PHP is growing up, and has got a lot of functions, so Google can comes in handy if you are wondering how to do a common thing in PHP scripts.

You can also download a cheat sheet, which can show you at first sight the power of the tool you are working with.

6. Booleans could be complicated

If you have got a boolean variable, name it in an afirmative way. Just like the first example.

<?php
// Good and cleaner way
$enable = false;
if (!$enable)
	echo "Ok";

// Bad way. This is just if($enable)
$disable = false;
if (!$disable)
	echo 'Not ok';
?>

7. Copy and Paste are developers’ devils

Just two commands can waste a whole morning. I’m not saying we have to reinvent the wheel every time we type, but we always have to read and completely understand the code we are using.

Say we don’t do this, and we see a code similar to the code we want and without even reading it we just put in the middle of our script. Well, if you realize is like putting a spare part in our car without seeing it. If the car breaks down it’s justified, isn’t it?

A program is like a car, so take cares of him, and don’t let anything crosses the door without researching it before.

8. Getters and Setters

A class must respect some patterns too, like our style. A widely extended practice is mark the attributes as privates and if we want to make them public, we make its getter and setter functions.

See the example below, where we don’t want the rest of classes to know who the owner is, but we don’t care about they know the animal’s name, so we use this practice:

<?php
class animal{
	private $owner;
	private $name;

	// Getter
	public function get_name(){
		return $this->name;
	}

	// Setter
	public function set_name($string){
	   $this->name = $string;
	}
}
?>

9. Exceptions are useful

An exception sounds like an ugly thing, in fact every time we’ve got one means something is wrong and we have to fix it. But exceptions in a script can save a lot of time typing code and checking it.

When something can go wrong (almost always) we have to say to someone (the user or other program), at least the error and the reason why it happened. Exceptions can be very useful here, and using them is a must.

10. Divide to rule them all

A common explication for the students at University is that a program is just a set of boxes, the way the boxes have to communicate something is just their output (commonly return).

Well, this definitions is very abstract, but also very useful, we have to think about boxes when we are programming, and if some lines share an objective, we have to make a function and put them there. See this couple of snippets, and judge for yourself.

<?php
// Bad way
$int_array = array(1,9,10,12,7,2,8);

echo "We have to order this array" . "<br />";
foreach($int_array as $value){
	echo $value . "<br />";
}

sort($int_array);

echo "The output is:" . "<br />";
foreach($int_array as $value){
	echo $value . "<br />";
}
?>

And the good way:

<?php
// Good way
$int_array = array(1,9,10,12,7,2,8);

function print_array($array){
	foreach($array as $value){
		echo $value . "<br />";
	}
}

echo "We have to order this array" . "<br />";
print_array($int_array);

sort($int_array);

echo "The output is:" . "<br />";
print_array($int_array);
?>

Of course this is a fool example, because there is a way to do this with some built-in functions (var_dump, for instance), and the script doesn’t do too much work, but the point here is you can see the function “print_array” is saving us writing again the same code and the script, at first sight, looks cleaner.

11. Coding is important

Even essential if in your language there are characters like é, ó, ñ…etc. And not because of the code itself, the key are the comments or some html if you are printing it from a PHP script.

If you change the coding you can create a mess, so every time you are starting or modifying a project you need to check your editor is using exactly the same coding than the project.

I could say just don’t use weird symbols, but it’s not always possible, so be careful.

12. Comments are as important as the code is

I don’t want you to think I’m crazy, but imagine you develop a complex script, without a single comment, if someone is going to reuse it some months later, even you, and an error comes up, fixing the problem is going to take a lot of time just trying to understand the code plus fixing the problem itself.

There is a way to comment which can helps, because it’s very extended and almost every developer understands. You can see all the docs at the conclusion, but basically we’ll have some “special parameters” starting with @, like @see to refer another function, @return to specify the type of the the variable the function is going to return….etc. (You can see all of them in the link at the conclusion)

A good thing about using this format is you can use a tool and export the documentation as a pdf, html or another file, even from the IDE itself you are using (most IDE’s can do this).

13. Be independent

Your code must be a box, and a box doesn’t care about the rest of boxes, so your functions and classes shouldn’t do.

When we write a class we have to think the only way the user has to know something which could happen inside our class is up to us, so we have to do it as better as we can, and make developers’ life easiest (not only ours).

The better thing we can do is making a “map” of errors, and name them with a code and a description. When we have got an exception we return the specified error code. Of course our decisions aren’t standard, so we have to explain the code we’ve invented in the comments

14. An interface is a gift

When we have got a class, and the functions return really useful messages, we are very very lucky, because most developers returns values almost cryptic, and there is no reason apart from laziness to do this.

So every time we have to return something, or display a message, think the best and cleanest way to do that.

15. Official documentation is the only reliable source

Internet is a huge source of information, but in technical stuff, we have to be very carefully and don’t trust anyone, actually if you have got a doubt about a function, which is perfectly usual, it’s better looking up only in the official site.

documentation

16. Use of variables

In a programming language where we declare a variable with just a line, there is a risk of having too much and some pointless variables.

That’s exactly what happens in PHP when our program starts to grow. We should have variables, apart from well named, with a well known role in the script, and if we use an “aux” variable, taking care of not reusing it.

It’s not about the number of variables we can have, it’s about we need to know them all very well, and the reason why they exist.

17. Family is cool

At least in a programming context. PHP is an OO language, so not using heritage in our programs it’s almost an offense for an object oriented language like PHP. Let’s see how to do it, in the first example we can see the bad way:

<?php
class Person
{
    private $givenName;
    private $age;
}

class Employee
{
    private $givenName;
    private $age;
}
?>

And the good way should be something like:

<?php
abstract class Person{
    private $givenName;
    private $age;

	// Getters and setters
    public function set_givenName($name){
        $this->givenName = $name;
    }

    public function get_givenName(){
        return $this->givenName;
    }

    public function set_age($age){
        $this->age = $age;
    }

    public function get_age(){
        return $this->age;
    }

    public function say_hello(){
        echo("I am ");
        $this->print_data();
    }

	// The son will define this function according to its features
   	abstract public function print_data();
}

class Employee extends Person{
    private $role;

	// Getters and setters
    public function set_role($r){
        $this->role = $r;
    }

    public function get_role(){
        return $this->role;
    }

    /*This class have all the public and protected methods from
	the class Person*/
    public function print_data(){
        echo($this->getRole() . " " . $this->get_givenName() . " and I am " .
            $this->get_age() . " years old");
    }
}
?>

18. Functions should be small

If you have got a function where you need to scroll down to see its end, probably you should be thinking how to split it into smaller functions.

19. Frameworks can save you a lot of work

Frameworks are friends who can make for you the dirty work. There are many of them, probably the most used ones are CodeIgniter, Zend or CakePHP, but it’s up to you watch some screencast and study some tutorials to choose the one which should be better for the project we are working on.

If you are starting with frameworks in PHP I recommend you CodeIgniter, it has a great documentation, and develop with it it’s very easy.

CodeIgniter can save you a lot of work

20. Regular expressions are always useful

In every project, if it’s a little bit big, regular expressions will always come in handy.

Since removing repeated words in a text to extracting data from a raw format are only some tasks very easy to do with regular expressions. PHP has a set of functions to do that and know regular expressions and this functions can save you a lot of time, and even make the code cleaner.

21. Common sense above everything

This advices are only useful if you understand them, and try always to use your common sense. How to name variables, or comment the code are just some task where you should be using your common sense, so don’t forget we program for computers but also for human beings.

Conclusion

Like everything else in life you should learn as much as you can about the tools you are working with, and it takes a lot of time to become a better developer in any programming language, so be patience and remember, common sense and documentation are your best allies.

Geary Interactive agency is the leading Real Results digital marketing agency that provides nationally recognized, full service capabilities in a performance driven model. Download Windows 8 Themes

Sign up for Testking 220-702 professional training to learn how to make your PHP code better. Download Testking 70-647 php tutorials with expert Testking 70-290 study guides to become expert.

Tags: , , , , , , , ,
Posted in Tutorials | 16 Comments »

Five Reasons Why Twitter is The Best Social Media

Wednesday, April 21st, 2010

Nowadays, social media is a major part of success. If you have a start-up or you work as a freelancer, you should hear and use some of these social media services. If you did not, you are missing out the opportunity to get clients and unique visitors.

Actually, I don’t want to talk about how to use social media or how to grow your business, because there are a lot of articles about that. So, I will talk about Twitter as the best social media platform up to now. A lot of people may disagree with me, but I’m able to prove this with five points.

Why Twitter?

I will admit, Twitter has a special kind of charm that distinguishes it from other social media platforms. The achievement of Twitter is very stunning. Why Twitter? Because, Twitterers want to be the first to find out about anything. Why Twitter? Because, Twitter provides a global connection. Why Twitter? Because, Twitter users want news and Facebook users are more interested in trendy topics. You still want more? Here are five reasons to persuade you that Twitter is the best social media platform:

1 – Simplicity

As you know, freelancers and business owners have two aims when they carry out social media marketing, and it will be very hard to do that without simplicity:

Get more links in order to get more traffic;
Build the largest possible readership.

The simplification – the usability – of Twitter is one of the most important reasons why Twitter is sitting on the throne of social media. Simply put, you can tweet about your business and work at any time, from anywhere in the world. The Secret is the 140 characters that let you write over and over.

2- Rapid Fire

With millions of users on Twitter and other services like tags and search, some tweets will rapidly reach a large audience. Don’t forget – Twitter has one billion tweets per month, averaging almost 40 million tweets per day. Can you visualize the growing use of Twitter? What will it be like next year? In ten years?

There are two types of owners’ accounts on Twitter :

1- Individuals and Companies want to get the largest possible number of followers, and do that by following a lot of accounts for individuals and companies.

2- Famous Companies, people and websites have a lot of followers, although they follow very limited accounts themselves.

From my own experience, the second type is better for getting more traffic, because most followers for this type of account are really interested in what you have to say. No fake courtesies. No spam. No fake accounts.

3- Testimonials from Celebrities

Twitter has a lot of accounts for famous peoples, artists, singers and founders like Bill Gates, Barack Obama, Britney Spears and Oprah Winfrey. All that means is that the famous know they can build more consumers (or voters) from Twitter. These accounts also build more reputation for Twitter, which increases the demand – for Twitter.

Here are some of the celebrities account :

1- Britney Spears with more than 4,427,735 followers

2- Ellen DeGeneres with more than  4,261,563  Followers

3- Barack Obama with more than  3,309,557  Followers

4- Oprah Winfrey with more than  3,168,437  Followers

5- John Mayer with more than  3,066,404  Followers

6- CNN Breaking News with more than  2,906,187  Followers

7- Bill Gates with more than  481,203  Followers .

4- Tools and Applications

The huge number of tools and applications made by developers and companies greatly help Twitter to increase its rate of growth. The tools and applications split into many of categories:  Web-Based Mobile Apps, WordPress Twitter Plug-Ins, Find New Twitter Friends Apps, Search Twitter Apps, Tools and Productivity Apps, Statistics and Analytics, Adobe Air Twitter Apps and Firefox Twitter Extensions are just some of the categories. As to the tools and applications themselves, here are a few:

1- TwitPic

TwitPic lets you share photos on Twitter. You can post pictures to TwitPic from your phone, the TwitPic home page or your Twitter account.

2- Twitterfeed

Twitterfeed allows you to post your RSS feed to Twitter automatically.

3- TweetDeck

TweetDeck aims to improve the existing functionality of Twitter by taking the abundance of Twitter feeds and breaking them down into more manageable bite-sized pieces.

4- Twittercal

Twittercal is a service that connects your Twitter account to your Google Calendar and lets you add events easily, directly from your Twitter account.

5- Twibs

Twibs gives you the ability to find, follow and interact with businesses, apps and services on Twitter.

6- Twitter Alerts

Twitter alerts lets you keep track of conversations that mention you, your products, your company and anything else, via hourly email updates.

7- TweetStats

TweetStats is an app that tracks your number of tweets per hour and per month. It basically creates a graph based on your tweets.

8- Twitter Search

Twitter Search is an excellent search engine that allows you to find out what’s happening in the world beyond your personal timeline.

9- Twittelator

Twittelator is an all-around great new application for your iPhone.

10-TwitBin

TwitBin is a Firefox extension that allows you to keep up with all of your Twitter conversations directly from your browser’s sidebar, to send and receive messages, share links and more.


5- Measuring Success

If you still doubt that Twitter is the king of social media platforms, these live examples should change your mind. These are statistics for Twitter, Digg, Facebook, Stumbleupon, Raddit, Delicious and comments from popular sites around the Internet – Note the statistics are change with the time, and may have changed by the time this article is posted.

39 Olympic Logos From 1924 to 2012

This article features every logo from the summer and winter Olympic games from 1924 to 2012 and it gets 718 retweet, 123 digg and 246 share of Facebook.

50+ Beautiful Websites with Great Colour Schemes

This article features more than 50 Beautiful Websites with Great Colour Schemes and it gets 266 digg and 329 retweet.

10+ Tips For Using Twitter To Grow Your Freelance Business

This article shares some basic transferable principles that could help you to get your feet wet with Twitter and it gets 560 retweet, 33 share on Facebook and 89 saves on

11 Non-Traditional Uses of WordPress

This article looks at a combination of tutorials, plugins and themes that can help you to use WordPress in non-traditional ways and it gets 256 retweet and 116 comments.

Top 33 Best Logo Design Processes of 2009

This article is a round up that collected 33 of the most popular Logo Design Processes from 2009 and it gets 284 retweet and 22 comments.

How Much do Music Artists Earn Online?

This article is Talking about Music Artists and How much do they earn when their music is distributed online, compared to selling CDs? It doesn’t show digg, but it does show an astounding 1,765 retweets and 47 comments.

Conclusion

We have a lot of social media services; what should we use? I think Twitter is the most important and popular service on the Internet, as evidenced above by retweets vs. other platforms. However, some can’t afford to leave their efforts on other services. If this is you, link Facebook/Buzz/Digg and any other service you might be using with Twitter. Your social media efforts won’t be wasted, and they’ll be infused with Twitter power. Sponsor: Windows 8 Themes

Learn all about web designing with testkings online course. Learn the latest design techniques using testking 1z0-054 live demos and testking JN0-350 study guide.

Tags: , , , , , , , ,
Posted in Articles | 4 Comments »

Next Page »