VOOZH about

URL: https://deepwiki.com/hypervel/devtool/12.1-file-watching-and-hot-reload

⇱ File Watching and Hot Reload | hypervel/devtool | DeepWiki


Loading...
Menu

File Watching and Hot Reload

This document covers the watch command, a development utility that monitors file changes and automatically restarts the development server. This command enables a hot-reload workflow during development, eliminating the need for manual server restarts after code modifications.

For information about other development utilities, see Development Tools. For event system introspection, see Event Inspector.


Purpose and Functionality

The WatchCommand provides automatic server restart functionality by monitoring the filesystem for changes. When source files are modified, the command detects the changes and restarts the configured server command (typically php artisan serve). This is a non-generator utility command that extends HyperfCommand rather than GeneratorCommand.

Key Characteristics:

  • Command Name: watch
  • Class: WatchCommand
  • Base Class: Hyperf\Command\Command (not a generator)
  • External Dependency: hyperf/watcher package (required)
  • Primary Use Case: Development-time hot-reload workflow

Sources: src/Commands/WatchCommand.php1-66


Command Structure

Class Definition

The WatchCommand class is implemented as a standard Hyperf console command:

PropertyTypeDescription
$containerContainerInterfaceDependency injection container
Command NamewatchCLI command identifier
DescriptionHot-reload watcherCommand purpose
TraitNullDisableEventDispatcherDisables event dispatching

Sources: src/Commands/WatchCommand.php17-29

Command Architecture Diagram


Sources: src/Commands/WatchCommand.php7-19


CLI Options

The watch command accepts four CLI options that control its behavior:

OptionShortTypeDefaultDescription
--config-CString.watcher.phpPath to custom configuration file
--file-FArray[]Specific file(s) to watch (repeatable)
--dir-DArray[]Directory(ies) to watch (repeatable)
--no-restart-NFlagfalseDisable automatic server restart

Usage Examples


Sources: src/Commands/WatchCommand.php25-28


Configuration System

Configuration Source Resolution

The WatchCommand resolves configuration from multiple sources with the following precedence (higher number = higher priority):


Sources: src/Commands/WatchCommand.php38-56

Configuration Resolution Logic

The configuration is resolved through the following steps in the handle() method:

Step 1: Base Configuration

  • Attempt to load from application config: ConfigInterface::get('watcher', [])
  • If empty and default file exists, load from: BASE_PATH . '/vendor/hyperf/watcher/publish/watcher.php'

Step 2: Custom Configuration File

  • If --config option file exists, merge it over base configuration using array_replace()
  • Default config file path: .watcher.php

Step 3: Default Command

  • If command key not set in configuration, default to: 'artisan serve'

Step 4: CLI Options Override

  • CLI --dir and --file options are passed directly to Option constructor
  • CLI --no-restart flag inverts to restart boolean for Option constructor

Sources: src/Commands/WatchCommand.php38-57

Configuration Schema

A typical watcher configuration file contains:

KeyTypeDescription
commandstringCommand to execute (default: 'artisan serve')
dirarrayDirectories to watch
filearraySpecific files to watch
watcharrayFile patterns to watch
extarrayFile extensions to monitor (e.g., ['.php'])
intervalintPolling interval in milliseconds
scan_intervalintFilesystem scan interval

Sources: src/Commands/WatchCommand.php38-49


Dependency Check and Error Handling

Watcher Package Requirement

The command performs a runtime check for the hyperf/watcher package before execution:


If the Hyperf\Watcher\Watcher class is not found, the command outputs an error message and returns without executing. This fail-safe pattern ensures graceful degradation when the optional dependency is missing.

Sources: src/Commands/WatchCommand.php33-36


Execution Flow

Complete Execution Sequence

The handle() method orchestrates the entire watch process:


Sources: src/Commands/WatchCommand.php31-65


Object Creation and Initialization

Option Object Construction

The Option class is instantiated using the make() helper function with the following parameters:

ParameterSourceDescription
optionsMerged configurationComplete watcher configuration array
dir--dir CLI optionAdditional directories to watch
file--file CLI optionAdditional files to watch
restartInverted --no-restart flagWhether to restart server on changes

Sources: src/Commands/WatchCommand.php52-57

Watcher Object Construction

The Watcher class is instantiated with:

ParameterSourceDescription
optionCreated Option instanceConfiguration object
output$this->outputConsole output interface

Sources: src/Commands/WatchCommand.php59-62


Watcher Execution

Run Method

After object construction, the watcher is started by calling $watcher->run(). This method (implemented in the hyperf/watcher package) performs the following:

  1. Initialize File Monitoring: Sets up filesystem watchers based on configured directories, files, and patterns
  2. Start Target Process: Executes the configured command (e.g., php artisan serve)
  3. Monitor Loop: Continuously monitors watched paths for changes
  4. Restart on Change: When changes are detected:
    • Terminates the running process
    • Re-executes the command
    • Outputs change information to console

The restart option controls whether the process is restarted or just monitored.

Sources: src/Commands/WatchCommand.php64


Integration Points

Framework Integration


The WatchCommand is registered in the application through the ConfigProvider like all other commands in the devtool package. However, unlike generator commands, it does not extend GeneratorCommand and does not create files. Instead, it interacts with the runtime environment.

Sources: src/Commands/WatchCommand.php1-66


Dependency Requirements

Package Installation

The watch command requires the hyperf/watcher package to be installed:


This package provides the core file monitoring and process management functionality. Without it, the watch command will display an error message and exit.

Runtime Check: The command uses class_exists(Watcher::class) to verify the package is available before proceeding with execution.

Sources: src/Commands/WatchCommand.php10-36


Default Behavior

When executed without any options, the watch command:

  1. Loads Configuration: Attempts to load from application config, then falls back to vendor default config
  2. Uses Default Command: Executes php artisan serve as the monitored process
  3. Watches Project Files: Monitors paths specified in configuration (typically app/, config/, etc.)
  4. Enables Restart: Automatically restarts the server when changes are detected

This zero-configuration approach allows developers to simply run php artisan watch for immediate hot-reload functionality.

Sources: src/Commands/WatchCommand.php38-50


Use Cases

Development Workflow Enhancement

ScenarioCommandBenefit
Standard developmentphp artisan watchAutomatic restart on any code change
API developmentphp artisan watch -D app/Http/ControllersFocus on controller changes only
Configuration tuningphp artisan watch -D configMonitor configuration file changes
Debugging without restartphp artisan watch -NSee file changes without disrupting running process
Custom server commandConfigure command keyWatch with custom development server

Typical Configuration Example

A .watcher.php file for a typical Hypervel application:


Sources: src/Commands/WatchCommand.php44-49