Laravel全局设置模型 [英] Laravel Global Settings Model

查看:243
本文介绍了Laravel全局设置模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Laravel 5构建一个小型CRUD应用程序.我有一些应用程序范围的设置,例如"SiteTitle"和"BaseURL",我想让管理员可以从UI进行更改.我的整个应用程序使用base.blade.php模板,该模板可扩展到不同的views + controller,这是最有可能使用这些设置的地方.

I'm working on building a small CRUD app in Laravel 5. I have a few app wide settings such as "SiteTitle" and "BaseURL" I'd like to give my admins the ability to change from the UI. My whole app uses a base.blade.php template that gets extended to the different views+controllers, this is where these settings would most likely be used.

类似的东西:

<h1><a href="#">{{ $setting->SiteName }}</a></h1>

我在数据库表中存储了与Setting.php模型相关的设置.

I have the settings stored in a database table that are tied to a Setting.php model.

我希望不是我的每个控制器方法都向数据库查询这些设置,以将它们仅传递给模板base.blade.php.

I'd rather not everyone of my controller methods query the database for these settings to just pass them up to the template base.blade.php.

创建可在整个应用中重复使用的某种类型的全局设置变量的最佳方法是什么?

What's the best way of creating some type of global setting variable I can reuse throughout the app?

提前谢谢!

推荐答案

您可以创建一个服务提供商,例如SettingsServiceProvider,该服务提供商从数据库中加载所有设置,然后对其进行缓存.然后,在随后的页面加载中,它可能会返回缓存的设置值,而不是查询数据库,而这是您应该正确考虑的.

You could create a service provider, say SettingsServiceProvider, that loads all the settings from the database and then caches them. Then on subsequent page loads, it could return cached setting values rather than querying the database, which you should be rightfully concerned about.

简单的事情:

class SettingsServiceProvider extends ServiceProvider
{
    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('settings', function ($app) {
            return $app['cache']->remember('site.settings', 60, function () {
                return Setting::pluck('value', 'key')->toArray();
            });
        });
    }
}

根据Laravel的命名约定,假设您的设置模型称为Setting.然后,您可以像这样访问设置:

Assuming your settings model is called Setting as per Laravel’s naming conventions. You can then access settings like so:

<h1>{{ array_get(app('settings'), 'site.name') }}</h1>

如果您想以更漂亮的方式访问设置,可以创建一个辅助函数:

If you wanted a prettier way of accessing settings, you could create a helper function:

function setting($key)
{
    return array_get(app('settings'), $key);
}

将这样使用:

<h1>{{ setting('site.name') }}</h1>

几乎模拟config()辅助函数的用法.

Almost emulating the config() helper function’s usage.

这篇关于Laravel全局设置模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆