Bindings & observers
register() and boot() stay overridable for bespoke wiring — override them and call the parent first. Two helpers cover the most common config-driven wiring:
public function register(): void
{
parent::register();
// Bind a contract to the class named in config, with a default. Absent/null/blank → the
// default; a value that isn't an existing class implementing the contract (false, a
// typo'd class name) throws InvalidConfigurationException when the contract resolves.
$this->bindFromConfig(CommentRepository::class, 'comments.repository', EloquentCommentRepository::class);
}
public function boot(): void
{
parent::boot();
// Attach an observer to the model named in config.
$this->observesModel('comments.models.comment', CommentObserver::class);
}bindFromConfig()
bindFromConfig(string $contract, string $configKey, string $default) binds the contract to a closure that reads the config key on each resolution and builds that class through the container. An absent, null or blank ('' or whitespace) key binds the default class. Any other value must name an existing class that is a $contract — false, a typo’d class name or a class of the wrong type throws InvalidConfigurationException when the contract resolves (“Configuration value [comments.repository] must be a class-string of [{contract}], [{given}] given.”), never a silent fall-back to the default. Call it from register(), after parent::register(), so the package config is already merged.
observesModel()
observesModel(string $configKey, string $observer) resolves the model class named at the config key and registers the observer on it. The class is validated through ModelResolver with no default, so the key is required: an absent or blank key, or one that does not name an Eloquent model, throws InvalidConfigurationException at boot instead of failing silently. Call it from boot().
The config behind them
Both keys live in the package config, so a host swaps either one without touching the package:
// config/comments.php
return [
'repository' => EloquentCommentRepository::class,
'models' => [
'comment' => Comment::class,
],
];
// A host swaps either one without touching the package:
// 'repository' => App\Comments\CachedCommentRepository::class,
// 'models' => ['comment' => App\Models\Comment::class],Show your open-source love
This package is free and MIT-licensed. If it saves you time, a one-off donation or a Patreon membership keeps it maintained, tested and documented.
More ways to support, including cryptoBy donating, you agree to our donation terms.
Want this built into your product?
We integrate our packages into custom Laravel and AI builds. Tell us what you're working on and we'll reply within 48 hours.