Code / Appnel Solutions 

Posted
21 September 2007 @ 3pm

Template Context Variables Now Stashed In Lowercase

The following is a slightly edited fun “rant” I posted to the mt-dev list while working on my existing plugins and MT4 during its beta a couple of months ago.

While my “rant” was meant to be a bit of fun that let me blow off some steam there are two points worth noting:

  • Beginning with MT4, template variables are stored in lowercase and are case insensitive.
  • This is a classic case of why object-oriented (OO) principles is necessary in sophisticated applications over its lifecyle. Actually this is more of an example of how not following OO principles will sooner or later cause you grief. So the next time you are wondering why I’m being a grouch about something not following OO principles, see this post.

(Tim steps up to the virtual water cooler and begins…)

One of the toughest part of dealing with major restructuring of an app like MT4 is figuring out of the bug in your plugin or the test suite.

So here is one I’ve just spent the last couple of hours figuring out that effected my test suite: context variables in MT4 are converted to lowercase before being stored.

I was doing something like this in a tag handler…

} elsif (defined $args->{var}) {
     return $ctx->{__stash}{vars}{$args->{var}};
}

This works fine in MT 3.3. However MT4 introduces a var method in the context object (fine) and converts all keys to lower case (uh-oh). When setting a variable with the MTSetVar or MTSetVarBlock tags it uses the var method. My test suite tags being written back in MT 3.x days does not. So if you are using uppercase characters to access a variable in your code like I was it returns undef and get an error.

In order to maintain compatibility with MT 3 and 4 you have to do something like this:

} elsif (defined $args->{var}) {
    return MT->version_number() < 4
         ? $ctx->{__stash}{vars}{$args->{var}}
         : $ctx->var($args->{var});
}

This is PRECISELY why I dislike using hash keys instead of methods so much. (This is what OO folks refer to as encapsulation.) You can change the implementation of a method all you want as long as it takes the same input and dishes out the same outputs.

Had the var method existed in MT 3.x, MT could be stashing variables in $ctx->{__vars} or $ctx->{'hooray_for_flexibility!!!!'} or anything else and it wouldn’t matter to a developer or their code. You would drop in a key name to the var method and it would know how variables had been stored and how to correctly retrieve them. No breaks. No problems. No wasted time.

(Downs his water, crumples his cup up and dunks it in the trash can before heading back to his desk.)



There are no comments yet. You could be the first!

Leave a Comment

← Before After →