Skip to content

Advanced Usage

SupianIDz edited this page May 16, 2021 · 3 revisions

Advanced Usage

Defining Events

See : https://www.php.net/manual/en/inotify.constants.php for more event constants.

Group Events

To define your event as a group:

use Octopy\Inotify\Inotify;
use Octopy\Inotify\Contract\Event;
use Octopy\Inotify\Contract\Watcher;

$inotify = new Inotify('foo.txt', function (Event $event) {

    $event->on(IN_MODIFY, function (Watcher $watcher) {
        // do something
    });
    
    $event->on(IN_DELETE, function (Watcher $watcher) {
        // do something
    });

    // see : https://www.php.net/manual/en/inotify.constants.php for more events.
});

$inotify->watch();

Single Events

You can simply write event when there is only one event you are using:

use Octopy\Inotify\Inotify;
use Octopy\Inotify\Contract\Watcher;

$inotify = new Inotify('foo.txt');

$inotify->event->on(IN_MODIFY, function (Watcher $watcher) {
    // do something
});

$inotify->watch();

Event Logging

When you need the full details of the event log when the event is executed instead of writing your code for each event, it is simpler to write in the watch function callback, it will be executed every time there is an action on the target.

use Octopy\Inotify\Inotify;
use Octopy\Inotify\Contract\Event;
use Octopy\Inotify\Contract\Watcher;
use Octopy\Inotify\Contract\ExecutedEvent;

$inotify = new Inotify('foo.txt', function (Event $event) {

    $event->on(IN_MODIFY, function (Watcher $watcher) {
        // do something
    });
});

$inotify->watch(function (ExecutedEvent $event) {
    if($event->is(IN_MODIFY)) {
        echo 'File Updated...';
    }
    
    if($event->is(IN_DELETE)) {
        echo 'File Deleted...';
    }
    
    // dump details of the running event process
    $event->events()->dump();
});

Terminating

Feel free to terminating the inotify process running when an event is executed:

use Octopy\Inotify\Inotify;
use Octopy\Inotify\Contract\Event;
use Octopy\Inotify\Contract\Watcher;
use Octopy\Inotify\Contract\ExecutedEvent;

$inotify = new Inotify('foo.txt', function (Event $event) {
    
    // The process is stopped when the file is deleted
    $event->on(IN_DELETE, function (Watcher $watcher) {
        $watcher->terminate();
    });
});

// Or you want to stop the process at any event.
$inotify->watch(function (ExecutedEvent $event, Watcher $watcher) {
    $watcher->terminate();
});