Description
In my extension on MarkdownExtra I have to copy a lot of methods only to change a single line.
Sometimes I have changed the regex a little bit (attributes on an image by reference), sometimes I want to add attributes (target=blank on external links), sometimes I want to change the output (img is wrapped in ).
In all of these cases, having a hook that is called would suffice. If several functions would check if a hook function is added I wouldn't have to copy a lot of code.
For example, this is the beginning of the inline anchors callback:
protected function _doAnchors_inline_callback($matches) {
$whole_match = $matches[1];
$link_text = $this->runSpanGamut($matches[2]);
$url = $matches[3] == '' ? $matches[4] : $matches[3];
$title =& $matches[7];
$attr = $this->doExtraAttributes("a", $dummy =& $matches[8]);
If this would be like this:
protected function _doAnchors_inline_callback($matches) {
$whole_match = $matches[1];
$link_text = $this->runSpanGamut($matches[2]);
$url = $matches[3] == '' ? $matches[4] : $matches[3];
$title =& $matches[7];
$attr = $matches[8];
if ($this->hooks['beforeAnchorsInline']) {
$this->hooks['beforeAnchorsInline']($whole_match, $link_text, $url, $title, $attr);
}
$attr = $this->doExtraAttributes("a", $attr);
And from my script (no extension needed, could be a wrapper), I could do this:
$parser->addHook('beforeAnchorsInline', function(&$whole, &$text, &$url, &$title, &$attr) {
if (preg_match('//', $url)) {
$attr .= " target=blank";
}
};
This way I wouldn't have to copy any code, I can add the same hook to beforeAnchorInline and beforeAnchorByReference to save duplicate code.
When I have finished my current project, I could fork this project and work on it and make pull requests if you prefer.