dadehpardaz/laravel-app-settings

一个用于存储和管理应用程序所有设置的UI包

1.5 2021-03-07 13:24 UTC

This package is not auto-updated.

Last update: 2024-10-01 05:16:55 UTC


README

Latest Version on Packagist Software License Build Status Total Downloads

使用 qcod/laravel-app-settings 将设置管理器(带UI)添加到您的Laravel应用程序中。它将设置存储在数据库中,默认使用Bootstrap 4进行样式化,但您可以配置它以与任何CSS系统一起使用。

所有保存在数据库中的设置都会被缓存,以提高性能,通过减少SQL查询至零。

安装

1 - 您可以通过composer安装此包

$ composer require qcod/laravel-app-settings

2 - 如果您正在安装Laravel 5.4或更低版本,您需要手动通过在config/app.php提供者数组中添加它并在别名数组中添加外观来注册服务提供者。

'providers' => [
    //...
    QCod\AppSettings\AppSettingsServiceProvider::class,
]

'aliases' => [
    //...
    "AppSettings" => QCod\AppSettings\Facade::class
]

Laravel 5.5或更高版本中,服务提供者会自动注册,并将外观AppSettings::get('app_name')可用。

3 - 现在您应该使用以下命令发布配置文件:

php artisan vendor:publish --provider="QCod\AppSettings\AppSettingsServiceProvider" --tag="config"

它将创建config/app_settings.php,其中包含所有配置选项以及定义您的设置输入的方式,分为不同的部分。

4 - 现在运行迁移php artisan migrate以创建设置表。

入门

首先,您需要定义您在设置页面中想要的所有设置。例如,我们需要这些设置app_namefrom_emailfrom_name。让我们在配置中定义它

config/app_settings.php

<?php

[
    //...
    // All the sections for the settings page
    'sections' => [

        'app' => [
            'title' => 'General Settings',
            'descriptions' => 'Application general settings.', // (optional)
            'icon' => 'fa fa-cog', // (optional)

            'inputs' => [
                [
                    'name' => 'app_name', // unique key for setting
                    'type' => 'text', // type of input can be text, number, textarea, select, boolean, checkbox etc.
                    'label' => 'App Name', // label for input
                    // optional properties
                    'placeholder' => 'Application Name', // placeholder for input
                    'class' => 'form-control', // override global input_class
                    'style' => '', // any inline styles
                    'rules' => 'required|min:2|max:20', // validation rules for this input
                    'value' => 'QCode', // any default value
                    'hint' => 'You can set the app name here' // help block text for input
                ]
            ]
        ],
        'email' => [
            'title' => 'Email Settings',
            'descriptions' => 'How app email will be sent.',
            'icon' => 'fa fa-email',

            'inputs' => [
                [
                    'name' => 'from_email',
                    'type' => 'email',
                    'label' => 'From Email',
                    'placeholder' => 'Application from email',
                    'rules' => 'required|email',
                ],
                [
                 'name' => 'from_name',
                 'type' => 'text',
                 'label' => 'Email from Name',
                 'placeholder' => 'Email from Name',
                ]
            ]
        ]
    ]
];

现在,如果您访问http://yourapp.com/settings路由,您将获得包含您定义的所有设置的UI。

Laravel App Settings UI

您可以通过更改app_settings配置来更改布局,以适应您的应用程序设计。

// View settings
'setting_page_view' => 'your_setting', // blade view path

接下来,打开resources/views/your_setting.blade.php,并在您想要显示设置的任何位置包含设置部分

@extends('layout')

@section('content')
    @include('app_settings::_settings')
@endsection

现在您应该看到设置页面是您应用程序的一部分,并且具有您的布局 😎。

访问保存的设置

您有setting('app_name', 'default value')和外观AppSettings::get('app_name', 'default value'),您可以使用它们来获取存储的设置。

更改设置URL

如果您的应用程序需要不同的URL来访问设置页面,您可以从配置中更改

// Setting page url, will be used for get and post request
'url' => 'app-settings',
// http://yourapp.com/app-settings

使用分组设置

很多时候,您想要将设置存储在组中。从版本1.1开始,您可以从config/app_settings.php中定义组名。您可以使用一个更接近返回组名的字符串的函数

return [

    // All the sections for the settings page
    'sections' => [...]
    
    ...
    // settings group
    'setting_group' => function() {
        return 'user_'.auth()->id();
    }

在这种情况下,您可以为每个用户提供不同的设置。

无UI使用

如果您只想将键值对存储到数据库中,而无需UI来管理设置(例如在API中),则应使用qcod/laravel-settings包。此包在内部使用它来持久化设置。

如果您想同时使用UI和作为键值对存储在数据库中的设置,请简单地使用辅助函数setting()AppSetting::get('app_name')来从数据库中存储和检索设置。为此,您不需要在app_settings.php配置中定义任何部分和输入。

当同时使用UI和键值对作为设置时,请确保在config/app_settings.php中设置'remove_abandoned_settings' => false,否则在从UI保存设置时,任何未定义的输入字段将被删除。

以下是可用方法的列表

setting()->all($fresh = false);
setting()->get($key, $defautl = null);
setting()->set($key, $value);
setting()->has($key);
setting()->remove($key);

在JavaScript中访问设置

许多情况下,您需要从JavaScript中访问这些设置。您可以这样做的一种方式是将它们作为全局变量放入您的布局blade模板中。

// layout.blade.php
<head>
<title>@yield('title', 'Settings')</title>
<script>
    window.App = {!! json_encode([
            'settings' => \setting()->all(),
            'anyOtherThings' => []
    ]); !!}
</script>
</head>

有了这个,您将能够访问Vue组件或任何JavaScript代码中定义的设置。

App.settings.app_name;

// or define a computed property on Component root level
const app = new Vue({
  el: "#app",
  computed: {
    myApp() {
      return window.App;
    }
  }
});

// access it like this
myApp.settings.app_name;

输入类型

这里列出了您可以定义的所有输入类型及其属性,但如果有需要,您也可以添加自己的自定义输入类型。

每个输入都必须具有至少nametypelabel属性。

文本、数字、电子邮件

这些实际上只是通过类型更改以及数字类型的minmax属性来实现的。

// text
[
    'name' => 'app_name',
    'type' => 'text',
    'label' => 'App Name',
    // optional fields
    'data_type' => 'string',
    'rules' => 'required|min:2|max:20',
    'placeholder' => 'Application Name',
    'class' => 'form-control',
    'style' => 'color:red',
    'value' => 'QCode',
    'hint' => 'You can set the app name here'
],

// number
[
    'name' => 'users_allowed',
    'type' => 'number',
    'label' => 'Number of users allowed',
    // optional fields
    'data_type' => 'int',
    'min' => 5,
    'max' => 100,
    'rules' => 'required|min:5|max:100',
    'placeholder' => 'Number of users allowed',
    'class' => 'form-control',
    'style' => 'color:red',
    'value' => 5,
    'hint' => 'You can set the number of users allowed to be added.'
]

// email
[
    'name' => 'from_email',
    'type' => 'email',
    'label' => 'From Email',
    // optional fields
    'rules' => 'required|email',
    'placeholder' => 'Emails will be sent from this address',
    'class' => 'form-control',
    'style' => 'color:red',
    'value' => 'noreply@example.com',
    'hint' => 'All the system generated email will be sent from this address.'
]

可以使用data_type来转换输入数据,它可以是arrayint|integer|numberboolean|boolstring。如果您需要其他类型,您始终可以使用访问器来完成。

文本区域

文本区域字段与文本相同,但它具有rowscols属性。

[
    'type' => 'textarea',
    'name' => 'maintenance_note',
    'label' => 'Maintenance note',
    'rows' => 4,
    'cols' => 10,
    'placeholder' => 'What you want user to show when app is in maintenance mode.'
],

选择

您可以使用选项定义选择框。

[
    'type' => 'select',
    'name' => 'date_format',
    'label' => 'Date format',
    'rules' => 'required',
    'options' => [
        'm/d/Y' => date('m/d/Y'),
        'm.d.y' => date("m.d.y"),
        'j, n, Y' => date("j, n, Y"),
        'M j, Y' => date("M j, Y"),
        'D, M j, Y' => date('D, M j, Y')
    ]
],

从数据库中选择选项

您还可以动态填充选择选项。在大多数情况下,它们将来自数据库,只需使用闭包来完成此操作。

[
    'type' => 'select',
    'name' => 'city',
    'label' => 'City',
    'rules' => 'required',
    'options' => function() {
        return App\City::pluck('name', 'id')->toArray()
    }
],

注意:如果您需要动态解决字段值,您可以使用闭包(匿名函数)来处理大多数输入字段。

布尔值

布尔值只是一个具有是或否选项的单选输入组,您也可以通过设置options数组将其更改为选择。

// as radio inputs
[
    'name' => 'maintenance_mode',
    'type' => 'boolean',
    'label' => 'Maintenance',
    'value' => false,
    'class' => 'w-auto',
    // optional fields
    'true_value' => 'on',
    'false_value' => 'off',
],
// as select options
[
    'name' => 'maintenance_mode',
    'type' => 'boolean',
    'label' => 'Maintenance',
    'value' => false,
    'class' => 'w-auto',
    // optional fields
    'options' => [
        '1' => 'Yes',
        '0' => 'No',
    ],
],

复选框

添加复选框输入

[
    'type' => 'checkbox',
    'label' => 'Try Guessing user locals',
    'name' => 'guess_local',
    'value' => '1'
]

复选框组

添加一组复选框

[
    'type' => 'checkbox_group',
    'label' => 'Days to run scheduler',
    'name' => 'scheduler_days',
    'data_type' => 'array', // required
    'options' => [
        'Sunday', 'Monday', 'Tuesday'
    ]
]

图像、文件

您可以使用imagefile输入上传文件。文件上传将自动处理,旧文件将被新文件替换。

如果您在输入上定义了mutator,则上传处理取决于您,您必须从mutator返回上传文件的路径以存储在设置中并处理旧文件。

。在大多数情况下,您不需要使用mutator。

您可以为传入的文件定义rules以进行验证,它可以是图像或任何文档。

[
    'name' => 'logo',
    'type' => 'image',
    'label' => 'Upload logo',
    'hint' => 'Must be an image and cropped in desired size',
    'rules' => 'image|max:500',
    'disk' => 'public', // which disk you want to upload, default to 'public'
    'path' => 'app', // path on the disk, default to '/',
    'preview_class' => 'thumbnail', // class for preview of uploaded image
    'preview_style' => 'height:40px' // style for preview
]

// handle uploads by yourself using `mutator`
[
    'name' => 'logo',
    'type' => 'image',
    'label' => 'Upload logo',
    'hint' => 'Must be an image and cropped in desired size',
    'rules' => 'image|max:500',

    // a simple mutator
    'mutator' => function($value, $key) {
        // handle image do some reszing etc
        $image = Intervention\Image::make(request()->file($key));

        $path = Storage::disk('public')->put(
            $imagePath,
            (string) $image->encode(null, $imageQuality),
            'public'
        );

        // delete old image etc
        Storage::disk('public')->delete(\setting($key));

        // finally return new path to be stored in db
        return $path;
    }
]

不使用Bootstrap 4

如果您的应用程序不使用Twitter Bootstrap 4,您可以在app_settings.php中轻松自定义它,以遵循您的CSS库,如Bulma、Foundatio CSS或任何其他自定义解决方案。

// Setting section class setting
'section_class' => 'card mb-3',
'section_heading_class' => 'card-header',
'section_body_class' => 'card-body',

// Input wrapper and group class setting
'input_wrapper_class' => 'form-group',
'input_class' => 'form-control',
'input_error_class' => 'has-error',
'input_invalid_class' => 'is-invalid',
'input_hint_class' => 'form-text text-muted',
'input_error_feedback_class' => 'text-danger',

// Submit button
'submit_btn_text' => 'Save Settings',
'submit_success_message' => 'Settings has been saved.',

自定义应用程序设置视图

在某些情况下,如果您的应用程序需要自定义视图,您可以将应用程序设置视图发布,然后您可以自定义设置字段的每个部分。

php artisan vendor:publish --provider="QCod\AppSettings\AppSettingsServiceProvider" --tag="views"

自定义输入类型

尽管这个包提供了您需要的所有输入,但如果您需要包含在内的事物,您只需在应用程序设置部分中定义输入,并为其提供一个自定义类型即可,例如日期范围字段type="daterange"。接下来,您需要发布视图,并在resources/views/vendor/app_settings/fields/文件夹中添加一个blade视图,并匹配字段的名称,如daterange.blade.php

@component('app_settings::input_group', compact('field'))
<div class="row">
    <div class="col-md-6">
        <label>
            From
            <input
                type="date"
                name="from_{{ $field['name'] }}"
                class="{{ array_get( $field, 'class', config('app_settings.input_class', 'form-control')) }}"
                value="{{ old('from_'.$field['name'], array_get(\setting('from_'.$field['name']), 'from')) }}"
            >
        </label>
    </div>
    <div class="col-md-6">
        <label>
            To
            <input
                type="date"
                name="to_{{ $field['name'] }}"
                class="{{ array_get( $field, 'class', config('app_settings.input_class', 'form-control')) }}"
                value="{{ old('to_'.$field['name'], array_get(\setting($field['name']), 'to')) }}"
            >
        </label>
    </div>
</div>
@endcomponent

@component('app_settings::input_group', compact('field'))将添加labelhint以及error反馈文本。

要使用此自定义输入,您应该在app_settings.php中定义它,如下所示

<?php
[
    'name' => 'registration_allowed',
    'type' => 'daterange',
    'label' => 'Registration Allowed',
    'hint' => 'A date range when registration is allowed',
    'mutator' => function($value, $key) {
        // combine both from_registration_allowed and to_registration_allowed
        $rangeValues = [
            'from' => request('from_registration_allowed'),
            'to' => request('to_registration_allowed'),
        ];

        return json_encode($rangeValues);
    },
    'accessor' => function($value, $key) {
        return is_null($value) ? ['from' => '', 'to' => ''] : json_decode($value, true);
    },
]

这将渲染您的日期范围字段。您可以使用此方法创建任何类型的字段。

访问器和变换器

就像Eloquent模型一样,它允许您在输入上定义访问器和变换器,这在创建自定义输入时非常有用。

访问器

访问器可以在访问时更改设置值,它可以是Closer或具有handle($value, $key)方法的类。

<?php
// app settings input
[
    'name' => 'app_name',
    'type' => 'text',
    'accessor' => '\App\Accessors\AppNameAccessor'
];

// use a class
class AppNameAccessor {
    public function handle($value, $key) {
        return ucfirst($value);
    }
}

// or you can use Closer
[
    'name' => 'app_name',
    'type' => 'text',
    'accessor' => function($value, $key) {
        return ucfirst($value);
    }
];

变更器

变更器可以在数据存储之前更改设置值,就像访问器一样,它可以是Closer或者具有handle($value, $key)方法的类。

<?php
// app settings input
[
    'name' => 'app_name',
    'type' => 'text',
    'mutator' => '\App\Mutators\AppNameMutator'
];

// use a class
class AppNameMutator {
    public function handle($value, $key) {
        return ucfirst($value). ' Inc.';
    }
}

// or you can use Closer
[
    'name' => 'app_name',
    'type' => 'text',
    'mutator' => function($value, $key) {
        return ucfirst($value). ' Inc.';
    }
];

使用不同的控制器

为了使用您的控制器显示和存储设置,您可以通过更改app_settings.controller来实现。

// change the controller in config/app_settings.php at the bottom

// Controller to show and handle save setting
'controller' => '\App\Http\Controllers\SettingsController',

请确保您的控制器中包含index()store(Request $request)方法。

// Controller
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use QCod\AppSettings\SavesSettings;
use App\Http\Controllers\Controller;

class SettingsController extends Controller 
{ 
    use SavesSettings;
    
    // you can override following methods from trait
    
    // to display the settings view
    public function index()
    {
       return 'I am settings page'.
    }
    
    // to store settings changes
    public function store(Request $request)
    {
       return $request->all().
    }
}

配置文件

<?php
return [

    // All the sections for the settings page
    'sections' => [
        'app' => [
            'title' => 'General Settings',
            'descriptions' => 'Application general settings.', // (optional)
            'icon' => 'fa fa-cog', // (optional)

            'inputs' => [
                [
                    'name' => 'app_name', // unique key for setting
                    'type' => 'text', // type of input can be text, number, textarea, select, boolean, checkbox etc.
                    'label' => 'App Name', // label for input
                    // optional properties
                    'placeholder' => 'Application Name', // placeholder for input
                    'class' => 'form-control', // override global input_class
                    'style' => '', // any inline styles
                    'rules' => 'required|min:2|max:20', // validation rules for this input
                    'value' => 'QCode', // any default value
                    'hint' => 'You can set the app name here' // help block text for input
                ]
            ]
        ],
        'email' => [
            'title' => 'Email Settings',
            'descriptions' => 'How app email will be sent.',
            'icon' => 'fa fa-envelope',

            'inputs' => [
                [
                    'name' => 'from_email',
                    'type' => 'email',
                    'label' => 'From Email',
                    'placeholder' => 'Application from email',
                    'rules' => 'required|email',
                ],
                [
                    'name' => 'from_name',
                    'type' => 'text',
                    'label' => 'Email from Name',
                    'placeholder' => 'Email from Name',
                ]
            ]
        ]
    ],

    // Setting page url, will be used for get and post request
    'url' => 'settings',

    // Any middleware you want to run on above route
    'middleware' => [],

    // View settings
    'setting_page_view' => 'app_settings::settings_page',
    'flash_partial' => 'app_settings::_flash',

    // Setting section class setting
    'section_class' => 'card mb-3',
    'section_heading_class' => 'card-header',
    'section_body_class' => 'card-body',

    // Input wrapper and group class setting
    'input_wrapper_class' => 'form-group',
    'input_class' => 'form-control',
    'input_error_class' => 'has-error',
    'input_invalid_class' => 'is-invalid',
    'input_hint_class' => 'form-text text-muted',
    'input_error_feedback_class' => 'text-danger',

    // Submit button
    'submit_btn_text' => 'Save Settings',
    'submit_success_message' => 'Settings has been saved.',

    // Remove any setting which declaration removed later from sections
    'remove_abandoned_settings' => false,

    // Controller to show and handle save setting
    'controller' => '\QCod\AppSettings\Controllers\AppSettingController'
    
    // settings group
    'setting_group' => function() {
        // return 'user_'.auth()->id();
        return 'default';
    }
];

变更日志

请参阅变更日志获取最近更改的更多信息。

测试

该软件包包含一些由Orchestra设置的集成/烟雾测试,可以通过phpunit运行这些测试。

$ composer test

贡献

请参阅贡献指南获取详细信息。

安全

如果您发现任何与安全相关的问题,请通过电子邮件saquibweb@gmail.com联系,而不是使用问题跟踪器。

鸣谢

关于QCode.in

QCode.in (https://www.qcode.in) 是由Saqueib撰写的一个博客,涵盖了关于全栈Web开发的所有内容。

许可证

MIT许可证。请参阅许可证文件获取更多信息。