定制 whilesmart/eloquent-model-configuration 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

whilesmart/eloquent-model-configuration

最新稳定版本:1.0.10

Composer 安装命令:

composer require whilesmart/eloquent-model-configuration

包简介

Laravel package for managing model-specific configurations with type safety and easy persistence

README 文档

README

This Laravel package provides a complete configuration solution ready to be integrated into your application.

Features

  • NoSQL-like Flexibility: Add schema-less dynamic attributes to any Eloquent model without database migrations
  • Type-Safe Storage: Supports strings, integers, arrays, JSON, dates with automatic type casting via ConfigValueType enum
  • Polymorphic Relationships: Any model can have configurations through a single, flexible relationship
  • Ready-to-use endpoints: Complete API for managing configurations
  • OpenAPI documentation: Automatically generated documentation using PHP attributes
  • Configuration file: Easily customize settings
  • Laravel agnostic considerations: designed with future framework agnosticism in mind

Development

This package includes a Docker development environment and Makefile for easy development.

Quick Start

# Start the development environment make up # Install dependencies make install # Run tests make test # Run code formatter make pint # Show all available commands make help

Available Make Commands

  • make up - Start Docker containers
  • make down - Stop Docker containers
  • make install - Install dependencies
  • make test - Run tests
  • make pint - Run Laravel Pint code formatter
  • make lint - Alias for pint
  • make fresh - Fresh start (down, up, install)
  • make setup - Complete setup with tests
  • make check - Run all checks (formatting + tests)
  • make shell - Access container shell

Installation

1. Require the package

composer require whilesmart/eloquent-model-configuration

2. Publish the configuration and migrations:

You do not need to publish the migrations and configurations except if you want to make modifications. You can choose to publish the migrations, routes, controllers separately or all at once.

2.1 Publishing only the routes

Run the command below to publish only the routes.

php artisan vendor:publish --tag=model-configuration-routes php artisan migrate

The routes will be available at routes/model-configuration.php. You should require this file in your api.php file.

 require 'model-configuration.php';

2.2 Publishing only the migrations

+If you would like to make changes to the migration files, run the command below to publish only the migrations.

php artisan vendor:publish --tag=model-configuration-migrations php artisan migrate

The migrations will be available in the database/migrations folder.

2.3 Publish only the controllers

By default the controllers assign the device to the currently logged in user. If you would like to assign the device to another model, you can publish the controllers and make the necessary changes to the published file.
To publish the controllers, run the command below

php artisan vendor:publish --tag=model-configuration-controllers php artisan migrate

The controllers will be available in the app/Http/Controllers directory. Finally, change the namespace in the published controllers to your namespace.

2.4 Publish the documentation

To publish the openapi documentation, run the command below

php artisan vendor:publish --tag=model-configuration-docs

The documentation will be available at app/Http/Documentation

2.5 Publish everything

To publish the migrations, routes and controllers, you can run the command below

php artisan vendor:publish --tag=model-configuration php artisan migrate

Note: See section 2.1 above to make the routes accessible

2.6 Middleware configuration

The default controller gets the authenticated user from the Request object. The default routes must be placed in an auth middleware. Set your auth middleware in the config/model-configuration.php file.

<?php return [ ..., 'auth_middleware' => ['auth:sanctum'], ];

2.7 More configurations

Config keys are case-insensitive by default. For example ConfigName and configname are considered the same. To change this behavior, set the allow_case_insensitive_keys config variable to true.

<?php return [ ..., 'allow_case_insensitive_keys' => true, ];

Config names can take only the following:

  1. Lowercase characters: a to z
  2. Uppercase characters: A to Z
  3. Numbers: 0 to 9
  4. Some special characters: hyphen (-), underscore (_), fullstop (.) and plus (+)

You can also restrict the key names allowed by adding each allowed key name in the allowed_keys array

<?php return [ ..., 'allowed_keys' => ['key-1','key-2'], ];

2.8 Using Custom Configuration Models

If you need to extend the Configuration model with additional functionality (e.g., soft deletes, auditing, or custom traits), you can use your own model class:

Step 1: Create a custom model that extends the base Configuration model:

<?php namespace App\Models; use Illuminate\Database\Eloquent\SoftDeletes; use Whilesmart\ModelConfiguration\Models\Configuration as BaseConfiguration; class Configuration extends BaseConfiguration { use SoftDeletes; protected $fillable = ['configurable_id', 'configurable_type', 'key', 'type', 'value', 'metadata']; }

Step 2: Configure the package to use your custom model:

<?php return [ ..., 'model' => \App\Models\Configuration::class, ];

Step 3: Use the package normally - no need to override traits or controllers!

The package will automatically use your custom model for all configuration operations. This allows you to:

  • Add Laravel traits (SoftDeletes, Auditable, etc.)
  • Include additional attributes and relationships
  • Implement custom business logic at the model level
  • Receive automatic package updates without maintaining custom controllers

2.9 Hooks

Register hooks to customize behavior. A single hook class can implement one or both interfaces:

<?php return [ ..., 'hooks' => [ PaginateResultsHook::class, OnboardingCompletedHook::class, ], ];
ModelHookInterface (HTTP Request Hooks)

Runs before/after HTTP requests to configuration endpoints.

class PaginateResultsHook implements ModelHookInterface { public function beforeQuery(mixed $data, ConfigAction $action, Request $request): mixed { if ($action == ConfigAction::INDEX) { return $data->paginate(); } return $data; } public function afterQuery(mixed $results, ConfigAction $action, Request $request): mixed { return $results; } }
ConfigValueHookInterface (Value Change Hooks)

Runs when setConfigValue() is called, useful for triggering side effects.

use Illuminate\Database\Eloquent\Model; use Whilesmart\ModelConfiguration\Enums\ConfigValueType; use Whilesmart\ModelConfiguration\Interfaces\ConfigValueHookInterface; use Whilesmart\ModelConfiguration\Models\Configuration; class OnboardingCompletedHook implements ConfigValueHookInterface { public function onConfigValueSet( Model $model, string $key, mixed $value, ConfigValueType $type, Configuration $configuration, bool $wasCreated ): void { if ($key === 'onboarding_completed' && $value === 'true') { app(OnboardingService::class)->complete($model); } } }

The hook receives:

  • $model - The model that owns the configuration (e.g., User)
  • $key - The configuration key that was set
  • $value - The new value
  • $type - The ConfigValueType enum
  • $configuration - The Configuration model instance
  • $wasCreated - true if this was a new configuration, false if updated
Combined Hook

A single class can implement both interfaces:

class MyHook implements ModelHookInterface, ConfigValueHookInterface { public function beforeQuery(mixed $data, ConfigAction $action, Request $request): mixed { return $data; } public function afterQuery(mixed $results, ConfigAction $action, Request $request): mixed { return $results; } public function onConfigValueSet( Model $model, string $key, mixed $value, ConfigValueType $type, Configuration $configuration, bool $wasCreated ): void { // Handle value changes } } ### 3. Model Relationships We have implemented a Trait `Configurable` that handles relationships. If your model has configuration, simply use the `Configurable` trait in your model definition. ```php use Whilesmart\ModelConfiguration\Traits\Configurable class MyModel { use Configurable; } 

You can call yourModel->configurations() to get the list of configuration tied to the model

$model = new MyModel(); $model->configurations();

The Configurable trait also has the getConfigurationssAttribute() method. If you want to append the configuration to the model response, simply add configuration to your model's $appends

use Whilesmart\ModelConfiguration\Traits\Configurable; class MyModel { use Configurable; protected $appends = ['configurations']; }

The following additional methods are available also available in the Configurable trait

  1. getConfig() gets the full details of a particular config. It returns a Configuration object
$model = new MyModel(); $config = $model->getConfig('default_wallet'); $config_id = $config->id;
  1. getConfigValue() gets the value of a particular config. It also ensures the value is returned in the correct type
$model = new MyModel(); $config_value = $model->getConfigValue('default_wallet');
  1. getConfigType() gets the type of a particular config. It returns a ConfigValueType enum
$model = new MyModel(); $config_type = $model->getConfigType('default_wallet');
  1. setConfigValue() sets/updates the value of a particular config. It returns a Configuration object
$model = new MyModel(); $config= $model->setConfigValue('default_wallet',1, ConfigValueType::Integer);

Usage

After installation, the following API endpoints will be available:

  • POST /api/configurations: Registers a new config linked to the current logged in user.
  • GET /api/configurations: Retrieves all configurations linked to the current logged in user.
  • PUT /api/configurations/{id}: Updates the information in a configuration.
  • DELETE /api/configurations/{id}: Deletes a configuration.
  • OpenAPI Documentation: Accessible via a route that your OpenAPI package defines.

Example Request:

{ "value":"unique_token_string", "type":"string" }

统计信息

  • 总下载量: 330
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 2
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-01-04

承接程序开发

PHP开发

VUE

Vue开发

前端开发

小程序开发

公众号开发

系统定制

数据库设计

云部署

网站建设

安全加固