• Tidak ada hasil yang ditemukan

INTRODUCTORY PROGRAMMING

Dalam dokumen Creating database-backed library Web pages (Halaman 80-102)

Chapter

4

In the Web server–based scripting approach, the Web server has been out- fitted with special modules to handle database requests and other types of pro- gramming tasks. Programming instructions are embedded directly into an HTML-like page that is given a special extension (such as search.php rather than search.html). When the user requests this special page, the Web server notes the special extension and then sends the request to the appropriate module. The module then processes the page, running the code inside the code areas as needed and returning the results to the server where they are in turn passed on to the user. The beauty of this approach is that the languages involved are easier to use and (because you don’t have to program the HTML sections) easier to develop, and that the module (being part of the Web server) performs its task quickly. This is the technique I will be showing you.

As you can tell from these descriptions, the approach we will be using involves programming. Therefore, it is a good idea to begin exploring how you (yes, YOU) can become a programmer.

PROGRAMMING?! YIKES!!

I can see it happening as I write this. The mere mention of the P word brings on the same physical symptoms as the phrase math test or hearing a police siren coming up behind you while you are driving: your breathing gets shallow, your eyes glaze over, and your fight-or-flight response is engaged as your brain goes numb. This is one area where we feel that the term Idiot’s Guide is all too appro- priate.

The truth is, programming is not a big deal. Anyone who has ever cooked a dinner, given driving directions, or done training has programmed. Program- ming is simply writing out step-by-step instructions to tell the dumbest entity on the planet (a computer) how to do something. If you start out with the assump- tion that you are smarter than a computer (which, if you’re reading this book—

or any book—or if you’re breathing for that matter, you are), you have already won half the battle!

Once you realize who the boss is, you just need to figure out how to let IT in on the secret. This will involve deciding what you need the computer to do, learning the language (words and grammar) that the computer can understand (because it certainly can’t understand English, at least not yet), and patiently (and thatis the key concept) writing out a step-by-step recipe telling it what to do at each step of the way.

68 I N T R O D U C T O RY P R O G R A M M I N G

We will now look at some of the techniques and concepts we use when telling computers what to do. (That is why programmers do what they do: they get to tell them what to do. Talk about a feeling of power!) To show that it is the syntax, rather than the activity, of programming that is unfamiliar, I will demon- strate each programming technique and concept below using a cooking analogy.

Appendix A pulls all of these together and shows how a recipe, written in pro- gramming style, looks and compares it to a more traditionally formatted recipe.

My hope is that, by seeing the two juxtaposed, you will have a better feel for (and less fear of) what programming actually is.

BASIC CONCEPTS

Values

We first need to define several basic concepts we will be using from here for- ward. Knowing these terms will go a long way toward understanding how pro- gramming actually works (and can be useful at cocktail parties as you wow your colleagues with your computational savvy). We will begin by looking at the ways that values are stored and transmitted within a program, focusing primarily on variables and arrays.

Variables

Variables are the building blocks that contain the individual values the program will use to do its job. They are, if you will, the containers into which you put your raw ingredients with the expectation that they will be transformed into some- thing edible. For example, when creating certain types of sauces, there are three categories of things (variables) you need to have to make the sauce: a fat, a thick- ening agent, and a liquid. Another way of looking at variables is to think of them as containers into which you place a value: a fat container, a thickening agent container, and a liquid container. Note that different kinds of sauces might start with different values for each of these containers (hence the term variable).

What a cook (programmer) does is to take those variables and assign values to them, depending on what the desired end result is. Thus, for a white sauce, the three variables might be given the following values:

$fat = "4T butter";1

$thickener = "4T flour";

$liquid = "8C milk";

On the other hand, if a brown sauce were needed, the variables might be these:

$fat = "2T oil";

$thickener = "2T flour";

$liquid = "3C beef broth";

Note that I have created the variables ($fat, $thickener, $liquid) by plac- ing a dollar sign in front of the variable name. This illustrates two principles. The first is the use of the $ in front. This tells the computer (and the programmer too, for that matter) that the thing $fatis a variable, not the word fat. Although not all programming languages use a dollar sign to denote a variable, PHP does (as does Perl). I have therefore used that formulation here so that it may become more familiar to you.

The second principle is that the word I used for a variable actually describes that which the variable is to represent. Although you could call it $x,

$big_foot, or even $mother_of_all_variables, such a name won’t help you as you use the variable in writing the program. Nor are you likely to remem- ber what it represents when you return to the program down the road. By using a variable name that clearly describes the information that it contains (such as

$fat), you are writing what is known as self-documenting code. This is a con- cept we use throughout this book.

You may have noticed that, in assigning values to a variable, I place the vari- able on the left side of the = and the value that will be assigned to that variable (poured into that container, if you will) on the right. This is about the closest you will ever come to a universal truth about all programming languages: content to the right of the = is assigned to the variable to the left of it.

Arrays

An array is a set of variables that contain related items of information. Arrays dif- fer from variables in that, though variables track individual entities, arrays organ- ize sets of values that go together in some way and that need to be handled together. When we program database searches, we will use arrays to store the individual records before processing them.

To return to our cooking metaphor, when creating a dish, you might keep all of the spices together in small bowls on your counter, using them as needed. For example, an Italian dish might have oregano, basil, thyme, marjoram, and garlic.

If you were to create an array to keep the names of all of the spices needed for a dish, you could assign each element individually:

70 I N T R O D U C T O RY P R O G R A M M I N G

$spices[0] = "2T oregano";

$spices[1] = "4T basil";

$spices[2] = "4T thyme";

$spices[3] = "1T marjoram";

$spices[4] = "3 cloves garlic";

Another option is to assign the elements in a single statement:

$spices = array("2T oregano","4T basil","4T thyme","1T marjoram","3 cloves garlic");

Either way, in using an array, when you need to add the spices, you can refer to them as $spices[0], $spices[1], $spices[2], and so forth instead of using 2T oregano, 4T basil, 4T thyme, and so on. Note that we are using a num- ber as the index (array address, if you will) of the individual elements (or values) of the array. This technique is useful if you will be stepping through the array one at a time and don’t need to look for any particular value.

An alternate approach to indexing arrays—associative arrays—is supported by a number of languages, including PHP. An associative array is one in which we associate a name with the value being stored in the individual element, rather than a number. For example, if we were creating an array of the values needed to make a sauce, we could create it like this:

$sauce["fat"] = "4T butter";

$sauce["thickener"] = "4T flour";

$sauce["liquid"] = "8C milk";

Thus, referring to $sauce["fat"] would get us the value 4T butter,

$sauce["thickener"]would be 4T flour, and $sauce["liquid"]would be 8C milk. This technique makes it much easier to access and output items in an array—such as the results of a database search—by using a name that we know (the field name) rather than having to know where in the array a particular value is to be found. The formulation $result_array[<field_name>] gives us access to each field of the results. Thus, in handling output from a database search, we can use $record["title"] to obtain the title field, $record ["author"]to get the author, and so on. In this case, by referencing $sauce ["fat"], we would obtain the value 4T butter. This is a remarkably powerful and useful technique and one that I use throughout the book. You will have many opportunities to see it in action.2

Coding

Let me now demonstrate how to do something with variables and arrays.

Building on our sauce example above, let’s “program” a white sauce we can use to make macaroni and cheese. As noted, creating the program involves writing out each action that needs to be performed to get the desired results. To start, I will use pseudo-code to demonstrate the concept. Pseudo-code is a technique in which you describe what needs to be done in a programming-like way without getting into the intricacies of a particular programming language. I will show you a more programming-like way of doing this later in the chapter.

1. $pan = "4 quart sauce pan";

2. $how_hot = "medium high";

3. $heat_source = "stove";

4. $sauce["fat"] = "4T butter";

5. $sauce["thickener"] = "4T flour";

6. $sauce["liquid"] = "8C milk";

7.

8. Place $pan on $heat_source;

9. Turn on $heat_source under $pan to $how_hot;

10. $roux = $sauce["thickener"] + $sauce["fat"];

11. Place $roux into $pan;

12. Heat the $roux;

13. Heat $sauce["liquid"];

14. $white_sauce = $roux + $sauce["liquid"];

Lines 1–6 set the variables for the program. These include the type of pan ($pan), the temperature at which to make the sauce ($how_hot), what you’re cooking on ($heat_source), and the array of items with which to start the sauce ($sauce). Lines 8–14 then describe the steps to be taken with the variables.

When this “program” is run, the program substitutes the contents of each vari- able for the variable name. Thus, line 8 becomes “Place 4-quart sauce pan on stove”

and line 9 becomes “Turn on stove under 4-quart sauce pan to medium high.”

Decision Blocks

Anyone familiar with cooking is aware that the previous recipe does not provide enough information as written. You could perform each step in succession, but the results would be far from satisfactory. For this recipe to work, we need to tell the cook (the computer) certain things, including

72 I N T R O D U C T O RY P R O G R A M M I N G

How long should the heating in line 12 continue?

Does one add $sauce["liquid"]all at once?

How does one know if the process is working correctly?

For each of these questions, instructions need to be included in the program so that the cook (being a computer, not a very bright cook) can proceed properly.

The following code shows how we might flesh out the needed information:

1. $pan = "4 quart sauce pan";

2. $how_hot = "medium high";

3. $heat_source = "stove";

4. $sauce["fat"] = "4T butter";

5. $sauce["thickener"] = "4T flour";

6. $sauce["liquid"] = "8C milk";

7. $half_cups = 16;

8.

9. Place $pan on $heat_source;

10. Turn on $heat_source under $pan to $how_hot;

11. $roux = $sauce["thickener"] + $sauce["fat"];

12. Place $roux into $pan;

13. $roux_status = "raw";

14. while ( $roux_status == "raw" ) { 15. stir $roux;

16. $temp = temp( $roux );

17. if ( $temp < 350 ) { 18. print "Not Yet";

19. } elseif ( $temp >= 350 && $temp < 400 ) { 20. $roux_status == "cooked";

21. } else {

22. $roux_status = "burned";

23. throw_away( $roux );

24. exit;

25. } 26. }

27. Heat $sauce["liquid"];

28. $bechamel = $roux;

29. for ( $x=0; $x < $half_cups; $x++ ) {3

30. $bechamel = $bechamel + 1/2 cup ( $sauce["liquid"] );

31. stir $bechamel for 30 seconds;

32. print "You have added $x cups";

33. }

In this example, lines 1–7 set the values for each of the variables and lines 9–33 contain the expanded steps. These steps are implemented as decision blocks.

Note that this example has three decision blocks—places where the computer decides what to do, whether to continue what it has been doing, or to do some- thing new. These three types of blocks (while, if, and for) are those we will use most often in this book. Before examining them more closely, let us take a look at how a block is structured.

All decision blocks have the same structure:

1. conditional ( condition ) { 2. "Do something!";

3. }

There are four things to note here:

conditionalwhile, if, or for

condition—the condition the computer should check to see if it should execute this block

The entire block of code is contained in a block—between the {and } characters—that is executed if the condition is met. If the condition is foror while, then it continues to be executed for as long as the condition in line #1 is true (if the condition is if, then the block is run only once). This means that the block starts at the first line and continues executing until the last line before the }character and, if appropriate, checks the condition again at the top of the block to see if it is still true. If so, it goes through the block again. If not, it goes to the first command after the block closes.4

Here the {and }characters are used to denote the beginning and end of the block, the way it is done in C, C++, Java, PHP, Python, and other C-like languages. Note that Pascal usesbegin/end.

Before continuing, I would like to point out a formatting convention that, though not required, does make programming code a lot easier to read: within the first decision block (lines 15–26), the lines are indented three spaces and, within the blocks within that block (lines 18, 20, and 22–24), the lines are 74 I N T R O D U C T O RY P R O G R A M M I N G

indented again. Although the programming language does not require this, indenting makes it easier to see where decisions are being made, what is being done at each possible point, and where blocks begin and end. I strongly suggest that you follow this practice.

Now let us take a closer look at the conditional statements:

while (lines 14–26). This block says, “As long as the $roux_statusis raw, keep on cooking.” Because we initialized—gave an initial value of—rawto $roux_statusat line 13, the first time we get to line 14, it enters the loop. If you don’t do this—or you gave it any other value––it would never enter the whileloop at line 14. It then pro- ceeds through to the end of the block (line 26). When it goes there, it goes back to 14 and checks to see if the $roux_status is still raw. If it is, the program goes through the block again and contin- ues to do so until the condition is no longer true. For this status to change, a test needs to be run each time through the block to see if the status should be changed. This is done in line 16, where the tem- perature of the mixture is taken. If you do not do this, the status will never change and so the program will never end (you will have entered what is called an infinite loop).

if (lines 17–25). An ifblock says “if a condition is true, then, do some- thing once” (where there are multiple possibilities, you can use one or more elseif statements to do subsequent checks of the value).

In line 16, you get the temperature of the roux and then proceed to your ifstatements. In this case, the condition is checking the value by taking the temperature of the roux. If the temperature is less than 350, then the first condition ifblock is entered and the cook is told “Not yet”5 and the program skips the other two conditions (lines 19 and 21), jumping down to line 25 (the closing of the if/then/elseblock at which point it returns to line 14, where the status is checked. Because it has not changed, it enters that block again. Also note that this block actually has two more tests. If the temperature is not less than 350, then check to see if the tempera- ture is between 350 and 400. If so, it enters the second block, where the $roux_statusvalue is set to cooked(at which point, it goes to line 26 and then back up to 14 to check the status again. Because the status is now cooked, the program skips down to line 27 (the first line after the whileloop) and proceeds to the next task. However, if it finds that $tempis more than 400, that means that the process

has somehow gotten away from you and has burned. You then change the $roux_statusto burned, throw the $rouxaway, and exit the program (presumably to start over).

for (lines 29–33). In a forblock, you know the number of times you need to go through the block (in this case, the number assigned to a sentinel variable $half_cups). In the opening statement, you ini- tialize a counter variable, ($x=0); you tell it to run as long as the counter variable is less than the sentinel variable ($x<$half_

cups). You then tell it to increment the counter variable by one each time the block is run ($x++). Then, each time you go through the block, you add 1/2 cup of liquid and stir for 30 seconds, at which point you start the block over and see if your counter variable is now equal to (not less than) your sentinel value, $half_cups. Once it is equal, that means that all of the liquid has been added and the sauce is made.

When going through a forblock, it was noted that a counter variable is used to keep track of how many times the block had been executed. This makes the counter variable a valuable resource when used within the block with a numeri- cally indexed array. This is because, as you go through the block, $xis increasing in value by 1 each time through the block. You could then use $xto go through an array one at a time, using the variable as the index to the array to access the array values. For example, if you were making an Italian dish, you could access the array as follows:

1. $num = count( $spices );

2. for ( $x=0; $x<$num; $x++ ) { 3. add $spices[$x];

4. }

The first time through the loop (when the value of $xwas 0), line 3 would read $spices[0](whose value is 2T oregano) and it would be executed as:

add 2T oregano

The second time, the value of $x would be 1 and, because the value of

$spices[1]is 4T basil, it would be executed as:

add 4T basil

and so on. This is a technique we will be using often.

76 I N T R O D U C T O RY P R O G R A M M I N G

Dalam dokumen Creating database-backed library Web pages (Halaman 80-102)

Dokumen terkait