Installing xhprof on XAMPP for OSX Lion

Directions adapted from Ben Buckman.

Download xhprof.

cd path/to/xhprof/.../extension

# If you don't have autoconf... I didn't.
sudo chmod o+w /usr/local/bin  #(brew needs to write a symlink there)
brew install autoconf

sudo /Applications/XAMPP/xamppfiles/bin/phpize

Make sure you have a CLI C compiler. I installed one via XCode.

sudo MACOSX_DEPLOYMENT_TARGET=10.6 CFLAGS='-O3 -fno-common -arch i386 -arch x86_64' LDFLAGS='-O3 -arch i386 -arch x86_64' CXXFLAGS='-O3 -fno-common -arch i386 -arch x86_64' ./configure --with-php-config=/Applications/XAMPP/xamppfiles/bin/php-config-5.3.1

sudo make

sudo make install

sudo nano /Applications/XAMPP/xamppfiles/etc/php.ini

Add these lines to php.ini:

[xhprof]
extension = xhprof.so
xhprof.output_dir = "/Applications/XAMPP/xhprof-logs"

Restart Apache.

Designing a Highly Reusable HTML Component

The UF College of Education uses a header/footer template designed to be applied to any page, and we use this across several applications such as WordPressMoodleElgg, and Drupal. Changes can be propagated quickly to all sites, and adding the template to new PHP apps is trivial.

If you need to create an HTML component that can be reused across a wide set of sites/apps, these guidelines might help.

Avoid HTML5 elements if you can

HTML5 elements like header must be accompanied by JS to fix compatibility in old browsers. Sticking to HTML4 also helps with validation under HTML4/XHTML doctypes. Of course, if you’ll only be deploying to HTML5 sites that already have the IE shim, go ahead and use the best markup elements for the job.

Guard the host markup against the component CSS

Any component CSS selectors that match host markup elements can cause massive problems in the host application, and if this component is applied across an entire site, it’s very difficult to predict the impact. The key then is following a few simple rules for the component CSS:

  1. Each class/id name must be sufficiently unique such that there’s practically no chance of name collision. Unfortunately even selectors like .hidden and .clearfix could be implemented in different ways in the host app and this could cause problems. Using a constant prefix in every name might help.
  2. Each selector must include at least one of the component classes/ids.
  3. Avoid using a CSS reset/normalizer. If you must, make sure each selector follows the above rules so the effect of this is limited in scope to the component.
  4. Selectors must not match non-component elements. E.g. the selector #component-root + div should not be used because it would select a DIV element after the component.
  5. Take care to avoid obscuring elements in the host page. E.g. negative margins could pull the component over a host element.

Guard the component markup against the host CSS

Similarly, host CSS could break the desired styling of the component markup.

  • Test the component in a wide variety of pages and applications. Especially test pages that use common CSS resets and normalizers, and that have a lot of element-only selectors in the CSS.
  • When interactions occur, make the affected element’s selector more specific until the component CSS “wins”. As always, test across the browsers you need to support; IE7 still has some specificity bugs for the selectors it understands, if you need to care about that.

Javascript Tips

Expose as little to the global namespace as possible

E.g., define all necessary functions and variables inside an anonymous function that is executed:

!function () {
  // your code here ...

  // explicitly expose an API
  this.myComponentAPI = api;
}();

Document your script’s dependencies and let the implementor supply those

Automatically including JS libraries may break the host app. Consider the case of jQuery: Many plugins extend the jQuery object, so redefining it removes those added functions (actually stores them away, but it will break the host app nonetheless). Don’t assume the user did this right. Wrap your functionality in a condition that first tests for the presence of the the library/specific features you need, and make it easy for the implementer to realize the problem if they have a console open.

Here’s an example of how to test for jQuery’s on function:

if (this.jQuery && jQuery.fn.on) {
  // code
} else if (this.console && console.log) {
  console.log('Requires jQuery.on, added in version 1.7');
}

Assume the component could be embedded after the page loads, and multiple times

Carefully consider the initialization process your component requires. In some cases it’s reasonable to leave the initialization to be triggered by the implementer. If you do automatically use DOMReady functions like jQuery’s ready(), consider allowing the implementer to cancel this and initialize later.

Helping Netbeans/PhpStorm with Autocomplete/Code-hinting

Where Netbeans can’t guess the type/existence of a local variable, you can tell it in a multiline comment:

/* @var $varName TypeName */

After this comment (and as long as TypeName is defined in your project/project’s include path), when you start to type $varName, Netbeans will offer to autocomplete it, and will offer TypeName method/property suggestions. If you rename the variable with Ctrl+r (rename refactoring), Netbeans will change the comment, too.

I usually forget this syntax because type comes first in @param declarations.

Update: PhpStorm supports a similar syntax, but reversing the type and variable name:

/* @var TypeName $varName */

Bash: Resolve symlinks in your working directory

Say you have created a symlink from your home dir to another location:

$ ln -s /Applications/XAMPP/xamppfiles/htdocs ~/htdocs

Now you can easily change to the XAMPP htdocs: cd ~/htdocs and then get back home: cd ..

But how do you get to xamppfiles?

Update: Thanks to sapphirepaw, the solution is simple: cd -P htdocs/.. or to resolve your current wd: cd -P .

Less optimal methods follow:

The secret is pwd -P, which outputs your “real” working directory with symlinks resolved. By escaping this with $(...), we can include this in a cd command:

$ cd $(pwd -P)  # change working directory to the real current path.

So to get to xamppfiles from home:

$ cd htdocs $ cd $(pwd -P)/..

Filtering WordPress Navigation Menus

WordPress 3 introduced native navigation menus, usually created via the wp_nav_menu theme function and the built-in Custom Menu widget.  If you have a menu with a deep hierarchy, you may want to display only the active branch and the submenu directly below the active item (given class “current-menu-item” by WordPress). You can see this menu behavior on the left in the UF College of Education Faculty site.

This is sadly not doable with CSS. I originally did it with Javascript, but the requirements of progressive enhancement required that the whole menu be output before attacking the DOM. Depending on the page, this caused a distracting collapse of the menu during the layout.

The class Coewp_MenuFilter does this menu filtering server-side. Until I wrap this in a plugin, just put it in your theme folder:

// in functions.php
require dirname(__FILE__) . '/MenuFilter.php';
Coewp_MenuFilter::add();

How it works

add() attaches a filter to the “wp_nav_menu” hook, so WordPress passes menu HTML through the class’s filter() method before returning it in wp_nav_menu(). In filter(), the HTML is converted to a DOMDocument object, which is edited using DOM methods (with XPath available, this version was almost a direct port of the jQuery version). After cutting it down, the DOM tree is re-serialized to HTML.

I was really hoping this filtering could be done before the HTML was created, say by subclassing WP’s Walker_Nav_Menu class, but this proved difficult to debug.

Using jQuery Before It’s Loaded

It’s better to include scripts like jQuery at the end of the BODY, but this makes its methods inaccessible earlier in the page (e.g. inside a WordPress post). What you can do is use a script like the one below to queue DOMReady functions before jQuery loads.

(function (w) {
    if (w.$) // jQuery already loaded, we don't need this script
        return;
    var _funcs = [];
    w.$ = function (f) { // add functions to a queue
        _funcs.push(f);
    };
    w.defer$ = function () { // move the queue to jQuery's DOMReady
        while (f = _funcs.shift())
            $(f);
    };
})(window);

Minified:

Setup

  1. Link to the script in the HEAD or at least before your typical page content area
  2. Link to jQuery at the end of BODY
  3. Below jQuery, include: <script>defer$()</script>

Now in the BODY you can use $(function(){ ... }); to queue up a function as if jQuery were already loaded. And, thanks to the fact that Javascript identifiers are referenced at run-time, you can call any other jQuery functions inside your queued function.

With some modifications you can use this pattern for any library with a similar DOMReady implementation.

Tiny Email Munging Script

I’ve seen a lot of these that are bloated/less effective/inaccessible, so I might as well put this out there. It’s simple enough to modify if you’re comfortable with Javascript.

Markup: <a href="mailto:john{@}example{.}org">john{@}example{.}org</a>

(function(){
  var a, i = 0, o = this.onload;
  onload = function(){
    o && o(); // run the old window.onload if existed
    while (a = document.getElementsByTagName("a").item(i++))
      if (0 == a.href.indexOf("mailto:")) {
        a.href = a.href.replace(/[{}]/g, "");
        a.innerHTML = a.innerHTML.replace(/{(.)}/g, "$1");
      }
  };
})();

Minified 234B:

for jQuery 150B:

A Zend Framework App in a Single File

Most PHP micro-frameworks I’ve reviewed have some major cons: incomplete namespacing of functions/classes/global vars; doing too much/little; being under-tested; and the worst: forcing a unique (and usually under-documented) code structure that will make it difficult to “graduate” an app into a more full-featured framework. It also seems silly to rely on “micro-optimized” code if performance isn’t your number one goal and you have well-tested libraries sitting around.

So over the weekend, as a proof of concept (and mostly to get better acquainted with ZF’s MVC implementation), I built some minimal classes allowing one to implement a “quick and dirty” Zend Framework MVC app in a single script, with the resulting abomination being relatively easy to convert to a full app. The README shows how such a script might look. Continue reading  

StackExchange folks, KeyMinor already exists

Why is there a StackExchange proposal in the works for a “Musical Practice and Performance site” when KeyMinor already exists on the SE platform?

The proposed site is “for people who play musical instruments. On-topic questions will be about technique, practice, theory, composition, and repertoire.” KeyMinor already serves this purpose, it’s just not known about.

I’d add a comment to the proposal but I see no way to; I probably don’t have sufficient reputation points.