Laravel 全局设置模型
我正在 Laravel 5 中构建一个小型 CRUD 应用程序.我有一些应用程序范围的设置,例如SiteTitle"和BaseURL",我想让我的管理员能够从 UI 进行更改.我的整个应用程序使用 base.blade.php 模板,该模板扩展到不同的视图+控制器,这是最有可能使用这些设置的地方.
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.
相关文章