Posted 01/28/2010 - 19:00 by State68
Most people who don't need to code never have to learn how to code, and live their lives in bissful ignorance. This includes people like graphic designers who use a computer every day to do pretty technical things: Photoshop, for example. But when they come to do Drupal theming, these same people need to know a load of coding fundamentals that aren't covered in even the most basic PHP tutorials.
So, here we are: a tutorial that covers the real fundamentals of coding. I'm using PHP for the examples, but the concepts translate to any programming language. One thing to note: any computer program is broken up into individual lines. PHP separates these lines with semicolons, which is why you see them at the end of every line.
1. Input, processing, output, and comments
In essence a computer, and therefore a programming language, does three things. It accepts input, usually from something that's typed into the keyboard. It then processes that input. For example, a very simple computer program might take your date of birth and the current date as inputs, and work out how old you were. Finally, the program produces some form of output, usually displayed on the screen.
By the time we're working with the theme layer in Drupal, almost all of the input and processing stuff has been dealt with, so we only have to worry about output. In PHP, output statements look like this:
<?php
echo "Hello World!"; //This displays the text "Hello World!" on the screen, without the quotes
print "Hello again!"; //Similarly, this displays "Hello again!" on the screen, again without the quotes
?>For our purposes, the echo and print commands do exactly the same thing: they make stuff appear on the screen. If we're using them like in this example they're pretty limited, but they can be combined with other things to become much more powerful.
Note that in the example above, we've used slashes to demarcate part of the text. The text to the right of the slashes is called a comment, and it will be ignored when your program is run. Comments are really useful for making sure that other people can understand code that you've written.
There is another comment style that allows you to comment multiple lines in one go:
<?php
print "Hello World!"; // Doing comments like this only comments out one line at a time...
/*
But doing comments like this
lets you comment out
lots and lots of lines
in one go!
*/
?>In summary: if you want stuff to appear on the screen, you're going to have to use print or echo.
2. Variables
Printing stuff to the screen is all well and good, but it would be pretty crap if all of that stuff had to be stored within our program. And, obviously, this isn't how things work. Any computer program (I'm including any interactive website in that definition) stores stuff that you type in. It stores this stuff in variables.
For example,
<?php
$OurVariable = "Hello World!";
print $OurVariable;
?>This would not display "$OurVariable" on the screen. Instead, it displays "Hello World!", which we allocated to our variable by using the "=" sign. There are two things to note here. Firstly, our variable has a "$" sign in front of it. This indicates to PHP, the programming language we're working in, that we're referring to a variable. Different programming languages have different conventions that you have to follow when giving a variable a name: in JavaScript, for example, variables should start with a lower case letter.
The second thing to note in this example is that we are "hard coding" the value of our variable into the code. In real world examples, we'd have some extra code that would allow the user to enter a value for the variable, but seeing as Drupal deals with all of that stuff we're not going to cover it here.
Variables can have lots of different types. For example, a variable could be a number, or a load of text - usually called a string. There are other types, but that's all you need to know for now. Whenever you're setting a variable to a value that is a string, you should use inverted commas. When you're setting a variable to a numerical value, never use inverted commas:
<?php
$a_number = 12345;
$a_string = "Twelve thousand, three hundred and forty-five";
?>In summary: variables store stuff.
3. Operators and concatenators
Once you've got stuff stored in variables, it's really useful to be able to manipulate that stuff. For example, if you've got two numbers stored in separate variables, it would be good to be able to store the sum of those two numbers in a separate variable. Here's how you do it in PHP:
<?php
$number1 = 325;
$number2 = 178;
$sum = $number1 + $number2;
print $sum;
?>This would output the sum of 325 and 178 - 503 - to the screen.
There are lots of different operators - see http://www.w3schools.com/PHP/php_operators.asp. The Arithmetic Operators listed there should all make sense; don't worry if the other stuff doesn't.
One special operator that you'll probably use a lot is the concatenator. In PHP this operator is written as a dot (in JavaScript the plus sign is used in stead). It lets you join multiple strings together into one long string. It works like this:
<?php
$FirstBit = "You can use ";
$MiddleBit "the concatenator ";
$LastBit = "to join multiple strings together!"
$BigLongString = $FirstBit . $MiddleBit . $LastBit;
print $BigLongString;
?>This will output,
You can use the concatenator to join multiple strings together!In summary: operators combine variables to give a result
4. Arrays
Sometimes you won't know exactly how many values you want your program to store before it's actually running. For example, consider a program that asks you to enter the heights of a load of different people, and then gives you back the average height. It would be a real pain if the program only worked if there were precisely ten people in the group, and it would be much better if the program let you enter as many or as few values as you wanted to.
Arrays let you do this. An array is a variable that stores multiple values. The number of values an array can store expands dynamically: if you give an array more stuff to store, that array just stores it. For example:
Any entry in an array has two parts: a key and a value. The value is the thing that you actually want to store; the key just indicates where in the array that thing is stored. This is how you build an array which has keys containing the names of football teams, and values containing the names of the teams' stadia:
<?php
$StadiumArray['Arsenal'] = 'Ashburton Grove';
$StadiumArray['Chelsea'] = 'Stamford Bridge';
$StadiumArray['Liverpool'] = 'Anfield';
$StadiumArray['Manchester United'] = 'Old Trafford';
print $StadiumArray['Liverpool']; // outputs 'Anfield'.
?>Often, the indices of an array will be numbers. In this case, the command,
<?php
$Array[] = 'Next Entry';
?>Can be used to store the value 'Next Entry' in the next available space in the array. If $Array[0], $Array[1] and $Array[2] all have values, then 'Next Entry' will be stored in $Array[3].
In summary: arrays are super variables that can contain more than one value at the same time.
5. Conditional logic
All computer programs should do certain things in certain circumstances, and certain things in other circumstances. For example, a website should only let users see certain parts of the site if they are logged in.
This sort of programming structure is called conditional logic. If a certain condition is met, then do something. Otherwise, do something else. Here's a mock up of how the password bit of a website works - imagine the user has just typed in a password, and it's been stored in the variable $PasswordEnteredByUser:
<?php
$PasswordStoredByWebsite = "TheCorrectPassword";
if ($PasswordEnteredByUser == $PasswordStoredByWebsite) {
print 'You are allowed to see the site!';
}
else {
print 'You are not allowed to see the site. Try entering your password again.';
}
?>First of all, don't get freaked out by the double equals sign, '=='. All this means is "is the same as". We're already using the single equals sign to assign values to variables, so we need to use something else to mean "is the same as". This is called a comparison operator - there are a number of other comparison operators; they're all listed at http://php.net/manual/en/language.operators.comparison.php.
Now, reading through this program is pretty straight forward. Translated into English, it says, "if the password is correct, display a message saying that the user is allowed to see the site. Otherwise, display a message saying the user is not allowed to see the site, and that they should try entering their password again".
There is one other part of conditional logic that's important to know: the elseif statement. Consider a (really stupid) password program, where the password is set to "1" but the user is told that the password is either 1, 2 or 3. The user guesses the password and it's stored in $PasswordEnteredByUser:
<?php
if ($PasswordEnteredByUser == 1) {
print "That's the right password";
}
elseif ($PasswordEnteredByUser == 2) {
print "That's pretty close, but it's not right!";
}
else ($PasswordEnteredByUser == 3) {
print "That was miles out!";
}
?>Here, if the user got the password right, then they're shown the first message. But if they got the password wrong, the program goes on to check whether the user was almost right. If they were, they're shown the second message. Finally, if the user wasn't even close, they are shown the third message.
In summary: Conditional logic lets you make your program do stuff only in certain circumstances.
6. Functions
Any computer program could, in theory, be written as one long piece of code, containing lots of variables and conditional logic. There are, however, a number of reasons why this isn't done, which we'll go into in a second. Instead, computer programs tend to make extensive use of functions. These are mini computer programs that the main program can call. Just like with a program, you give a function some input data (called arguments) and it gives you an output (called a return value).
The following program is a simple (in fact, pointlessly simple) calculator. The user has entered five values, $a, $b, $c, $d and $e, and has then picked what they want to do with those values: add them together, multiply them together, or find the average:
<?php
if ($operation == "add") {
$answer = $a + $b + $c + $d + $e;
}
elseif ($operation == "multiply" {
$answer = $a * $b * $c * $d * $e;
}
elseif ($operation == "average") {
$answer = fancy_new_averaging_function($a, $b, $c, $d, $e);
}
print $answer;
function fancy_new_averaging_function($v, $w, $x, $y, $z) {
$sum_total = $v + $w + $x + $y + $z;
$averge = $sum_total / 5;
return $average;
}
?>In this program, additions and multiplications are done in the main flow, but if the user wants to perform the more complicated averaging operation, this is delegated to a separate function.
There are a couple of advantages to this. First of all, if there is an operation that you want to perform multiple times at various different points in your program, you can type it all into a function, and then call that function instead. For our example that doesn't seem hugely useful, but consider it in the context of Drupal: every time a node is loaded, Drupal has to perform a huge number of operations, pulling all of the relevant data out of the database and putting it all together in a useful way (the node object, if you're interested - we deal with objects next). If all of these operations were typed in by hand for each instance that a node was loaded, Drupal would be unworkable. Instead, everything is typed in once, into the node_load() function. If you call this function with the id number of the node you want to load, node_load() gives you back the node object.
In addition to reusability, using functions makes code more readable. When you're reading through a program, it can be difficult to follow its flow. If parts of it are packaged up into functions, your job is made a lot easier: you can just concentrate on what the main program is doing, and then read the functions that it calls later on.
In addition to custom functions, PHP ships with more than 700 built-in functions. On top of that, Drupal defines a load more functions that you can use.
One other advantage of using functions is that it allows you to make use of a feature called variable scope. I'm not going to go into this in depth here (if you want to learn more, a good place to start is this tutorial: it's based on JavaScript rather than PHP, but it should make sense). Just bear in mind that it is possible to set variables up so that only a particularly function can see them - in fact, this is the normal thing to do.
In summary: Functions are mini programs that other programs can use. They help keep code neat and readable.
7. Objects
There is a widely adopted way of doing programming called object-oriented programming. You don't have to know too much about this, apart from the fact that it makes use of something called an object.
Objects are a pretty complicated idea to fully get your head round. They make a great deal of use of the scope concept discussed above with regards to variables, and make for great code. However, you don't really need to know any of that. For your purposes, you can think of an object as a thing that contains functions and variables (and other objects). To confuse things a bit, functions are called methods when they're referred to in the context of objects, and variables are called properties.
Objects, methods and properties work like this:
<?php
$object->property1 = "This is the value of a property of our object";
$object->property2 = "This is the value of another proprety of our object";
print $object->property1; // prints the value of the first property
print $object->property2; // prints the value of the second property
$object->property3 = $object->some_method(); // calls a method - in other words, a function
?>Defining objects - especially their methods - is outside the scope of this tutorial, but you won't have to do it. The key thing here is that if you see something that looks like a variable with a funny little arrow pointing out of it, it's an object.
In summary: Objects are a load of variables and functions all bundled together.

This is a great resource and very-well stated. Lacking basics to tackle Drupal PHP is a real limitation for otherwise sophisticated designers.
Please consider a chapter 2, etc.
Right now I am theming a Drupal site and this was very helpful. At times I feel that I am building a house on sand.
Debbie
Glad it was useful - what would you like to see in chapter 2?
I'm particularly interested in how people have been learning Drupal - so if you could let me know roughly what your pathway has been - what resources have been useful, which haven't, places where you've got really stuck, "eureka" moments, that sort of thing - that would be a great help.
This was really helpful. I've done AS3 programming for Flash, but PHP has always been something that intimidated me. I'm a Graphic Designer, but I have also themed a few Drupal sites. I've been wanting to extend my theming power by actually learning how to override theme functions, or add in new variables to the themes that I have created. This article definitely covers all of the things that even basic PHP manuals assume the reader already knows. Thanks for the post :)
Hi most of this goes over my head but in terms of the conditional stuff. Where the two equal signs are "==" you said that means if, how does it know what the password is? Is it able to get it from a database or somewhere like that?
http://www.learmonts.co.uk
Have another look at the blog post: the two equals signs means "is the same as". And yes, usually the password would be stored in a database.
...on one of my blogs, a Penn State Sports site we built with similar methods in 2009. Very interesting.