Providing Your Own Replacements Lookup for the Decorator

Filling an array with replacements may not be the best solution for providing replacement information to the decorator. If you have a more elegant algorithm that performs replacement lookups on-the-fly you may provide your own implementation.

Providing your own replacements lookup implementation for the Decorator is simply a matter of passing an instance of Swift_Plugins_Decorator_Replacements to the decorator plugin's constructor, rather than passing in an array.

The Replacements interface is very simple to implement since it has just one method: getReplacementsFor($address).

Imagine you want to look up replacements from a database on-the-fly, you might provide an implementation that does this. You need to create a small class.

class DbReplacements implements Swift_Plugins_Decorator_Replacements {
  public function getReplacementsFor($address) {
    $sql = sprintf(
      "SELECT * FROM user WHERE email = '%s'",
      mysql_real_escape_string($address)
    );
    
    $result = mysql_query($sql);
    
    if ($row = mysql_fetch_assoc($result)) {
      return array(
        '{username}'=>$row['username'],
        '{password}'=>$row['password']
      );
    }
  }
}

Now all you need to do is pass an instance of your class into the Decorator plugin's constructor instead of passing an array.

$decorator = new Swift_Plugins_DecoratorPlugin(new DbReplacements());

$mailer->registerPlugin($decorator);

For each message sent, the plugin will call your class' getReplacementsFor() method to find the array of replacements it needs.

Note: If your lookup algorithm is case sensitive, you should transform the $address argument as appropriate – for example by passing it through strtolower().

NOTE: Documentation for version 3 is in the wiki.