Getting started
In this guide we will install phpgt/sync, copy a directory and inspect what happened.
[!NOTE] In WebEngine applications, this package is usually used through the build system. The default build configuration calls
vendor/bin/syncto copy or link files from directories such asscript/,style/andasset/intowww/.This guide installs the package directly, for when we want the same sync behaviour in a standalone PHP script or in another framework.
1. Install the package
composer require phpgt/sync
The package provides PHP classes and a command line script at vendor/bin/sync.
2. Copy one directory to another
use GT\Sync\DirectorySync;
$sync = new DirectorySync("asset", "www/asset");
$sync->exec();
If the destination directory does not exist, it is created. Files that do not exist in the destination are copied across, and files that already match are skipped.
3. Read the summary
After exec() has finished, the object keeps track of what happened during that run:
printf(
"Copied %d, skipped %d, deleted %d",
count($sync->getCopiedFilesList()),
count($sync->getSkippedFilesList()),
count($sync->getDeletedFilesList()),
);
The lists are reset each time exec() is called.
4. Check whether two directories match
If we only need to know whether the destination is already in sync, call check():
if(!$sync->check()) {
$sync->exec();
}
By default, files are compared using their modification time. We can use content hashes instead:
$sync->check(DirectorySync::COMPARE_HASH);
$sync->exec(DirectorySync::COMPARE_HASH);
Do not combine COMPARE_FILEMTIME and COMPARE_HASH in one call. The library will throw GT\Sync\SyncException.
Next, move on to directory sync to see how copying, filtering and deletion work.