Oh Dear is the all-in-one monitoring tool for your entire website. We monitor uptime, SSL certificates, broken links, scheduled tasks and more. You'll get a notifications for us when something's wrong. All that paired with a developer friendly API and kick-ass documentation. O, and you'll also be able to create a public status page under a minute. Start monitoring using our free trial now.

A package to watch for file system changes in PHP

Original – by Freek Van der Herten – 2 minute read

Our team has released a new package called file-system-watcher. As the name implies, this package can watch changes in the file system and let you act on those changes.

Using the package

Here's a simple example that allows you to run some code when a new file gets added.

use Spatie\Watcher\Watch;

    ->onFileCreated(function (string $newFilePath) {
        // do something...

After calling start, the watcher will start a never-ending loop. When a file is created in the given $directory, the closure passed in onFileCreated will be executed.

There are methods for each kind of file change onFileCreated(), onFileUpdated(), onFileDeleted(), onDirectoryCreated(), onDirectoryDeleted().

Pretty simple, right?

How it works under the hood

Under the hood, this package leverages (https://github.com/paulmillr/chokidar), a popular JS library that can efficiently handle file system changes without requiring much memory or CPU.

To see a demo of the package and learn how we integrated our PHP code with a JS package, watch this fragment of a stream in which I introduced our file-system-watcher.

In closing

There are a few more options available in file-system-watcher. Head over to the readme on GitHub to learn more.

Be sure also to check out the packages our team has created previously. I'm sure there is something that you could use in your next project.

Stay up to date with all things Laravel, PHP, and JavaScript.

Follow me on Twitter. I regularly tweet out programming tips, and what I myself have learned in ongoing projects.

Every two weeks I send out a newsletter containing lots of interesting stuff for the modern PHP developer.

Expect quick tips & tricks, interesting tutorials, opinions and packages. Because I work with Laravel every day there is an emphasis on that framework.

Rest assured that I will only use your email address to send you the newsletter and will not use it for any other purposes.