Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Parameter Bundle Laravel Package

cannibal/parameter-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require cannibal/parameter-bundle
    

    Add the bundle to your config/app.php under providers:

    Cannibal\ParameterBundle\ParameterServiceProvider::class,
    
  2. Publish Configuration (if needed):

    php artisan vendor:publish --provider="Cannibal\ParameterBundle\ParameterServiceProvider"
    

    This generates a config/parameter.php file for customization.

  3. Basic Usage: Define a parameter group in config/parameter.php:

    'groups' => [
        'app' => [
            'name' => 'Application Settings',
            'parameters' => [
                'site_name' => ['value' => 'My App', 'type' => 'string'],
                'max_items' => ['value' => 100, 'type' => 'integer'],
            ],
        ],
    ],
    
  4. First Use Case: Retrieve a parameter in a controller or service:

    use Cannibal\ParameterBundle\ParameterManager;
    
    public function showSettings(ParameterManager $manager)
    {
        $siteName = $manager->get('app.site_name'); // Returns 'My App'
        $maxItems = $manager->get('app.max_items'); // Returns 100
    }
    

Implementation Patterns

Dependency Injection

  • Automatic Binding: The ParameterManager is auto-bound via the service provider. Inject it directly into controllers, services, or commands:

    public function __construct(ParameterManager $manager) { ... }
    
  • Lazy Loading: Use the get() method with a fallback for optional parameters:

    $timeout = $manager->get('api.timeout', 30); // Defaults to 30 if 'api.timeout' is missing
    

Configuration Management

  • Grouped Parameters: Organize parameters hierarchically (e.g., app.site_name, api.timeout). Use dot notation for nested access:

    $manager->get('database.connections.mysql.host');
    
  • Dynamic Updates: Override parameters in .env (prefix with PARAMETER_):

    PARAMETER_app_site_name=Custom App Name
    

    Or update runtime via the manager:

    $manager->set('app.site_name', 'Updated Name');
    
  • Validation: Define validation rules in the config:

    'parameters' => [
        'api.timeout' => [
            'value' => 60,
            'type' => 'integer',
            'validation' => ['min' => 1, 'max' => 300],
        ],
    ],
    

    Access validated values:

    $timeout = $manager->get('api.timeout'); // Throws exception if invalid
    

Integration with Laravel Features

  • Cache Parameters: Enable caching in config/parameter.php:

    'cache' => true,
    

    Parameters are cached automatically (uses Laravel’s cache driver).

  • Environment-Specific Parameters: Use environment variables to switch parameter sets:

    'environments' => [
        'local' => ['app.debug' => true],
        'production' => ['app.debug' => false],
    ],
    

    Set APP_ENV to control active parameters.

  • Seeding Parameters: Create a seeder to populate default parameters:

    use Cannibal\ParameterBundle\ParameterManager;
    
    public function run(ParameterManager $manager)
    {
        $manager->set('app.site_name', 'Default Site');
    }
    

Advanced Usage

  • Parameter Collections: Fetch all parameters for a group:

    $appParams = $manager->getGroup('app');
    // Returns: ['site_name' => 'My App', 'max_items' => 100]
    
  • Type Casting: The bundle handles type casting (e.g., string, integer, boolean, array). Custom types can be added via events (see Gotchas).

  • Events: Listen for parameter changes:

    use Cannibal\ParameterBundle\Events\ParameterUpdated;
    
    Event::listen(ParameterUpdated::class, function ($event) {
        Log::info("Parameter {$event->key} updated to {$event->value}");
    });
    

Gotchas and Tips

Pitfalls

  1. Configuration Overrides:

    • .env values override config values, but only if prefixed with PARAMETER_. Forgetting the prefix will ignore the env variable.
    • Example: PARAMETER_app_site_name=New Name works; APP_SITE_NAME=New Name does not.
  2. Type Mismatches:

    • The bundle throws Cannibal\ParameterBundle\Exceptions\ParameterException if a parameter’s type doesn’t match its value. Validate types early in development:
    try {
        $invalid = $manager->get('app.max_items'); // Throws if value is not an integer
    } catch (ParameterException $e) {
        Log::error($e->getMessage());
    }
    
  3. Caching Quirks:

    • Disabling cache in config forces a database/config reload on every get(). Useful for development but slow in production.
    • Clear cache manually if parameters don’t update:
    php artisan cache:clear
    
  4. Namespace Collisions:

    • Avoid parameter keys that conflict with Laravel’s reserved names (e.g., app.key). Prefix custom keys (e.g., custom.app.key).

Debugging

  • Dump All Parameters: Use Tinker to inspect all parameters:

    php artisan tinker
    >>> \Cannibal\ParameterBundle\Facades\Parameter::all();
    
  • Check Loaded Groups: Verify which groups are registered:

    $manager->getGroups(); // Returns ['app', 'api', ...]
    

Extension Points

  1. Custom Parameter Types: Extend the bundle by adding a custom type handler. Implement Cannibal\ParameterBundle\Contracts\TypeHandler:

    use Cannibal\ParameterBundle\Contracts\TypeHandler;
    
    class JsonTypeHandler implements TypeHandler
    {
        public function handle($value)
        {
            return json_decode($value, true);
        }
    }
    

    Register it in the service provider:

    $this->app->bind('parameter.type.json', JsonTypeHandler::class);
    
  2. Custom Storage: Override the default storage (config/database) by binding a custom Cannibal\ParameterBundle\Contracts\ParameterStorage implementation.

  3. Validation Rules: Extend validation by adding custom rules to the validation array in config. Example for a regex rule:

    'parameters' => [
        'user.email' => [
            'value' => '[email protected]',
            'validation' => ['regex' => '/^[^\s@]+@[^\s@]+\.[^\s@]+$/'],
        ],
    ],
    

Performance Tips

  • Batch Fetching: Fetch multiple parameters in one call to reduce overhead:

    $manager->get(['app.site_name', 'api.timeout']); // Returns ['app.site_name' => '...', 'api.timeout' => 60]
    
  • Disable Cache in Development: Set 'cache' => env('APP_DEBUG') === false in config/parameter.php to avoid stale data during development.

Security

  • Sensitive Parameters: Avoid storing secrets (e.g., API keys) in parameters. Use Laravel’s native .env or vault solutions instead.
  • Authorization: Restrict access to parameter updates in admin panels. Use middleware or gates to protect routes that call $manager->set().
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
oxygen/data
oxygen/core
jengo/base
xiloryx/log-collector
a21ns1g4ts/filament-stripe
la-php/laravel-admin
artisan-build/community-prompts
vleroy/smart
ayles-software/laravel-australian-public-holidays
cboxdk/laravel-id-spatie
cboxdk/laravel-id-billing
cboxdk/laravel-id-billing-bridge
simple-as-fuck/php-performance-log
hsluv/hsluv
seampact/codegen
seampact/hooks
seampact/ir
mehedimi/laravel-amp-mail
happones/laravel-vue-i18n-generator
jwerd/inertia-table