Using Akismet to Detect Spam Email

PHP 1 Comment

After seeing the effectiveness of the Akisment WordPress plug-in at filtering out spam comments here, I decided to see if I could use it in conjunction with a email contact form. I thought it might be interesting to some of my readers (there are at least a couple) to keep a sort of journal here of what I do to accomplish that, plus it might help encourage me to finish it.

So the first thing I've done is to create an Akismet class that can take the pertinent data, contact the Akismet server via cURL and send it that data, and then return the response as a boolean (true == spam, false == not spam).

Read the rest...

Application Constants in Interfaces

PHP No Comments

Here's a little trick I discovered the other day for passing application settings around in an object-oriented implementation. You can create an interface that defines any number of class constants, then any class you define that needs those constants needs only to implement that interface. For example:

<?php
/**
 * Define constants for use in other classes
 */
interface Constants
{
   const DB_HOST 'localhost';
   const DB_USER 'username';
   const DB_PASS 'abc123xyzr';
   const DB_NAME 'test';
}

/**
 * Database class based on MySQLi class
 */
class DB extends mysqli implements Constants
{   
   public function __construct()
   {
      parent::__construct(
         self::DB_HOST,
         self::DB_USER,
         self::DB_PASS,
         self::DB_NAME
      );
   }
}

The advantage of this over running some configuration script that sets the constants is that by implementing an interface, it becomes immediately visible that the class requires that interface. If on the other hand you depend on independently setting constants in an include file or such, then if you try to reuse a class that uses those constants, it will not be immediately obvious that they are needed until you start testing it in the new implementation.

The main limitation is that interfaces cannot have class variables, only constants. If you need application-wide variables for your object-oriented application, you'll either need to instantiate a class that has those variables and pass it to each object that needs it, use a singleton pattern class (which can have the same disadvantage of globals in that the fact that it is required can be hidden inside a class), or look into something like using a registry pattern class.