symfony/symfony — pull request #4605 by everzet (2012-06-18 10:15:11+00:00)
Title: [2.2] ResourceWatcher component (final)

**Bug fix**: no
**Feature addition**: yes
**Backwards compatibility break**: no
**Symfony2 tests pass**: _yes_ (for old tests) and _partly_ (InotifyTracker is not yet finished)
**Fixes the following tickets**: -

This is final rebased version of #3961, which was a refactoring of #391

### Short overview

This component is here for tracking filesystem changes. You're registering directory or file resources to track with specific track name (`tracking_id`) and `start()` watcher. Watcher checks for FS changes after specific timespan and if some change occur (file/directory create/update/delete) - watcher dispatches `EventDispatcher` event with `resource_watcher.all`, `resource_watcher.tracking_id` names and `FilesystemEvent` as argument.

### Usage

#### Simplest possible way of FS tracking

Simplest tracking code would look like this:

``` php
trackByListener(__DIR__.'/config', function($event) {
echo $event->getTypeString().': '.(string) $event->getResource();
});

// start listening
$watcher->start();
```

_best suitable `Tracker` and `EventDispatcher` would be instantiated for you, implicitly_

#### `track()` method

Extended usage looks like that:

``` php
track('twig.templates', __DIR__.'/view');

// track for `*.xml` files creations in `config` subfolder to `routing` tracker:
$watcher->track(
'routing',
Resource\DirectoryResource(__DIR__.'/config', '/\.xml$/'),
ResourceWatcher\Event\FilesystemEvent::IN_CREATE
);

// add `routing` track listener:
$dispatcher->addListener('resource_watcher.routing', function($event) {
echo $event->getTypeString().': '.(string) $event->getResource();
});

// add all tracks listener (listens to every tracked event):
$dispatcher->addListener('resource_watcher.all', function($event) {
echo $event->getTypeString().': '.(string) $event->getResource();
});

// start listening
$watcher->start();
```

#### `addListener()` method

If you don't want to deal with `EventDispatcher`, `ResourceWatcher` can hide this detail for you:

``` php
track('twig.templates', __DIR__.'/view');

// track for `*.xml` files creations in `config` subfolder to `routing` tracker:
$watcher->track(
'routing',
Resource\DirectoryResource(__DIR__.'/config', '/\.xml$/'),
ResourceWatcher\Event\FilesystemEvent::IN_CREATE
);

// add `routing` track listener:
$watcher->addListener('routing', function($event) {
echo $event->getTypeString().': '.(string) $event->getResource();
});

// add all tracks listener (listens to every tracked event):
$watcher->addListener('all', function($event) {
echo $event->getTypeString().': '.(string) $event->getResource();
});

// start listening
$watcher->start();
```