by
KK » Sat Dec 12, 2015 4:36 am
@tim, @trendoman, I thought you might like knowing a (hitherto not discussed) technique that could be useful with your code.
Couch provides a way to actually
override *all* its core tags.
So, if instead of creating a brand-new tag <cms:my_random_name /> (as you have done above), you'd like to modify the existing core <cms:random_name /> tag, here is how we can do that.
Place the following (slightly) modified version of your code in kfunctions.php file -
- Code: Select all
class CustomTags{
function my_random_name( $tag_name, $params, $node, &$html ){
global $AUTH;
if( count($node->children) ) {die("ERROR: Tag \"".$node->name."\" is a self closing tag");}
$html = strtr(base64_encode( $AUTH->hasher->get_random_bytes(5) ) , '+/=', '-_0');
return 1; // prevent the original tag from executing as we have set the output above
}
}
$FUNCS->add_event_listener( 'alter_tag_random_name_execute', array('CustomTags', 'my_random_name') );
With the above code in place, now when the original tag <cms:random_name /> is used, the custom code above gets executed thus completely overriding the core code in Couch.
To explain the code, while executing any tag Couch first fires an event (alter_tag_
<tag_name>_execute) to allow any custom code to override the behavior of that tag.
In our case the tag being overridden is 'random_name', so the event thrown would be 'alter_tag_
random_name_execute'.
Following line of the code hooks your code onto that event -
- Code: Select all
$FUNCS->add_event_listener( 'alter_tag_random_name_execute', array('CustomTags', 'my_random_name') );
Your original tag-handler function needs two minor modifications.
1. The original function signature changes from
function my_random_name( $params, $node )
to -
function my_random_name( $tag_name, $params, $node, &$html )
2. The overriding function (unlike the original tag functions) cannot simply return the HTML to be outputted. It has to set this output in the $html parameter instead -
original:
return strtr(base64_encode( $AUTH->hasher->get_random_bytes(5) ) , '+/=', '-_0');
modified:
$html = strtr(base64_encode( $AUTH->hasher->get_random_bytes(5) ) , '+/=', '-_0');
The return value is instead interpreted as a signal for Couch to skip calling the original tag-handler after our custom code -
return 1; // prevent the original tag from executing as we have set the output above
With this technique, we can avoid making direct changes to Couch's core code (which risks losing the modifications when an update occurs).
Finally, apologies if this suggestion seems completely unsolicited (and perhaps unnecessary in the context being discussed) but it appeared to me a good place to introduce a concept that could be vital in many other contexts.
Hope it helps.