MODX Snippet Development IV

In the last article, we cleaned up our code and gave the snippet a single exMODX logoit point. But there’s still a problem with the design. We’ll fix that in this article and begin adding some features that improve the snippet’s flexibility.

Starting Point

For reference here’s where we left off in the last article:

[code language=”php”]
/* NewResource snippet */

/* Default return value */
$output = ”;

/* Return value for new resources that are published */
$newOutput = ‘<span class="new_resource">NEW!</span>’;

/* Set $interval as the number of seconds in two weeks */
$interval = 1209600;

/* See if the resource is published */
$published = $modx->resource->get(‘published’);

/* See if publication date is within the last two weeks */
if ($published) {
/* Get the current time as a timestamp */
$currentTime = time();

/* Get the publishedon date (if any) and
convert it to a unix timestamp */
$ptime = strtotime($modx->resource->get(‘publishedon’));

/* Get the resource’s age in seconds */
$age = $currentTime – $ptime;

if ($age < $interval) {
/* Yes, it’s recent – return NEW! */
$output = $newOutput;
}
}

return $output;
[/code]

It’s a Sin

Coders will argue about whether is a mortal sin, a venial sin, or a cardinal sin, but most will agree that it’s a sin to mix code and content together. PHP code is about making decisions and controlling the flow of the program. Theoretically, in a well-designed snippet, there shouldn’t be any HTML or actual content. I don’t really like the term MVC, but the concept is the same. Ideally, you have the business logic in the PHP, the form in the HTML contained in your Tpl chunks, and the content in placeholders.

If you were going to create a menu based on your pages, for example, the PHP code of Wayfinder would provide the business logic, the Tpl chunks would provide the form, and the Resource tree would provide the content through placeholders in the Tpl chunks.

Conforming to some ideal of program design isn’t the only reason for moving the content out of your snippet. Suppose you (or your client) would like to change the output of the snippet. There should be an easier way than having to edit the raw PHP code of the snippet.

Moving the Content

When it comes to moving your content and display format out of a snippet, there are a number of places to put it. Sizable data sets will usually go in the database or sometimes in a file. Sizable blocks of HTML, will usually go in a chunk. In our case, there isn’t that much to store or edit so we’ll put it in a property in the snippet tag. While we’re at it, we’ll also make the time interval a property, since it’s the only other thing the user might want to change.

New Code

The first obvious enhancement to our snippet is to let the user control what will be displayed without having to edit the code of the snippet. In this version, we simply make the string of HTML we want to use for indicating new resources a property in the snippet tag. The snippet returns nothing if the resource wasn’t published in the last two weeks. If it’s more recent, the value passed in the tag is returned. The interval is now also a property.

[code language=”html”]
[[!NewResource? &showNew=`<span class="new_resource">NEW!</span>` &interval=`1209600`]]
[/code]

 

[code language=”php”]
/* NewResource snippet */

/* Default return value */
$output = ”;

/* Return value for new resources that are published */
$newOutput = $modx->getOption(‘showNew’, $scriptProperties,
‘<span class="new_resource">NEW!</span>’, true);

/* Set $interval as the number of seconds in two weeks */
$interval = $modx->getOption(‘interval’, $scriptProperties, 1209600, true);

/* See if the resource is published */
$published = $modx->resource->get(‘published’);

/* See if publication date is within the last two weeks */
if ($published) {
/* Get the current time as a timestamp */
$currentTime = time();

/* Get the publishedon date and
convert it to a unix timestamp */
$ptime = strtotime($modx->resource->get(‘publishedon’));

/* Get the resource’s age in seconds */
$age = $currentTime – $ptime;

if ($age < $interval) {
/* Yes, it’s recent — Set the return value */
$output = $newOutput;
}
}
}

return $output;
[/code]

The value you send in the snippet tag will be shown if the resource meets the conditions, and nothing will show if it doesn’t. Notice how easy it was to make this change with the variables extracted and placed at the top of the snippet. All we had to do was replace their values with a call to the getOption(), which extracts the values from the snippet tag via the $scriptProperties array.

The $scriptProperties Array

I’ve written about this in other articles, but the only code that needs explaining above is the call to $modx->getOption(), so I thought put in a quick reminder about how it works. Skip this section if you already know.

Whenever MODX launches a snippet, it gathers the properties from the snippet tag, any attached property sets, and the snippet’s default properties, puts them all in the same array, and sends it to the snippet as the $scriptProperties array. It’s very common to see $scriptProperties (or some alias for it) in the second argument to getOption(). If there are many getOption() calls, the programmer will usually create a variable with a shorter name to save typing, like this:

[code language=”php”]
$sp = $scriptProperties;
$modx->getOption(‘someOption’, $sp);
[/code]

The getOption() method takes four arguments. The first one is required, but the other three are optional:

[code language=”php”]
public function getOption($key, $options = null, $default = null, $skipEmpty = false) {}
[/code]

The first argument is the string you’re looking for. The second argument can be empty or an array. If it’s empty, getOption() will look for a MODX System Setting (or a Context, Group, or User Setting) with the key specified in the first argument. If the second argument is an array, getOption() will search the array for the key. If the key isn’t found there, it will search the settings, as described above.

The third argument to getOption() is the default value to use if the key isn’t found.

The fourth argument tells getOption() what to do if the key is found but the value is empty. It must be true or false (false is the default). With the default value of false, getOption() will return whatever value it finds, even if it’s empty. When the fourth argument is set to true and the value is empty (e.g., 0, ”, “”, or null), though, getResources() will return the default value from its third argument instead.

That fourth argument is especially important in MODX Revolution, where snippets can have default properties that might be empty. If the property is missing from the snippet tag (or misspelled) and there is no default property with that key, the default value in the getOption() call will be used. But what if there *is* a default property with that key that was installed with the snippet and it’s completely empty and has never been set. In that case getOption() will return that empty value rather than using the default value in the getOption() call unless you’ve set the fourth argument to true.

Remember that getOption() will always search for a System Setting if it hasn’t found what it’s looking for. (Actually, it searches all the settings: System, Context, Group, and User). Be careful not to give a snippet property with the same name as a System, Context, Group, or User Setting, unless you want the Setting as a default value for the property.

More Uses for Properties

You can send anything that’s available in the page as the value of a property in the snippet tag. For example, say you want to have different “New” indicators on different pages. You could create a TV called NewIndicator and put the value you want for the indicator (e.g., NEW, New!, This is NEW!!!, or nothing) in that TV on each page. Then, in the snippet tag, you’d could do this:

[code language=”html”]
[[!NewResource? &showNew=`[[*NewIndicator]]` &interval=`1209600`]]
[/code]

Coming Up

In this article, we looked at how to move the content and user options out of the PHP code and into the snippet tag. In the next one, we’ll see a more user-friendly way of letting the user specify the time interval.


For more information on how to use MODX to create a web site, see my web site Bob’s Guides, or
better yet, buy my book: MODX: The Official Guide.

Looking for quality MODX Web Hosting? Look no further than <a
href=”http://bit.ly/YgFGHl”>Arvixe Web Hosting!

Tags: , , | Posted under MODX, MODX | RSS 2.0

Author Spotlight

Bob Ray

Bob Ray is the author of MODX: The Official Guide and over 30 MODX add-on components. He hosts Bob's Guides, a source of valuable information for MODX users, and has been very active in the MODX Forums with over 19,000 posts.

Leave a Reply

Your email address will not be published. Required fields are marked *