Yii 2.0: akismet

Prevent comment spam using Akismet service.
1 follower

Akismet for Yii

ReleaseLicenseDownloadsCode qualityBuild

Prevent comment spam using the Akismet connector for Yii, high-performance PHP framework.

Features

  • Key Verification: checks an Akismet API key and gets a value indicating whether it is valid.
  • Comment Check: checks a comment and gets a value indicating whether it is spam.
  • Submit Spam: submits a comment that was not marked as spam but should have been.
  • Submit Ham: submits a comment that was incorrectly marked as spam but should not have been.

Requirements

The latest PHP and Composer versions. If you plan to play with the sources, you will also need the Phing latest version.

Installing via Composer

From a command prompt, run:

$ composer require cedx/yii2-akismet

Usage

In your application configuration file, you can use the following component:

return [
  'components' => [
    'akismet' => [
      'class' => 'yii\akismet\Client',
      'apiKey' => 'YourAPIKey',
      'blog' => 'http://your.blog.url'
    ]
  ]
];

Once the yii\akismet\Client component initialized with your credentials, you can use its methods.

Key Verification

$client = \Yii::$app->get('akismet');
 
$isValid = $client->verifyKey();
echo $isValid ? 'Your API key is valid.' : 'Your API key is invalid.';

Comment Check

use yii\akismet\{Author, Comment};
 
$comment = new Comment([
  'author' => new Author(['ipAddress' => '127.0.0.1', 'userAgent' => 'Mozilla/5.0']),
  'content' => 'A comment.'
]);
 
$isSpam = $client->checkComment($comment);
echo $isSpam ? 'The comment is marked as spam.' : 'The comment is marked as ham.';

Submit Spam/Ham

$client->submitSpam($comment);
echo 'Spam submitted.';
 
$client->submitHam($comment);
echo 'Ham submitted.';

Events

The yii\akismet\Client class triggers some events during its life cycle.

The request event

Emitted every time a request is made to the remote service:

use yii\akismet\{Client, RequestEvent};
 
$client->on(Client::EVENT_REQUEST, function(RequestEvent $event) {
  echo 'Client request: ', $event->getRequest()->getUri();
});

The response event

Emitted every time a response is received from the remote service:

use yii\akismet\{Client, ResponseEvent};
 
$client->on(Client::EVENT_RESPONSE, function(ResponseEvent $event) {
  echo 'Server response: ', $event->getResponse()->getStatusCode();
});

Unit Tests

In order to run the tests, you must set the AKISMET_API_KEY environment variable to the value of your Akismet API key:

$ export AKISMET_API_KEY="<YourAPIKey>"

Then, you can run the test script from the command prompt:

$ phing test

See Also

License

Akismet for Yii is distributed under the Apache License, version 2.0.

Be the first person to leave a comment

Please to leave your comment.

Create extension