【问题标题】:Impementing global app settings for Laravel API?为 Laravel API 实现全局应用设置?
【发布时间】:2019-11-10 00:22:11
【问题描述】:

我希望实现一些全局应用设置,例如应用名称、一周的第一天和其他功能标志。最终目标是让管理员通过 API 获取和编辑这些内容。

这样做最方便的方法是什么?我已经尝试使用设置模型来存储键值对,但这对我来说没有意义,因为所需的设置应该是硬编码的并且不会改变,并且播种设置表听起来并不理想。提前致谢!

【问题讨论】:

  • 请通过https://stackoverflow.com/questions/32745104/laravel-global-settings-model链接。

标签: laravel api settings


【解决方案1】:

您可以从 Laravel 提供的配置函数中访问应用名称。

$appName = config('app.name'); 
// This value is retrieved from .env file of APP_NAME=

如果你必须存储多个与星期相关的值,你可以创建一个新的配置文件 week.php

//config/week.php
return [
    ...
    'first_day_of_the_week' => 0
]; 

为了检索 first_day_of_the_week,您可以使用相同的函数 config

$firstDayOfTheWeek = config('week.first_day_of_the_week')

与其他基本标志类似,您可以创建一个新的配置文件。 您可以稍后使用以下命令缓存您的配置变量。

php artisan config:cache

你也可以在 laravel 项目的任何首选位置创建一个 Helper 类。我将助手类保存在 App\Helpers 中。

<?php

namespace App\Helpers;

use Carbon\Carbon;

class DateHelpers
{
    public const DATE_RANGE_SEPARATOR = ' to ';

    public static function getTodayFormat($format = 'Y-m-d')
    {
        $today = Carbon::now();
        $todayDate = Carbon::parse($today->format($format));
        return $todayDate;
    }
    ....
}

如果需要在Laravel项目中获取方法值,可以通过

$getTodayDateFormat = App\Helpers\DateHelpers::getTodayFormat();

编辑 1:

根据问题描述。您需要在设置表中创建一行。

//create_settings_table.php Migration File
public function up()
    {
        // Create table for storing roles
        Schema::create('settings', function (Blueprint $table) {
            $table->increments('id');
            $table->string('app_name')->default("My App Name");
            $table->unsignedInteger('first_day_of_the_week')->default(1);
            ....
            $table->timestamps();
        });
    }

您只需要一行设置表即可检索/更新默认值。

//检索第一天

$first_day_of_the_week = App\Setting::first()->first_day_of_the_week;

//更新第一天

...
$first_day_of_the_week = request('first_day_of_the_week');
App\Setting::first()->update([
    'first_day_of_the_week' => $first_day_of_the_week
]);

【讨论】:

  • 如果用户需要通过 API 更改这些怎么办?
  • 要从 API 中获取反映,您需要将这些值存储到数据库中,正如您在问题描述中提到的那样。
  • 我添加了一个 sn-p 可能会帮助您使其动态化。
猜你喜欢
  • 2013-03-14
  • 2015-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-16
  • 1970-01-01
  • 2014-11-24
  • 1970-01-01
相关资源
最近更新 更多