Articles with tag ‘tutorial‘

 
 

Advance Your Programming - Part 2 - Templates

Every programmer is faced with code repetition at some point. Since the earliest programming in assembly language we have seen code repetition happens often and can be a problem. We realized that there should be a way to reduce the repetition to help the programmer.

The most basic solution was creating a procedure (also known as functions and methods), which would run the repetitive code. Every point where where one would encounter a situation where he/she would need the code they would call the procedure (with parameters if necessary) and the procedure would run the code. This had a number of advantages for the programmers.

  1. The amount of code could be greatly reduced.
  2. The procedures/functions could be modular by using parameters
  3. Changes would only need to be made in one place, greatly enhancing maintainability

In terms of web development you will encounter programming situations in PHP and javascript where you will need to use the aforementioned method of creating procedures and functions but what about HTML/XHTML?

Repetition across HTML documents is obvious. For starters, each document will have a head and a body. Quite possibly there will be a footer within the body. More then likely the header and footer for each document will be almost exactly the same. First time programmers will see this as an excellent copy-and-paste opportunity but from an experienced perspective you can see that this is just code repetition. The copy-and-paste technique will work but will almost surely cost you more work in the future.

Imagine this common situation, you have a website with 20 separate HTML documents each with the same CSS include files and the same footer <div> which displays contact information and links. Something along the lines of a header:

<head>
  <title>My Site - Homepage</title>
  <link rel="stylesheet" type="text/css" src="general.css" />
  <script type="text/javascript" src="scripts.js" />
</head>

And a footer:

<div id="footer">
  <p>&copy; 2006-2007 My Site</p>
  <p>
     <a href="index.html">Home</a> |
     <a href="contact.html">Contact</a>
  </p>
</div>

Now imagine that you have to make a change. You might want to change the name of the css or javascript file, add a javascript file to include, change the years in the footer or change one of the link locations or names. To make any of these single changes you would have to go and manually edit all 20 pages. This is the worst possible situation and it can be easily avoided. The concept is using a template, and including repetitive code, which has the same three advantages above.

Templates are not possible solely with HTML. That is unless you are using frames in which you have little to no control and horrible cross browser computability. Don’t even try frames. Template driven websites can be created very easily with server-side programming languages (PHP/ASP) or even just using a sophisticated web server like Apache using a concept called Service Side Includes (SSI). The idea is that such a fundamental concept in both programming and design should be easy to implement, and templates are considered a major concept.

There are really only two steps needed to make this happen. First put the section of html that you want included from all of your main documents into a single file. Common extensions are .inc for include, but the extension does not matter. The above case is a nice example, you could put the footer into its own file, footer.inc. Many frameworks have an entire folder devoted to included files, often named includes/ in the root directory. This is a good idea and makes it easy to use an absolute path inside any html document on the web server to the include files.

Finally you now need to include the file from you main html documents. Here is the php way to include that file:

<?php include '/includes/footer.inc'; ?>

And the SSI method which looks a lot like an html comment (You may need to look into turning on SSI functionality on your webserver first, here is a resource):

<!--#include virtual="'/includes/footer.inc'" -->

With the correct include statement above the contents of your include file will be placed at that position in the HTML document. This is all done on the server, so the final product delivered to the client’s browser (the person visiting your website) will not be any different from the original.

There are differences between the PHP and SSI includes. Without question the PHP includes are more powerful but I’ll give a brief description of each. The SSI’s only go one level deep. This means that if you include a file, you will not be able to include another file from within the included file. SSI is meant to allow for very basic templating without a full blown server side programming language like PHP.

With PHP there are endless possibilities. The included files can contain php code. In actuality, when you include a file in PHP the contents of the file are run as if they are php code. So any php tags will be properly executed. Even the variables outside of the include are directly accessible because they are considered on the same scope as the included code.

There are a few ways you could put the above header a php include. Here is a very straightforward approach. First the PHP file to be include. I will call it ‘header.php’ because that is a clear indicator to me later that the file contains php code. Notice the php tag and variable:

<head>
  <title>My Site - <?php echo $pageTitle; ?></title>
  <link rel="stylesheet" type="text/css" src="general.css" />
  <script type="text/javascript" src="scripts.js" />
</head>

The original php file that would set the variable before the include like so:

<?php
$pageTitle = 'Homepage';
include '/includes/header.php';
?>

This would work just fine. It is a very loose form of templates. The programmer is forced to keep track of the variables that are all floating around in the global scope. Another approach would be to make a collection of functions, like an API. Take this example:

<?php
/*
  Function to print out the <head> for each of my webpages.
  @param   $title   To go inside the <title>
*/
function printHead($title = 'My Site') {
?>

<head>
  <title><?php echo $title; ?></title>
  <link rel="stylesheet" type="text/css" src="general.css" />
  <script type="text/javascript" src="scripts.js" />
</head>

<?php
}
?>

Clearly a little more structured approach. You would have to include this file to make the function available, but everything from there is straightforward. Just call the function and pass the appropriate title as a parameter to the function:

<?php
include '/includes/commonFunctions.php';
printHead('My Site - Homepage');
?>

Templates are a fundamental part of good programming. Common uses are the header, footer, and menu’s for websites. Very little variation is needed across a website for these portions, so consolidating all of the code into a single file is immensely helpful. I just want to make sure that you learn about it soon and not like I did. The hard way.

Introduction to Server Side Includes - Apache’s very own HowTo. A good start.

Setup More SSI Setup Information - Some Troubleshooting and Methods to get SSI working on Apache

PHP Include Function - Documentation and Comments on the include function. Will be helpful to PHP developers.

A Unique Unix Tutorial

Thats right. You’ve all read tutorials. They range all over the place: boring, brief, detailed, useless, inspiring, the list goes on. There are those that are too technical, that you don’t understand until you look back at them at a later date. In the case of Unix and Linux the majority of the tutorials are like that. They are just reworded man pages. Many people turn away from *nix because of this gap in technical familiarity. My Unix tutorial aims to change this.

I have read a number of tutorials and I find the best are the ones that include you, the reader, in them. You are participating in the tutorial. Often there is a story, or some creative aspect that brings you into the tutorial. You are learning in an entertaining way. For first timers this can make all the difference.

My tutorial also gives tips and tricks for using the terminal. They are the kind of tricks that make using the console much easier, but they are the tricks that you often don’t know unless someone shows you. I hope that my tutorial at least gives insight to newer Unix/Linux users as they take the leap into a new realm.

Please take a look and offer your feedback to help me improve the tutorial. I now present my Unix Tutorial.

I would like to point out that the tutorial happened to be a college project that I recently decided to turn into a reality. I have been and will be refurnishing the tutorial with improvements (sIFR), more rich content, while still maintaining my original goals and objectives.

Inspiration: A rather stimulating Ruby tutorial that wraps you inside a rather creative story, with “synergy and cartoon foxes.”

Advance Your Programming - Part 1 - Regex

In my case I will talk about PHP, because it is so widely available (nearly 100% of reasonable hosting companies include PHP support in even their lowest plans). This article is also geared toward rather novice programmers because surely the aspects I mention can be seen on the tool belt of all master programmers.

  • Regular Expressions
  • Templates and Includes
  • XML Parsing

I will only touch light on these subjects in the hope that you will continue research on them if you have a desire to improve your skills. Once learning each of these, your understanding of web programming will be greatly improved, your code may become cleaner and more concise, and most importantly you will have more fun programming! Today’s article will focus on Regular Expressions, commonly refered to as regex.

Regular Expressions - Regex

This will not be an article teaching regular expressions (I may refer to them as ‘regex’). I would rather this be a stimulus for you to learn regular expressions if you are currently in the dark, and afterwards I may provide you with a few sources to help you learn regular expressions. You don’t need to really understand the regex that I show you in this article, nor will I really explain them to you. You may even be able to decipher what the regex means on your own. Keep in mind that I am showing you uses of regular expressions, their powerful and simplicity, as a means to entice you to learn them yourself. You will not regret it.

Regular expressions are a language in their own. At first glance, a regex may appear complex, but they are in fact very straightforward and they have many uses for web programmers. Regex provide pattern matching for strings. A common use is searching a string for something, if that something exists then execute some code. Or the reverse, if the pattern is not found then execute some code. One such example is input validation.

Lets say you have a simple contact form, which asks for a user’s phone number and email address. Those are common form elements and should be checked for valid input so you can be sure users are not putting deliberately fake input or perhaps a simple typo in their phone number. Regex can ensure that the users input is not only valid, but that it is also in the correct format that you specify, making your work easier.

Lets make a simple PHP example, with hardcoded values, and the phone number format we want is ###-###-####.


<?php
$str = '555-555-555a';
$regex = '/^d{3}-d{3}-d{4}$/';
if (preg_match($regex, $str))
  echo 'This is a valid phone number.';
else
  echo 'Bad phone number.';
?>

The regex is located between the forward slashes. / here /. I am also using a PHP function preg_match( regex, string the regex works on ). For those interested, here is the documentation on preg_match from php.net. Copy, Paste, Save, and Run this example and you should see that the result is that 555-555-555a is indeed a bad phone number! The reason, you probably determined, was that ‘a’ is not a number! The preg_match() function applies the regex on the string and finds that the string is not in the correct format (described above). Powerful, simple, and fast! To see the script in action with a working phone number change $str to any valid phone number, here is an example:

$str = '123-456-7890';

With one simple string we force all input to be exactly how we want it! To show how flexible regex can be, we can extend the regular expression to allow for a phone number in either: ###-###-### format, ######### format, or (###) ###-#### format! All at the same time like so: /^(\d{3}-\d{3}-\d{4})|\d{10}|(\(\d{3}\) \d{3}-\d{4})$/

Now lets take a look at an email address. An email address to be valid should look something like: example@domain.com. It may even be as complex as: alpha.123@crazy.com, but lets just have a regex to allow for a simple email address. Here goes:


<?php
$email = 'example@domain.net';
if (preg_match('/^[a-z0-9_-]+@([_a-z0-9-]+.)+(com|net)$/i', $email))
  echo 'Valid Email ending in .com or .net';
else
  echo 'Bad email address!';
?>

The regular expression allows for only a simple email address. It only allows email address ending in .com or .net, but that can easily be extended. I think you can see how powerful this is! Only allow valid formatted email address will prevent problems down the line if you ever have to email this person using a script. At least the email will be correctly formatted, at least your script won’t crash prematurely due to a formatting error, but instead the worst that could happen was the email is sent but no one ever receives it!

The simplicity of regex in form validation is unparalleled. How would you ensure that the user put in a valid phone number?!? Would you individually check each character in the string? Make sure that the first character is a number, the second, the third, then a dash, number, number, … A pain to do manually, regular expressions are just a single string which can do all of the work.

Soon I will provide another use of regular expression, search and replace! There are countless uses but I will cover topics you will surely have to deal with as web programmers, and by learning regular expressions you will see a new world of possibilities. It would be best if you started to learn the basics of regular expressions and so I will provide you with some links.

Overview - A Brief but Very Accurate Overview of Regular Expressions.

Regular-Expressions.info - Regex Tutorial, Examples and Reference - Regexp Patterns
This is the website I highly recommend that you start at.

Regular expression - Wikipedia, the free encyclopedia
Wikipedia is always a great resource for programming questions.

Regular Expressions Cheat Sheet - Cheat Sheets - ILoveJackDaniels.com
If ever you need a cheat sheet, be it PHP, Ruby on Rails, or CSS, get it here!


Recent Resources

Clicky Web Analytics