Dynamic Eclipse PDT (PHP) templates for the singleton pattern


I’m currently working with a legacy PHP CMS and do-it-all system which is heavily reliant on singletons. Instead of relying on static methods and direct invocation we store object instances in a global array, these instances are then retrieved through the use of a call looking like this: singleton(’ClassName’).

As you can imagine calls of the form singleton(’ClassName’)->funcName($arg1, $arg2) are extremely common. And as you also realize there is no way in eclipse to get autocompletion for something like this without templates.

However, adding a template for each class method manually in Eclipse is out of the question. We need a way to generate a massive templates file which we then can import. In that respect the title for this article is somewhat misleading since this process is hardly wholly dynamic in the true sense of the word, more like semi-dynamic which is probably a better description.

After tokenizing the whole project tree we can use the resultant information to generate a template XML like this:

ob_start();
echo '<?xml version="1.0" encoding="UTF-8" standalone="no"?>';
?>
<templates>
<?php foreach($to_xml as $el): ?>
  <template 
  autoinsert="false" 
  context="php" 
  deleted="false" 
  description="singleton <?php echo $el['class'] ?>" 
  enabled="true" 
  id="org.eclipse.php.ui.editor.templates.php.<?php echo $el['class'].'.'.$el['function'] ?>" 
  name="<?php echo $el['class'].'.'.$el['function'] ?>">
    singleton("<?php echo $el['class'] ?>")-><?php echo $el['function'] ?>(<?php echo $el['args'] ?>);
  </template>
<?php endforeach ?>
</templates>
<?php
file_put_contents('templates.xml', ob_get_clean());

Note that I have put things on separate rows above, this is not the case in the real XML output which has each template element on a single row.

As you can see we use the string “ClassName.funcName” as both name and id, note also that the $el[’args’] contents need to be of the form “${dollar}arg1, ${dollar}arg2″ to account for the fact that $ needs to be rendered correctly in the completion output.

Anyway, we import templates.xml by going to Window -> Preferences -> PHP -> Editor -> Templates -> Import.

If we now start typing ClassN and hitting Ctrl - Space we see ClassName.funcName in the list of completion alternatives. If I then select ClassName.funcName the result under the cursor will be: singleton(’ClassName’)->funcName($arg1,$arg2), awesome and quite a big productivity boost for me.

Related Posts

Tags: , ,