— tomauger.com

One of the aspects of PHP that students find really baffling is the challenge of mixing HTML markup with PHP content. In this tutorial I will attempt to demystify the HTML + PHP mashup with step by step examples. This tutorial was painstakingly written for my Centennial GMD 304 students, but if it’s useful to you in any way, so much the better!

Roles

HTML is used for markup and static content; PHP is used for content that could change and for repeating content.

For example, suppose you wanted display an article (like a WordPress post). The markup might be an H1 tag for the title of the post, and then P tags for each paragraph of the post content. You would use HTML to markup the title and the post content. But the title and content might change, and are coming from the database, so it is up to PHP to insert them. Take a look at the following sample article:


Sample Post Title

This is sample body content. Each paragraph must be wrapped in its own P tag.

Here is another sample paragraph which must be wrapped in yet another P tag.


That’s how we want our articles to be output in the browser. The challenge for someone who’s not coding HTML every single day is to visualize this in terms if the HTML markup needed. To do that, you need to study the source code of your HTML output. In the above example, the source looks like this:

<h1>Sample Post Title<\h1>

<p>This is sample body content. Each paragraph must be wrapped in its own P tag.<\p>

<p>Here is another sample paragraph which must be wrapped in yet another P tag.<\p>

You have to remain aware of this markup as you’re writing your PHP. You need to be very rational about the order of things, so you know when to insert your HTML markup, and when to insert your PHP content.

HTML and PHP sequencing

It’s important to have an idea ahead of time, of where your markup should go. For example, you might think about the order of the markup from the previous sample article in this way:

  • first, open an H1 heading tag
  • then, insert the article title
  • then, close the H1 heading tag
  • now, for each paragraph of your article content:
    • open a P paragraph tag
    • insert one paragraph of content using PHP
    • close the P paragraph tag
    • move on to the next paragraph and do it again.

So, now let’s look at how we mix HTML and PHP.

Mixing HTML and PHP

There are a number of strategies when it comes to mixing your markup, your static text, and your variable or conditional content (PHP content). The two most popular approaches are:

  1. ‘echo’ all the things
  2. Output HTML as HTML and PHP as PHP.

Let’s take a closer look at these two approaches.

Echo all the things

In this approach, everything is done inside the <?php ... ?> tags, so every line of code must be valid PHP. This includes any HTML that you might need to output. In PHP the way you output stuff is to use the echo keyword. Once again, this includes HTML.

Before we go any further, review what you already should know about echoing in PHP:

  • echo a variable using echo $my_variable;
  • that variable must be scalar (ie: not an array)
  • anything that is not a variable must be wrapped in quotes like this: echo "Hello World!";
  • this is also true for HTML: echo "<h1>My Heading</h1>";
  • these are called “string literals
  • you can echo multiple things using multiple echo statements. PHP does not insert white space or line breaks between echo statements, which may be a bit disappointing at first, but is actually helpful in the end
  • you can echo multiple things by separating them with commas: echo "Hello", " ", "World";
  • you can mix and match string literals and variables this way too: echo "Hello ", $name;
  • alternatively, strings can be concatenated (smushed together) using the . concatenation operator: echo "Hello " . $name;
  • finally, you can use variables within your quotes and PHP is smart enough to replace the variable name with the actual variable contents: echo "Hello $name";
  • this variable “expansion” described above only works in double quotes ("); anything inside single quotes is output literally

So, back to “Echo all the things”. In the example we have been working with so far, we have an article title and the article content. Let’s say we have stored the title in a PHP variable called $title and the article content inside $content.

Refer to the section called “HTML and PHP sequencing”, above. If you wanted to reproduce those steps exactly using the “echo” method, echoing your HTML within quotation marks, and inserting your PHP variables at the appropriate places, how would you proceed?

I suggest you try to work it out on your own right now before looking further. Skip back up to the HTML and PHP sequencing section and re-read the sequence of things we want to output, until you completely comprehend it to the point of being able to explain it to someone else.

If you have a clear idea in your mind about the sequence in which your HTML and PHP should be output, the actual code should be easy.

Got it? Okay, here’s the most literal translation of the sequence described in the HTML and PHP sequencing section, using the echo all the things method:

<?php
    echo "<h1>”;
    echo $title;
    echo ”</h1>”;

    echo "<p>”;
    echo $content;
    echo ”</p>";
?>

Or, you can do it more compactly:

<?php
    echo "<h1>", $title, "</h1>";
    echo "<p>”, $content, "</p>";
?>

And, my personal favourite:

<?php
    echo "<h1>$title</h1>";
    echo "<p>$content</p>";
?>

All are equally valid approaches. The one that works for you is whichever one that makes the most sense to you. It’s the one that you can use every time and not feel confused. It’s a matter of personal taste and none are “wrong”.

As long as you are outputting valid HTML.

HTML as HTML

The alternative approach to echo all the things is to output HTML as HTML and PHP as PHP. If you use this technique, your HTML is just plain ol’ HTML, just like you used to do it when you were using Dreamweaver to code static sites. HTML remains outside any <?php ... ?> tags and so you do not have to echo it – just type it in the way you want it to appear in your browser.

This is because even though the file may have a .php extension, it’s still a .html file except the parts inside <?php ... ?> tags. You only need to worry about using echo within the <?php ... ?> sections.

To see how this approach is different from the echo all the things approach, see the sample code below, which ought to have the same result in the browser as the previous examples.

<h1>
    <?php echo $title; ?>
</h1>
<p>
    <?php echo $content; ?>
</p>

Differences between the two approaches

In the first approach, you’re doing a lot of echoing, and you need to remember to carefully watch your use of quotation marks (“).

In the second approach, you find yourself with a lot of <?php ... ?> blocks, and you still have to remember to echo within those sections.

There should be virtually no performance difference between the two approaches. It comes down to personal style, and what you are looking to emphasize:

  • echo all the things places the emphasis on your PHP. If you have a lot of loops, if statements or other programming logic, with a little bit of HTML, this is the way to go as it will make your code a lot more readable.
  • HTML as HTML and PHP as PHP puts the focus on your HTML structure, and is useful if you have a little bit of PHP that you can conveniently insert into your HTML structure by echoing simple variables or functions.

Which to use?

The choice is yours. For customizing WordPress template files, most people find that the HTML as HTML approach is the most readable. This is because WordPress provides lots of very helpful “template functions” that insert the content you want using function names that are very descriptive, such as the_title() and the_content(). These functions also handle the echoing part, too, which makes your code even more readable. Below is the same example as above, but this time, using the WordPress template functions:

<h1><?php the_title(); ?></h1>
<p><?php the_content(); ?></p>

Sweet, huh?

On the other hand, if you’re not working in WordPress, and you want to focus on your PHP, then I strongly recommend the echo all the things approach, particularly if you are dealing with loops and/or conditional statements.

Arguably, this method is a little harder and requires a bit more thought around your quotation marks, and your HTML structure is a little obfuscated. But in my opinion, if you’re here to learn PHP, you should be focusing on your PHP. So for the rest of this tutorial, I’ll be using the echo all the things approach in all my examples.

Validating your Markup

And as you test your PHP, you need to verify that your markup is correct, too. These days, modern browsers are pretty smart about fixing badly formed markup, so even horribly broken markup code might end up looking exactly right on the screen.

For example, in-class, I recently saw (a lot of) the following HTML output:

<ul><li>Item 1</li></ul>
<ul><li>Item 2</li></ul>
<ul><li>Item 3</li></ul>

This is almost always wrong, since in HTML a list (ordered or unordered) consists of a list container (the <ul>) and then a number of list items (the <li>). What is almost certainly wanted in this case is:

<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>

However, if all you are doing is looking at your output in the browser window, chances are you’ll probably see more or less the same result, regardless of the structure:


  • Item 1
  • Item 2
  • Item 3

For better or for worse, modern web browsers can generally figure out what you meant and will do their best to close open tags, fix nesting issues and otherwise clean up rogue markup. The problem is not so much the browser, as what happens with other consumers of your content, such as Google Search indexers, RSS feed syndicators and Assistive Technologies used by persons with disablities. Nowadays you have a very real responsibility toward creating valid and semantically correct markup, so you need to take charge of your testing.

To catch markup blunders, you have to get into the discipline of using View Source in your browser to see the actual HTML markup that gets generated by your program. If your browser doesn’t feature the ability to view a given page’s source HTML, it’s time to switch browsers. Google Chrome and Firefox both have this feature, as does Internet Explorer on Windows. For most browsers, just right-click on an empty part of your website in your browser window, and select “View Source” from the context menu that appears.

Loops and Other Complex Structures

It’s the complex structures such as loops that really cause the confusion with all this, so that’s what I want to focus on for the rest of this tutorial.

At the end of the day, however, no matter how complex the structure, all you really need to do is follow these steps:

  1. Understand what you’re outputting
  2. Determine the correct, semantic, HTML structure for this output
  3. Write out, in plain language, the sequence of markup and content that you need to output
  4. Pick an HTML+PHP mashup method (echo all the things or HTML as HTML)
  5. Code it out.

By the time you’ve gotten to #5, the code should practically write itself. At least as far as your markup is concerned. Figuring out your PHP logic is another thing altogether, but that’s not the scope of this tutorial.

Single Loop Example

It’s always best to code by example, so let’s imagine a simple scenario:

You have a catalog of books. Your code should list each book title, along with the author, the publisher and the published date.

Okay, let’s go through the steps outlined above and see if it’s really as easy as I claim.

1. Understand what you’re outputting

Re-read the description of the example again. Are you clear about what we’ll be outputting? A visual example is always good in these circumstances:


The Lord of the Rings

J.R.R. Tolkien, Unwin and co., 1954

How the Grinch Stole Christmas

Dr. Seuss, Random House, 1957

The Year Without Pants

Scott Berkum, Jossey-Bass, 2013


You get the picture.

2. Determine the correct HTML structure

The first question you need to ask yourself if: “is this a list?”. Is this output a collection of repeating, similarly-themed and similarly-structured content? If so, it’s a list. If it’s a list, is the sequence critical and/or number of items important? Then it should be an ordered list, if not, an unordered list.

Almost all content that gets output using a loop in PHP should be expressed as an HTML list. Let’s review the two list structures that HTML provides:

<!-- unordered list (bullet list) -->
<ul>
    <li>List Item</li>
    <li>List Item</li>
    <li>etc...</li>
</ul>

<!-- ordered list (numbered list) -->
<ol>
    <li>List Item</li>
    <li>List Item</li>
    <li>etc...</li>
</ol>

The next question is, “is there a heading in all of this?”. And if there is, which level of heading is correct?

If you determine that something can act as a heading, then the level is usually one level lower than whatever level you’re currently in. Since the title of most pages is usually contained within an H1 tag, you’re stuck with H2 or greater.

Finally, how will you express the rest of the content? Is there some further structure that should be recognized, or is it all just paragraph text after that? A frequently-overlooked HTML structure is the definition list <dl><dt>Label</dt><dd>Value</dd></dl> structure that is perfect for expressing any set of data that has a label and a value.

In this example we’ll keep things simple. We’ll just use an H1 for the title of the book, and then a single P tag for the rest of the book meta data.

The HTML structure for this example

Okay, so using the criteria above:

Is this a list? Yes.

Is it ordered or unordered? Unordered – if there’s no compelling reason to make it an ordered (numbered) list, then it’s just an unordered list.

Is there a heading? Sure. Let’s use the book title as a heading.

What about the rest of the content? We’ll just stick it all inside a single P tag for now.

Okay, so let’s see some sample markup:

<ul>
    <li>
        <h1>The Lord of the Rings</h1>
        <p>J.R.R. Tolkien, Unwin and co., 1954</p>
    </li>

    <li>
        <h1>How the Grinch Stole Christmas</h1>
        <p>Dr. Seuss, Random House, 1957</p>
    </li>

    <li>
        <h1>The Year Without Pants</h1>
        <p>Scott Berkum, Jossey-Bass, 2013</p>
    </li>
</ul>

3. Write out the sequence

All right, this is probably the most important part of the process: writing out the plain-language version. Why? Because it’s the part where you get to internalize the structure. It’s not “out there” anymore. It’s inside your head, the way the location of your house is in your head. If someone asked for directions on how to get to your house, you could tell them, right? And more importantly, they would understand your instructions. You wouldn’t even need to think about it that much – you would have a “picture” in your head of where you house was in relation to the major intersections, and you would just walk through that picture in your head as you explain the directions to get there.

Well, the same needs to be true for your HTML structure. If you can’t explain it to someone else, or even to yourself, you really shouldn’t even move past this step until you can. There’s no point trying to code to an unknown target. It’s a complete waste of time and energy. This is actually true for just about every coding task, but let’s just stay focused on HTML structure.

Let’s write out the sequence for this example. I strongly encourage you to try to work this out for yourself first, before looking at the solution, below.

All right, here’s the sequence:

  1. Start an unordered list (UL). (All the book listing items will be contained in this list)
  2. For each book in the list we need to:
    • Open a List Item tag (LI)
    • Output the title:
      • Open a heading (H1) tag
      • Output the title of the book
      • Close the heading (H1) tag
    • Output the rest of the content:
      • Open a P tag
      • Output the Author
      • Output a comma and a space (“, “)
      • Output the Publisher
      • Output another comma and space (“, “)
      • Output the year
      • Close the P tag
    • Keep looping through each book in the list
  3. After the loop is all done, close the unordered list (UL) tag

4 & 5. Code it out (using the “echo all the things” method)

Okay, now that you’ve really thought the markup and the sequence out, this should be the easy part! To start, let’s decide that we have all of our book data stored in an array called $books. It looks like this:

<?php
    $books = array (
        array( "title" => "The Lord of the Rings", "author" => "J.R.R. Tolkien", 
                "publisher" => "Unwin and co.", "published_date" => 1954 ),
        array( "title" => "How the Grinch Stole Christmas", "author" => "Dr. Seuss",
                "publisher" => "Random House", "published_date" => 1957 ),
        array( "title" => "The Year Without Pants", "author" => "Scott Berkum",
                "publisher" => "Jossey-Bass", "published_date" => 2013 )
    );

So, it’s a regular array (a list) of books, and each array item is an associative array (a record) of a specific book.

To access the first book we could use: $book = $books[0]; and then to get the publisher of that book, we would reference the appropriate key, like this: echo $book['publisher'];. To loop through all our books, foreach is the best structure, and the most logical variable naming is: foreach( $books as $book ){ // ... }. One at a time, each book’s record (associative array) is copied into $book. Then you use the appropriate key to get at the book data you want.

<?php
    // Before we start the loop, start the unordered list
    echo "<ul>";

    // Now, lets loop through our $books array, copying each book's data to $book.
    foreach( $books as $book ){
        // $book is now an associative array that has the following keys:
        // "title", "author", "publisher" and "published_date".

        // Each book in our list is a list item, so before we list the book data,
        // open a list item tag:
        echo "<li>";

        // Now for the title. Wrap it in an H1 tag as per our sequence above:
        echo "<h1>";
        echo $book['title'];
        echo "</h1>";

        // We could also have written it this way:
        // echo "<h1>", $book['title'], "</h1>";
        // Or this way:
        // echo "<h1>" . $book['title'] . "</h1>";
        // Or the most compact way:
        // echo "<h1>{$book['title']}</h1>";

        // Now let's output the rest of the book data, inside a P tag
        // and separated with commas.
        echo "<p>";
        echo $book['author'];
        echo ", ";
        echo $book['publisher'];
        echo ", ";
        echo $book['published_date'];
        echo "</p>";

        // That's it for this book's listing, so close the list item
        echo "</li>";
    }

    // That's it for the loop. By the time our program gets to this line, it will
    // have looped through every single book in our list of books, so it's time
    // to close off the unordered list tag:
    echo "</ul>";

    // And we're done.
?>

The things to pay attention to in the example above are the placement of the <ul>, <li>, </li> and </ul> tags with respect to the foreach loop.

  • The <ul> must happen before the loop is declared, so before the foreach.
  • The <li> must happen inside the loop, but before any other HTML or content is output.
  • The </li> happens inside the loop, but after all the other content is output.
  • The </ul> must come after the end of the loop block, to properly terminate the HTML unordered list element.

Nested Loops

If you understand everything I’ve talked about above, then nested loops should not really pose much of a problem for you. The HTML markup gets a little more complex, and you really need to remain focused and aware of where you are within the structure as you’re writing your code. Good indentation practices will really help here, so don’t be lazy! Indents are your friend when it comes to coding, especially as a beginner. Don’t make your life harder than it needs to be by wimping out on hitting the Tab key one more time. It’s really not that much extra work, and it pays big dividends every time.

The term “nested loop” means that while you’re inside a loop, listing through some items, the item you’re listing contains, itself, a list of items, which you need to loop through.

We can easily rewrite our book example to feature a nested loop. Here’s the revised HTML structure:

<ul>
    <li>
        <h1>The Lord of the Rings</h1>
        <ul>
            <li>Author: J.R.R. Tolkien</li>
            <li>Publisher: Unwin and co.</li>
            <li>Published Date: 1954</li>
        </ul>
    </li>

    <li>
        <h1>How the Grinch Stole Christmas</h1>
        <ul>
            <li>Author: Dr. Seuss</li>
            <li>Publisher: Random House</li>
            <li>Published Date: 1957</li>
        </ul>
    </li>

    <li>
        <h1>The Year Without Pants</h1>
        <ul>
            <li>Author: Scott Berkum</li>
            <li>Publisher: Jossey-Bass</li>
            <li>Published Date: 2013</li>
        </ul>
    </li>
</ul>

In this structure we have:

  • an “Outer” list, which is an unordered list
  • 3 list items, corresponding to the 3 books in our “database”
  • For each of those list items, we have a nested unordered list
  • which has 3 list items: author, publisher and published date.

Understanding and appropriating this HTML structure is critical if you want to move forward. Study it carefully, especially the parts which close off the list item or the list itself.

Also notice how the indenting is extremely helpful for grokking the structure. You can clearly see what items are contained within lists of their own. We’re going to use the same indenting in our PHP code to help keep this clarity.

Sequence

Let’s work it out in plain language before attacking the code:

  1. Start with an outer UL
  2. For each book in our list:
    • Output an LI
    • Output an H1
    • Output the title
    • Start a new (inner) UL
    • For each piece of book data (other than the title):
      • Output an LI
      • List the key (Author, Publisher or Published Date)
      • Output a colon and a space (“: “)
      • Output the value
      • Close the LI
    • Close the UL
    • Close the LI
  3. Close the outer UL

Code

You should be able to work this out yourself. I strongly encourage you to do so, because it’s by doing that you learn. Use the code below to check your work.

<?php
    // Still using the $books array from the previous example

    // Start the outer list
    echo "<ul>";

    // Loop through our books, as we did before
    foreach( $books as $book ){

        // Start the list item
        echo "<li>";

        // And do the title as before
        echo "<h1>";
        echo $book['title'];
        echo "</h1>";

        // Now, the inner loop
        echo "<ul>";

            // We should indent to help us keep our code straight
            echo "<li>";
            echo "Author: ", $book['author'];
            echo "</li>";

            echo "<li>";
            echo "Publisher: ", $book['publisher'];
            echo "</li>";

            echo "<li>";
            echo "Published Date: ", $book['published_date'];
            echo "</li>";

        // Close off this list
        echo "</ul>";

        // This whole list is inside the "book" list item, so close that too
        echo "</li>";
    }

    // Outside the loop, close off our outer unordered list
    echo "</ul>";
?>

Optimizations

There are some optimizations we could do. For example, hard-coding the inner loop is not only a pain, but also means that if the data ever changes (like we add a new data point such as “price”), we have to rewrite our code to include the new data item. Take a look at this first attempt at replacing the hard-coded inner loop with another foreach inner loop:

<?php
    echo "<ul>";

    foreach( $books as $book ){
        echo "<li>";

        echo "<h1>";
        echo $book['title'];
        echo "</h1>";

        // Now, the inner loop
        echo "<ul>";

        // Loop through each of the data items within the $book record.
        foreach ( $book as $key => $value ){

            // The only trick here is that we have to avoid re-outputting the title,
            // since we already did that earlier. So we need to check that the current
            // key is not the title. If it is, we skip outputting it entirely and
            // move on to the next key in the loop.

            if ( 'title' != $key ){
                echo "<li>";
                echo $key, ": ", $value;
                echo "</li>";
            }
        }

        echo "</ul>";
        echo "</li>";
    }

    echo "</ul>";
?>

This is pretty cool, and saves some manual coding. The output isn’t quite as nice since the $key is being output directly. We can solve this with a little string manipulation:

<?php
    echo "<ul>";

    foreach( $books as $book ){
        echo "<li>";

        echo "<h1>";
        echo $book['title'];
        echo "</h1>";

        echo "<ul>";

        foreach ( $book as $key => $value ){
            if ( 'title' != $key ){
                // Replace underscores with regular spaces
                // and then make the first letter of each word upper case.
                $pretty_key = ucwords( str_replace( "_", " ", $key ) );

                echo "<li>";
                echo $pretty_key, ": ", $value;
                echo "</li>";
            }
        }

        echo "</ul>";
        echo "</li>";
    }

    echo "</ul>";
?>

Conclusion

I hope this has helped demystify the “mashup” of HTML markup and PHP output. As you work through your own programming challenges remember:

  • Be sure you comprehend the appropriate HTML structure first before trying to add PHP
  • Take the time to understand the sequence of HTML and PHP output
  • Decide how you want to mix HTML in with your PHP: the echo all the things approach or the HTML as HTML approach.
  • Pay close attention to loops, especially where list elements and list items are concerned.
  • Check your work using view source because your browser may lie to you (trying to be helpful).
Read More

This was an awesome tip courtesy of Dan at WiredTree. Use case: you have a dev server and a production server and something goes pear-shaped on the live site. You can’t reproduce the problem on the dev server even though they are ostensibly identical. Where are the differences?

cd /path/to/dir_1/ ; find ./ -name "*.php" -print -exec diff {} /path/to/dir_2/{} \; 
Read More

This fall, I’m excited to be teaching “Development for Designers”, part of the program at Centennial College in Toronto Canada. This blog post is my introduction to the course, and outlines my objectives, approach and some of the key learning outcomes.

This post is primarily targeted at the registered students for this course, but may be of interest to other learners who may wish to follow my blog posts and improve their own development skills.

Read More

Okay, my JavaScript isn’t that strong yet – that is to say, my full comprehension and usage of the characteristics and idiosyncrasies of a prototypal language. But I ran into this pattern today that I just have to write down because it’s so cool.

I run into this a lot in, for example, PHP programming, where you want to use a function multiple times, but there are some computationally-heavy operations the function has to do, the results of which won’t change for the scope of the function (usually the execution of the script).

Read More

There are a number of reasons why you might get this error, including not declaring stage instances, mis-spelling a class name, or using the wrong class when declaring stage instances.

The one I found that was stumping me had to do with Exporting for ActionScript. A MovieClip was assigned a Class corresponding to an AS3 class – eg: view.MyClip. Then, in a class corresponding to that clip’s parent MovieClip, I declared a var like this `var myClip:MyClip;`.

The very act of declaring this variable in a parent MovieClip prevented MyClip from properly instantiating. I think the ReferenceError is actually just plain wrong.

At any rate, the solution was to assign view.MyClip to the Base Class, not to the Class in the Export for ActionScript properties. Problem solved. Fuck me. 2 hours wasted.

Read More

lava_progress

See that wicked progress bar above filled with… what? Orange Crush? Let’s call it the Waponi Woo UI. This element above is created entirely using the Layer f/x using only 2 layers for the effect (+ 2 more layers to create the animated bubbles). Many techniques and tutorials that you’ll find lurking around the Interwebs totally (in my opinion) “cheat” by drawing vector shapes for highlights or reflections or other visual features needed to pull off the effect. You know what? That’s totally bogus.

This is essential when you’re creating a series of UI elements you want to only use effects that can be 100% automated and scaled so that you can apply the same f/x to all your UI elements consistently and don’t need to hand-draw, paint or otherwise create artwork to fit the individual shapes of your UI elements. If the layout requires that you resize an element, it just happens, without any fiddling or re-creating artwork. It’s just plain smart workflow.

If you’re just looking to create the effect above, I have created a series of video tutorials that recreate the exact UI above. Visit my YouTube channel (see video, below), or you can find them all right here in this post.

Okay, maybe you can’t do absolutely everything with layer f/x – there are limitations, of course. But I guarantee that you are not using Photoshop’s layer f/x to their full potential. In this series of articles, which have been a very long time coming, I’m going to focus on breaking down the preconceptions about the roles of each of the effects available in the f/x menu and hopefully throw open the lid of Pandora’s box for you so you can really start flexing some Photoshop muscle.

Read More

I’ve been using $.Deferred in a few recent things I’ve done with jQuery and it solves a lot of problems that used to be kind of a big deal.

I won’t go into details about the jQuery Deferred object because there’s a ton already out there on it. Suffice to say that everything centers around Promise objects that can fire off events as they resolve. These events only fire off once and then the Promise object is basically used up.

What’s cool about all this is the $.when() method, that takes an array of Promise objects and returns basically a “master” Promise object that only resolves when all of the Promise objects passed to it have resolved. This is an awesome way to do a whole bunch of things asynchronously (ajax calls, image.onload callbacks, animation complete callbacks) where you still would like to be notified when and only when they are ALL done.

It’s pretty easy to do, too.

Read More
yum install subversion

would be the way to go, but sadly yum only has subversion 1.6.x. So we unyum and then manually build subversion ourselves. This includes the steps for making the Apache Runtime and Apache Runtime Tools libraries required by subversion.

1. From command line (logged in as root) yum remove subversion
2. cd /usr/local/src
3. In a web browser, visit http://subversion.apache.org/download/, and find the latest version. Find the URL for the .tar.gz version. Copy that
4. Back on your command line wget [paste URL here]
5. tar -xzf subversion-1.x.x.tar.gz
6. cd subversion1-1.x.x

Before we configure subversion, we need to install the Apache Runtime library and Apache Runtime Utils.
7. In a web browser, visit http://apr.apache.org/download.cgi
8. using wget, get the best versions of APR and APR-util: wget [paste APR URL here], wget [paste APR-util URL here]
9. Untar both of them: tar -xzf apr-1.x.x and tar -xzf apr-util-1.x.x

Now we have to compile APR and APR-util
10. First, compile APR.
11. cd apr-1.x.x
12. ./configure
13. make
14. make install

Now we have to compile APR-util and give it a reference to APR
15. cd ../apr-util-1.x.x
16. ./configure --with-apr=../apr-1.x.x
17. make and make install

Finally, we can compile subversion
18. cd ../
19. ./configure --with-apr=apr-1.x.x --with-apr-util=apr-util-1.x.x
20. make (grab a coffee) and make install

Verify our version
21. svn --version

Read More

Don’t ask, but I started to get paranoid about my usual way of calculating a random number range (e.g.: -20..+20) of negative to positive numbers in JavaScript.

I use:

let x be the range on both sides ( -x .. x )

Math.random() x * 2 – x;

Anyway, I just wanted to prove that this was not weighted more on 1 side than the other, so I learned about mean (average) and median (the middle number) and wrote this little test:

	var nums = [],
		max = 0,
		min = 1000,
		sum = 0;
	for ( var i = 0; i < 1000000; ++i ){
		var n = Math.random()* 2 - 1;
		nums.push( n )
		max = Math.max(n, max );
		min = Math.min(n, min);
		sum += n;
	}
	console.log( "max: " + max );
	console.log( "min: " + min );
	console.log( "i: " + i );
	console.log( "mean: " + sum / i );
	var mid = nums.sort( function( a, b){ return a - b } ).length / 2;
	var med = mid % 2 ? nums[mid] : (nums[mid-1] + nums[mid] / 2 );
	console.log( "median: " + med );

 

Read More

It’s pretty cool that whenever you’re writing on your (or someone else’s) timeline in Facebook, Facebook goes off and fetches a (usually) appropriate thumbnail image to use that adds a splash of colour to your post, and also visually identifies the site in question.

If that site is your site, however, you may want a greater degree of control over what image Facebook chooses. By default, Facebook trolls your site’s home page for IMG tags and background-images in your CSS and pulls them out, offering them each as options to the person posting the link.

To see what images facebook will offer up for your site, use the following link:

http://developers.facebook.com/tools/debug

Read More

blending_opts_1Yeah, these suckers here. You know, there’s not a lot that I don’t know in Adobe Photoshop, but every so often I come across something that I’ve been, well, avoiding to have to learn properly. Something I’ve always been able to muddle through without really understanding the why and the wherefore. Not often. And I hate when it happens. The layer Advanced Blending Options has been one such thorn, and in a recent UI experiment that I document with some video tutorials, I hit the wall and had to mess around randomly with these options until I found the magic combination and permutation that actually worked. I was content. Until I had to do said video tutorials. That’s where I look like a fool if I can’t explain something properly. “Don’t be an ass,” I said to myself. “You either know or you don’t. Don’t fake it.”

So I turned to Google. And you know what? no-one (least of all Adobe) had a satisfactory explanation for the phenomenon I was experiencing. Was it a bug? Unlikely. So I had to figure it out the hard way. I’m documenting my findings here, to create the definitive record on the web for how this shit works. I can only hope that my SEO + your Google-fu gets you to this article when you’re in need of enlightenment.

Read More

Just posted a bunch of new videos to my YouTube tutorial channel, so why don’t you check ‘em out and give your Photoshop skillz a mad boost?

(more after the break, or just subscribe to my YouTube channel for updates!)

Read More