Installation
composer require ornicar/akismet-bundle
Add the bundle to config/bundles.php:
return [
// ...
Ornicar\AkismetBundle\OrnicarAkismetBundle::class => ['all' => true],
];
Configuration Publish the default config:
php bin/console config:dump-reference OrnicarAkismetBundle
Update config/packages/ornicar_akismet.yaml with your Akismet API key and preferred HTTP client (Buzz/Guzzle):
ornicar_akismet:
api_key: 'your_api_key_here'
http_client: 'guzzle' # or 'buzz'
First Use Case Check a comment for spam in a controller:
use Ornicar\AkismetBundle\Akismet\Akismet;
public function submitComment(Request $request, Akismet $akismet)
{
$comment = $request->request->all();
$result = $akismet->verify($comment);
if ($result->isSpam()) {
return $this->json(['error' => 'Spam detected'], 400);
}
// Save comment to DB
}
config/packages/ornicar_akismet.yaml (Configuration)src/Akismet/Akismet.php (Core service)src/DependencyInjection/Configuration.php (Advanced config options)public function store(Request $request, Akismet $akismet)
{
$data = $request->validate([
'author' => 'required|string',
'email' => 'required|email',
'content' => 'required|string',
]);
$result = $akismet->verify($data);
if ($result->isSpam()) {
return back()->with('error', 'Spam blocked');
}
// Proceed with saving
}
Use the verifyMultiple() method for bulk checks (e.g., importing old comments):
$comments = Comment::where('checked', false)->get();
$results = $akismet->verifyMultiple($comments->toArray());
foreach ($results as $index => $result) {
$comments[$index]->is_spam = $result->isSpam();
$comments[$index]->save();
}
Enable stub mode in config/packages/ornicar_akismet_test.yaml:
ornicar_akismet:
stub: true
Mock responses in tests:
public function testSpamDetection()
{
$this->app->make('akismet')->shouldReceive('verify')
->once()
->andReturn(new \Ornicar\AkismetBundle\Akismet\Result(true));
$response = $this->post('/comments', ['content' => 'malicious']);
$response->assertStatus(400);
}
Subscribe to Akismet events (e.g., akismet.verify.success):
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Ornicar\AkismetBundle\Event\VerifyEvent;
class AkismetSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [
'akismet.verify.success' => 'onVerifySuccess',
];
}
public function onVerifySuccess(VerifyEvent $event)
{
if ($event->getResult()->isSpam()) {
$this->logSpamAttempt($event->getData());
}
}
}
Service Binding: Bind the Akismet service in AppServiceProvider for Laravel:
public function register()
{
$this->app->bind('akismet', function ($app) {
return $app->make('ornicar_akismet.akismet');
});
}
Form Request Validation: Combine with Laravel’s Form Requests for cleaner validation:
public function rules()
{
return [
'content' => 'required|string|akismet', // Custom rule
];
}
public function withValidator($validator)
{
$validator->extend('akismet', function ($attribute, $value, $parameters, $validator) {
$akismet = app('akismet');
$result = $akismet->verify($this->all());
return !$result->isSpam();
});
}
Caching Results: Cache Akismet responses for identical submissions:
$cacheKey = md5(json_encode($data));
$result = Cache::remember($cacheKey, now()->addMinutes(10), function () use ($akismet, $data) {
return $akismet->verify($data);
});
Async Processing: Use Laravel Queues for non-critical checks:
Queue::push(new CheckSpamJob($data));
$data = $request->all();
$data['user_ip'] = $request->ip();
$data['user_agent'] = $request->userAgent();
$result = $akismet->verify($data);
AKISMET_API_KEY) and .env:
ornicar_akismet:
api_key: '%env(AKISMET_API_KEY)%'
403 Forbidden.try {
$result = $akismet->verify($data);
} catch (RateLimitExceededException $e) {
sleep(10); // Retry after 10 seconds
$result = $akismet->verify($data);
}
config/packages/ornicar_akismet.yaml:
ornicar_akismet:
stub:
spam_response: true
ham_response: false
akismet.stub.set_response() dynamically in tests:
$this->app['akismet.stub']->setResponse(true); // Force spam
config/packages/ornicar_akismet.yaml:
ornicar_akismet:
http_client: guzzle
guzzle_options:
timeout: 10
middleware: ['retries' => 3]
Set debug: true in config to log raw Akismet requests/responses:
ornicar_akismet:
debug: true
Check logs at var/log/dev.log.
Akismet requires specific fields (user_ip, user_agent, etc.). Use akismet.validate() to check:
if (!$akismet->validate($data)) {
throw new \InvalidArgumentException('Invalid Akismet data');
}
Enable silent_exceptions: false in production to log errors:
ornicar_akismet:
silent_exceptions: false
Disable stub mode in tests to verify real responses:
# config/packages/ornicar_akismet_test
How can I help you explore Laravel packages today?