Side Effects and Events
Sometimes you may want to perform actions when your parser encounters something you're interested in. Parsica provides combinator called emit()
. It allows you to inject side effects at any point. It's intentionally very barebones: It's really just a callback function, that gets called only when the parser succeeds.
Using closures and mutable objects, you can embed mutability into a parsing process.
For most use cases, we suggest using emit()
with an adapter for your application's event dispatching mechanism. The following shows how to adapt emit()
to any PSR-14 compatible event dispatcher.
This way, you can neatly separate the occurrence of a parsing event, from the actual side effect. If the dispatcher is asynchronous, the parsing process can keep continuing, without being interrupted by blocking side effects, such as writing to a database. Or when parsing a large input file or continuous input stream, you can start processing the results before the parsing has finished.