Plugins are similar to Snippets in that they are bits of PHP code that have access to the MODx API. The big difference, however, is in when the code executes. You put Snippets inside of a page or inside a template and they run when the page is viewed, whereas Plugins are set to execute during certain system events, e.g. saving a Chunk, or emptying the cache. So when a given event "fires", any Plugin "listening" for that event is executed. Once the Plugin's code has executed, control returns to the point after the spot where the System Event was triggered.
Every CMS uses some concept of "plugin", but the exact nomenclature may differ. In WordPress, for example, plugins are "hooked" to events called "actions" or "filters".
Since they execute during various events, Plugins aren't limited to front-end processing. Many events are triggered by events that take place only within the MODx Manager. There is a list of MODx System Events here.
|Any closing PHP tag ?> will be stripped from your plugin code when it is saved. It's unnecessary (and unwanted) because the plugin code will end up inside other PHP code when executed.|
MODx invokes System Events across its code processes to allow you to modify core functionality without hacking the core. These System Events can have any number of Plugins attached to them, and will execute each Plugin in rank according to its priority (lowest numbers first).
In your Plugin, how you handle the output depends on the System Event you are in. For some system events, you return a value from the Plugin. For others, you access the output by reference and modify it.
If you need to know which event triggered your plugin (say, for a plugin that listens to more than one event), you can access the Event's name like so:
The code for a Plugin listening to more than one event looks like this:
Plugins can be used for a variety of different applications, below are a couple of examples:
Description: Send a custom message to the user as they create/edit a page... a custom header.
System Events: OnDocFormPrerender
Description: Do some custom validation on saving a page resource
System Events: OnBeforeDocFormSave
The trick here is that what you want to message the user has to be passed to the $modx->event->output() function; any text you want to write to the logs can simply be returned by the plugin. If you pass validation, simply return null.
|No HTML Allowed|
Description: Filter words from a document before it's displayed on the web
System Events: OnWebPagePrerender
Description: Redirects a user to selected document and sends a message
System Events: OnPageNotFound
- pnf.page: Error Resource ID
- pnf.mailto: Mail To Address
- pnf.mailfrom: Mail From Address