klaude/eloquent-preferences
Composer 安装命令:
composer require klaude/eloquent-preferences
包简介
Preferences for Laravel Eloquent models
README 文档
README
Use this library to bind multiple key/value pair preferences to your application's Eloquent models. Preferences are stored in your application's database so they can be easily stored and queried for. This library supports Eloquent 5 through 8 installed either standalone or as a part of the full Laravel framework. Issues and pull requests are welcome! See CONTRIBUTING.md for more information.
Installation
Run composer require klaude/eloquent-preferences to download and install the library.
Configuring In Laravel
- Add
EloquentPreferencesServiceProvidertoconfig/app.php:
// ... return [ // ... 'providers' => [ // ... KLaude\EloquentPreferences\EloquentPreferencesServiceProvider::class, ], // ... ];
- Install the configuration and database migration files:
$ php artisan vendor:publish
-
Model preferences are stored in the "model_preferences" database table by default. If you would like to use a different table then edit the "table" entry in
config/eloquent-preferences.php. -
Install the model preferences database:
$ php artisan migrate
Configuring Without Laravel
-
Model preferences are stored in the "model_preferences" database table by default. If you would like to use a different table then define the
MODEL_PREFERENCE_TABLEconstant at your project's point of entry with your preferred table name. -
Install the model preferences database. There are a number of ways to do this outside of Laravel. Here's the schema blueprint to apply:
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Schema\Blueprint; use KLaude\EloquentPreferences\Preference; // ... Model::getConnectionResolver() ->connection() ->getSchemaBuilder() ->create((new Preference)->getQualifiedTableName(), function (Blueprint $table) { $table->increments('id'); $table->string('preference'); $table->string('value'); $table->morphs('preferable'); $table->timestamps(); });
Usage
Add the HasPreferences trait to the Eloquent models that you would like to have related preferences.
use KLaude\EloquentPreferences\HasPreferences; // ... class MyModel extends Model { use HasPreferences; // ... }
This builds a polymorphic has-many relationship called "preferences" that you can query on your model like any other Eloquent relationship. Model preferences are modeled in the KLaude\EloquentPreferences\Preference class. A preference object has preference, value, and Eloquent's built-in created_at and updated_at attributes. The HasPreferences trait can be used by any number of model classes in your application.
// Retrieving preferences via Eloquent /** @var KLaude\EloquentPreferences\Preference $myPreference */ $myPreference = MyModel::find($someId)->preferences()->where('preference', 'my-preference')->get(); // Saving preferences via Eloquent $preference = new Preference; $preference->preference = 'some preference'; $preference->value = 'some value'; $myModel->preferences()->save($preference);
Eloquent queries can be run directly on the Preference class as well.
/** @var Illuminate\Database\Eloquent\Collection|KLaude\EloquentPreferences\Preference[] $preferences */ $preferences = Preference::whereIn('preference', ['foo', 'bar'])->orderBy('created_at')->get();
Helper Methods
The HasPreferences trait has a number of helper methods to make preference management a little easier.
Retrieving Preferences
Call the getPreference($preferenceName) or prefers($preferenceName) methods to retrieve that preference's value.
$numberOfFoos = $myModel->getPreference('number-of-foos'); $myModel->prefers('Star Trek over Star Wars') ? liveLongAndProsper() : theForceIsWithYou();
Setting Preferences
Call the setPreference($name, $value) or setPreferences($arrayOfNamesAndValues) methods to set your model's preference values. Setting a preference either creates a new preference row if the preference doesn't exist or updates the existing preference with the new value.
$myModel->setPreference('foo', 'bar'); $myModel->setPreferences([ 'foo' => 'bar', 'bar' => 'baz', ]);
Removing Preferences
Call the clearPreference($preferenceName), clearPreferences($arrayOfPreferenceNames), or clearAllPreferences() methods to remove one, many, or all preferences from a model. Clearing preferences removes their associated rows from the preferences table.
$myModel->clearPreference('some preference'); $myModel->clearPreferences(['some preference', 'some other preference']); $myModel->clearAllPreferences();
Default Preference Values
By default, getPreference() and prefers() return null if the preference is not stored in the database. There are two ways to declare default preference values:
- Use an optional second parameter to
getPreference()andprefers()to define a default value per call. If the preference is not stored in the database then the default value is returned.
// $myPreference = 'some default value' $myPreference = $myModel->getPreference('unknown preference', 'some default value');
- Avoid requiring extra parameters to every
getPreference()andprefers()call by declaring a protected$preference_defaultsarray in your model containing a key/value pair of preference names and their default values. If the preference is not stored in the database but is defined in$preference_defaultsthen the value in$preference_defaultsis returned. If neither of these exist then optional default value parameter ornullis returned.
class MyModel extends Model { use HasPreferences; // ... protected $preference_defaults = [ 'my-default-preference' => 'my-default-value', ]; } // ... // $myPreference = 'my-default-value' $myPreference = $myModel->getPreference('my-default-preference'); // $myPreference = 'fallback value' $myPreference = $myModel->getPreference('my-unstored-preference', 'fallback value');
Please note default preference values only apply when using the getPreference() and prefers() methods. Default values are not honored when retrieving preferences by Eloquent query.
Casting Preference Values
Preferences are stored as strings in the database, but can be cast to different types when retrieved.
Declare a protected $preference_casts array in your model containing a key/value pair of preference names and the types to cast their values to. Preferences are stored and cast according to the same rules as Eloquent's attribute type casts.
class MyModel extends Model { use HasPreferences; // ... protected $preference_casts = [ 'boolean-preference' => 'boolean', 'floating-point-preference' => 'float', 'date-preference' => 'date', ]; }
As with default values, casting preferences is only performed when using the getPreference(), prefers(), setPreference(), and setPreferences() helper methods.
Hidden Preference Attributes
By default all preference model attributes are visible when exporting to JSON. However it is possible to declare hidden attributes that act in the same manner as Eloquent's hidden attributes. There are two ways to declare which preference attributes to hide from JSON export:
- If this library is being used in a Laravel project then declare hidden attributes in the "hidden-attributes" key in
config/eloquent-preferences.php.
return [
// ...
'hidden-attributes' => ['created_at', 'updated_at'],
// ...
];
- If this library is being used outside the Laravel framework then define the
MODEL_PREFERENCE_HIDDEN_ATTRIBUTESconstant at your project's point of entry with a comma-separated list of attributes to hide from JSON export.
const MODEL_PREFERENCE_HIDDEN_ATTRIBUTES = 'created_at,updated_at';
klaude/eloquent-preferences 适用场景与选型建议
klaude/eloquent-preferences 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 16.62k 次下载、GitHub Stars 达 30, 最近一次更新时间为 2015 年 12 月 21 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「laravel」 「eloquent」 「preferences」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 klaude/eloquent-preferences 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 klaude/eloquent-preferences 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 klaude/eloquent-preferences 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
A Laravel Nova Tool to let users manage global settings created from code.
A Laravel Eloquent model trait for translatable resource
A package for automatically encrypting and decrypting Eloquent attributes in Laravel 5.5+, based on configuration settings.
Lightweight settings management for CodeIgniter 4
Help to manage meta data on Laravel Eloquent model
A package to cast json fields, each sub-keys is castable
统计信息
- 总下载量: 16.62k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 30
- 点击次数: 20
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2015-12-21