Writing a custom parser for Patterns 7.x

Last updated on
30 April 2025

Writing a Patterns parser is relatively straightforward, and it requires understanding the abstract pattern model, implementing just one Patterns hook, and sticking to a coding convention.

First, we need to implement hook_patterns_parser. This hook tells Patterns that a new parser is available. It must return an associative array of the type:

// Implements hook patterns_parser
function mymodule_parser_patterns_parser() {
  $parser = array();
  $parser['format'] = 'myformat;
  $parser['parser'] = 'mymodule_parser'; // the prefix to add when calling the operative methods, usually the name of the module
  return $parser;
}

Then, we need to write the following methods to write and read from 'myformat' format.

  • prefix_load: takes a path to pattern file as input parameter and returns the abstract representation of the pattern.
  • prefix_parse: takes a string as input parameter and returns the abstract representation of the pattern.
  • prefix_dump: takes the abstract representation of a pattern as input parameter and returns a string.
  • prefix_dump_comment: takes a string as input parameter, and transform it into a comment in the given format.

If we stick to the example above, prefix would be 'mymodule_parser'. Notice, that they are not strictly speaking Drupal hooks, because 'prefix', can be different from the name of the module. For this, it is rather a convention.

Patterns abstract model

In memory, patterns are stored as an associative array, regardless of their original format. It means that a _parse method should expect this kind of array, and a _dump should return this kind of array.

The nature of this associative array can be better understood with an example, that follows.

Pattern file stored in the file system

# YAML Taxonomy Pattern
# QScience

info:
  title: Taxonomy Terms MODIFY
  description: Modify a term within a vocabulary
  author: me
  category: Taxonomy
  version: 1.0
  core: 7.x
  author_email: me@i.org
  author_website: qlectives.eu


actions:

  - modify:
        tag: term
        name: Term name
        descr: This is not a Patatina
        tid: 1
        vocabulary: tags # machine_name

Patterns abstract model in memory

pattern	Array [2]	
	info	Array [8]	
		title	Taxonomy Terms MODIFY
		description	Modify a term within a vocabulary	
		author	me	
		category	Taxonomy	
		version	1.0	
		core	7.x	
		author_email	me@i.org	
		author_website	qlectives.eu
	actions	Array [1]	
		0	Array [1]	
			modify	Array [5]	
				tag	term	
				name	Term name	
				descr	This is the term name	
				tid	1	
				vocabulary	tags	

Help improve this page

Page status: Not set

You can: