VOOZH about

URL: https://deepwiki.com/hypervel/devtool/8.2-observer-generation

⇱ Observer Generation | hypervel/devtool | DeepWiki


Loading...
Menu

Observer Generation

Purpose and Scope

This document covers the make:observer command, which generates model observer classes that respond to Eloquent model lifecycle events. Observers provide a clean way to group event listeners for a specific model into a single class, handling operations such as created, updated, deleted, restored, and force deleted events.

For information about generating standalone event and listener classes, see Event and Listener Generation. For information about model generation, see Model and Factory Generation.

Command Overview

The ObserverCommand class provides the make:observer command for generating model observer classes.

PropertyValue
Command Namemake:observer
Base ClassHyperf\Devtool\Generator\GeneratorCommand
Default NamespaceApp\Observers
Stub Templateobserver.stub

Command Syntax


Available Options

OptionShortTypeDescription
--model-mOptionalThe model that the observer applies to

Sources: src/Generator/ObserverCommand.php11-64

Observer Lifecycle Events

The generated observer class includes methods for five standard Eloquent model lifecycle events:


Observer Lifecycle Event Mapping

Each method in the observer corresponds to a specific model event:

Event MethodTriggered WhenUse Case Examples
created()New model record savedSend welcome email, log creation, create related records
updated()Existing model updatedTrack changes, invalidate cache, notify subscribers
deleted()Model soft deletedArchive data, cleanup related records, log deletion
restored()Soft deleted model restoredRestore related records, log restoration, update indexes
forceDeleted()Model permanently deletedCleanup files, remove permanent references, final cleanup

Sources: src/Generator/stubs/observer.stub11-49

Command Implementation

Class Structure


Sources: src/Generator/ObserverCommand.php11-16 src/Generator/ObserverCommand.php18-23

Model Name Resolution

The command uses sophisticated logic to determine the model name, either from the --model option or by inferring it from the observer class name:


The model name resolution follows this logic src/Generator/ObserverCommand.php31-35:

  1. Explicit Model Option: If --model is provided, use it directly
  2. Inferred from Name: Extract from the observer class name by:
    • Taking the last part of the namespace (explode('\\', $name))
    • Removing the "Observer" suffix using Str::before($model, 'Observer')
    • Defaulting to "Dummy" if the result is empty

Sources: src/Generator/ObserverCommand.php28-46

Placeholder Replacement System

Placeholder Mapping

The replaceClass() method replaces three placeholders in the stub template:

PlaceholderDescriptionExample Value
%NAMESPACE_MODEL%Fully qualified model class nameApp\Models\User
%MODEL%Model class name onlyUser
%MODEL_VARIABLE%Camel-cased variable nameuser

Model Namespace Configuration

The model namespace is determined from configuration src/Generator/ObserverCommand.php37-38:


The default is App\Models, but this can be customized through the configuration system.

Sources: src/Generator/ObserverCommand.php37-45

Stub Template Structure

The observer stub template defines all five lifecycle event methods with consistent structure:


Each method follows the same pattern src/Generator/stubs/observer.stub11-49:

  1. PHPDoc comment describing the event
  2. Public method signature with typed model parameter
  3. Void return type
  4. Empty implementation body for developer to fill in

Sources: src/Generator/stubs/observer.stub1-51

Configuration

Configurable Settings

The ObserverCommand supports two configuration overrides via getConfig():

Configuration KeyDefault ValuePurpose
stub__DIR__ . '/stubs/observer.stub'Custom stub template path
namespaceApp\ObserversDefault namespace for observers
model_namespaceApp\ModelsBase namespace for models

Sources: src/Generator/ObserverCommand.php48-56

Usage Examples

Basic Observer Generation

Generate an observer by inferring the model name from the observer class name:


This creates app/Observers/UserObserver.php observing the User model based on naming convention.

Explicit Model Specification

Generate an observer with explicit model specification:


This creates an observer for the Post model, regardless of the observer's class name.

Short Option Syntax

Using the short option flag:


Generated File Example

Given the command php artisan make:observer UserObserver, the generated file structure would be:


Integration with Model System

Observer Registration

After generating an observer, it must be registered with the model. This is typically done in a service provider:


Observer vs Event/Listener Pattern

AspectObserverEvent/Listener
OrganizationAll model events in one classSeparate classes per event
Use CaseModel-specific lifecycle eventsGeneric application events
RegistrationVia Model::observe()Via event service provider
GranularityCoarse (model-level)Fine (event-level)

For non-model events or when you need multiple listeners for the same event, use the event/listener pattern documented in Event and Listener Generation.

Sources: src/Generator/ObserverCommand.php1-64 src/Generator/stubs/observer.stub1-51