Service / Callback
When an extension does not need any kind of interface or does not generate any HTML code for a website, you may write a Service/Callback extension. The idea is simple, when a certain event occurs your code is called by Navigate CMS to do a concrete action; you can send an e-mail, gather statistics, modify any kind of content...
We'll take the Akismet antispam extension to illustrate an example. What this extension does is check every new comment submitted, sending it to the Akismet webservice to determine if it is "ham" or "spam" (a real comment or an unwanted one).
To ask Navigate CMS to execute our function on a certain event we need to declare a bind in the extension definition:
"bindings": [
{
"module": "comments",
"event": "after_insert",
"function": "nvweb_akismet_antispam_plugin_check_spam"
}
]
As a side note, if your extension only will be called on events generated by a website, you can declare the bind programmatically with the before_parse website event (in this case you don't need to declare it in the definition):
function nvweb_akismet_antispam_event($event, $html)
{
global $events;
$html = '';
if($event == 'before_parse')
{
$events->bind(
'comment',
'after_insert',
'akismet_antispam',
'nvweb_akismet_antispam_plugin_check_spam'
);
}
return $html;
}
This function must be included in the main PHP file of the extension (extension_name.php). To better understand this mechanism please read the Raty example on the Website widget type of extension.
When Navigate CMS detects the event it calls the declared function and sends only one parameter, which in fact is an associative array of objects.
function nvweb_akismet_antispam_plugin_check_spam($params)
{
$extension = new Extension();
$extension->load('akismet_antispam');
$comment = $params['comment'];
$akismet = new Akismet(NVWEB_ABSOLUTE, $extension->settings['akismet_api_key']);
$akismet->setCommentAuthor($comment->name);
$akismet->setCommentAuthorEmail($comment->email);
$akismet->setCommentContent($comment->message);
$is_spam = $akismet->isCommentSpam();
if($save && $is_spam)
{
$comment->status = 3;
$comment->save();
}
return $is_spam;
}
In our example, $params only has one element: "comment", which is the comment object. Our function loads the Akismet extension object to retrieve the configuration for the current website. Then instantiates the Akismet class to send the detection request. If Akismet answer is "spam" then change the status of the comment to 3 (spam) and save the object. Of course you'll need to know that 3 is the status for spam comments.
To get a full list of available events to bind to, check the Events section of this manual.
0 Comments