Writing Custom PHP Snippets for MODx (part VII)

This article and tutorial video takes on how to add custom PHP scripts (known as Snippets) to the MODx content management system. This covers MODx Evolution (version 1.0 and before), but many of these methods and principles are applicable to MODx Revolution (version 2.0) and PHP coding in general.

Please enable Javascript and Flash to view this Blip.tv video.
Watch Video @ Blip.Tv

Adding a Snippet

MODx newcomers are sometimes confused as to where to upload the PHP files… YOU DON’T UPLOAD IT. You paste it into a database record. You can reference files on the file system, but you don’t have to.

1. To add a Snippet from the MODx (v1) manager go to Elements –> Manage Elements –> Snippets then paste in your PHP code.
2. Be sure to give it a unique name (I recommend avoiding spaces in the name)
3. Give it a category: this will make your Snippet easier to find in the manager.

Recommended Components of a PHP Snippet

This applies to ANY code you write, but for the record, please include the following documentation as comments in your Snippet:
1. SUMMARY: a sentence describing what the Snippet does.
2. INPUT: list any input variables the Snippet can accept. It’s good to note the data type (e.g. integer/string), whether or not they are required, or whether or not they have a default value.
3. OUTPUT: list any special output created by the Snippet. Usually it’ll just be HTML, but it’s good to note any external actions (e.g. whether it updates a database row).
4. EXAMPLE: give an example of how the Snippet should be called.

Sample Comment Block

Coding Suggestions and Rules of Thumb

1. Develop your Interface before you code: that bit about adding comments isn’t just for other users, it can help you determine how you want to be able to interact with your code. Coding to an interface is good way of establishing goals and structure before you even start writing the actual code.
2. Initialize your variables: This cuts down on the possibility of security exploits, bugs, and it makes your code easier to read, e.g.:
$output = '';
$garfield_characters_array = array();

3. Sanitize your input: if you are getting any user entered data (e.g. anything out of the $_POST or $_GET array), sanitize the data using regular expressions and if/then statements. Make SURE you have eliminated any possibility that the data is something other than what your program expects.
4. Test as you Go: PHP doesn’t have a built-in debugger, so don’t go too long without checking to see if your code still “compiles” (technically, you should check to see if it has a valid syntax and if it executes). Checking often will help you track down where you made a mistake.
5. Use Good Variable and Function Names: be descriptive. Don’t become a member of the hated “ASCII Preservation Society”. Besides, if you use unique variable names, it becomes MUCH easier to search for instances of that variable, and you’re less likely to have variable collisions.
6. Group your Code into Units: In a word, use functions that fit on the page. If you can SEE it, you’re less likely to UNDERSTAND IT. Chapters of uninterrupted code are hard to debug and test.
7. Reuse your Code: if there are cases in your code where you’re copying and pasting identical or NEARLY identical parts, then it’s time to relegate that code to its own separate function.
8. Log your Errors: if something goes wrong, let your users know about it. It’s a wonderful thing to use the MODx logging function.
9. DO NOT MIX HTML and PHP! There are a few cases where where this is acceptable, but it is good architectural design to separate your view (i.e. your HTML) from your logic. If you have to edit your PHP code to change div tags or CSS classes, then you probably did something wrong. Instead, use MODx Chunks to format Snippet output; your code will be MUCH cleaner as a result and MUCH easier to maintain.

Including Files from the File System

If you write anything more than simple Snippets, you’ll want to put your PHP file(s) on the file system and reference them from the Snippet stored in the MODx database. You can do this by including a standard include or require statement, e.g.


The standard MODx location would be in your own folder within the /assets/snippets directory.

Things to Remember When Including Files and Using Functions

1. Variable Scope: the $modx super-object and the methods that go along with it will not remain in scope within a funciton; use the global to ensure that the globally scoped $modx variable instance is used inside the function. Compare the two instances of the same API call:
// INSIDE a function
function inside_a_function($chunk_name,$garfield_characters_array)
global $modx;
$output = $modx->parseChunk($chunk_name, $garfield_characters_array, '[+', '+]');
return $output;

// Or OUTSIDE a function
$output = $modx->parseChunk($chunk_name, $garfield_characters_array, '[+', '+]');

2. You can’t return a value directly from an included file: because MODx treats Snippets as functions, it’s considered good form to always return a value, e.g. “return $output;” or “return TRUE;” but this MUST be returned from the original Snippet in the database; if you return output from the included file, you’ll have to return it again from the original database Snippet code. See the video for this quirk in action.
3. Take advantage of the File System: if you are developing stand-alone PHP files, you can use the bash terminal (on Linux or OS X machines) to test the PHP syntax. Simply navigate to the directory where your file is and type:
php -l name_of_your_file.php

6 thoughts on “Writing Custom PHP Snippets for MODx (part VII)

  1. Hi!

    I really like your MODx video tutorials and I’m eagerly awaiting part VIII “Using MODx for database driven dynamic websites” :) j/k

    Whatver you want to go trough nex. Do it. I like the series alot. And many other do to. I haven’t fond any good MODx video tutorials anywhere except on tipsfor.us!

    Best Regards


  2. Hi,

    I like your modx video very much can u tell me can i used my own databse in modx
    pls reply


  3. Of course you can. You can use seperate dbases one for modx and one for own stuff. There’s a db api to simply switch between them.

  4. Would it be possible for you to explain a bit more about the MODx logging?
    (how to switch it on or off, how and when to use it, are there several alternatives, or is there “one way”?)

Comments are closed.