Php Laravel-从设置表设置全局变量
我试图将我的Php Laravel-从设置表设置全局变量,php,laravel,laravel-5.1,Php,Laravel,Laravel 5.1,我试图将我的settings表中的所有设置存储到一个全局变量中,但我现在被卡住了(我不知道下一步是什么),这是我的实际模型和播种机: model-Settings.php class Setting extends Model { protected $table = 'settings'; public $timestamps = false; protected $fillable = [ 'name', 'value',
settings
表中的所有设置存储到一个全局变量中,但我现在被卡住了(我不知道下一步是什么),这是我的实际模型和播种机:
model-Settings.php
class Setting extends Model
{
protected $table = 'settings';
public $timestamps = false;
protected $fillable = [
'name',
'value',
];
}
seeder-SettingsTableSeeder.php
class SettingsTableSeeder extends Seeder
{
public function run()
{
$settings = [
['name' => 'title', 'value' => ''],
['name' => 'facebook', 'value' => ''],
['name' => 'twitter', 'value' => ''],
['name' => 'instagram', 'value' => '']
];
foreach($settings as $setting){
\App\Setting::create($setting);
}
}
}
我如何将所有数据存储在设置表中,然后从刀片服务器、任何控制器或视图访问这些数据
编辑
现在,我的问题是,如何更新表单中的单个或多个值 我已经建立了这个: 我的路线:
Route::put('/', ['as' => 'setting.update', 'uses' => 'Admin\AdminConfiguracoesController@update']);
我的管理员\管理员配置控制器:
class AdminConfiguracoesController extends AdminBaseController
{
private $repository;
public function __construct(SettingRepository $repository){
$this->repository = $repository;
}
public function geral()
{
return view('admin.pages.admin.configuracoes.geral.index');
}
public function social()
{
return view('admin.pages.admin.configuracoes.social.index');
}
public function analytics()
{
return view('admin.pages.admin.configuracoes.analytics.index');
}
public function update($id, Factory $cache, Setting $setting)
{
$this->repository->findByName($setting);
$cache->forget('settings');
return redirect('admin');
}
}
我的设置存储库:
class SettingRepository
{
private $model;
public function __construct(Setting $model)
{
$this->model = $model;
}
public function findByName($name){
return $this->model->where('name', $name)->update();
}
}
我的刀刃形状:
{!! Form::model(config('settings'), ['class' => 's-form', 'route' => ['setting.update']]) !!}
{{ method_field('PUT') }}
<div class="s-form-item text">
<div class="item-title required">Título do artigo</div>
{!! Form::text('title', null, ['placeholder' => 'Nome do site']) !!}
@if($errors->has('title'))
<div class="item-desc">{{ $errors->first('title') }}</div>
@endif
</div>
<div class="s-form-item s-btn-group s-btns-right">
<a href="{{ url('admin') }}" class="s-btn cancel">Voltar</a>
<input class="s-btn" type="submit" value="Atualizar">
</div>
{!! Form::close() !!}
{!!Form::model(配置('settings'),['class'=>'s-Form','route'=>['setting.update']])
{{method_字段('PUT')}
蒂图罗·多阿蒂戈
{!!Form::text('title',null,['placeholder'=>'Nome do site'])
@如果($errors->has('title'))
{{$errors->first('title')}
@恩迪夫
{!!Form::close()!!}
但事情并不成功。如何将值更新到表中?您可以将数据存储在数据库中,就像在Laravel中通常所做的那样<代码>\App\Setting::create(),
\App\Setting::new()
和其他方法
要使用blade中的值,可以执行{{\App\Setting::where('name','title')->pull('value')}
而且,您还可以为此使用作用域
class Setting extends Model
{
public function scopeFor($query, $settingName)
{
return $query->where('name', $settingName);
}
}
然后您可以使用\App\Setting::for('title')->pull('value')
参见更新2中的改进答案
我会为此添加一个专门的服务提供商。它将读取存储在数据库中的所有设置,并将它们添加到Laravels配置中。这样,设置只有一个数据库请求,您可以访问所有控制器和视图中的配置,如下所示:
config('settings.facebook');
步骤1:创建服务提供商。
您可以使用artisan创建服务提供商:
php artisan make:提供程序设置服务提供程序
这将创建文件app/Providers/SettingsServiceProvider.php
步骤2:将其添加到刚才创建的提供程序的启动方法中:
/**
*引导应用程序服务。
*
*@返回无效
*/
公共函数boot()
{
//Laravel>=5.2,对于Laravel集合('settings',\App\Setting::pull('value','name')->all()),使用'lists'而不是'pull';
}
从Laravel文档:
[引导方法]在所有其他服务提供商注册后调用,这意味着您可以访问框架注册的所有其他服务
步骤3:在应用程序中注册提供商。
将此行添加到config/app.php
中的提供程序数组中:
App\Providers\SettingsServiceProvider::class,
就这样。快乐编码
更新:我想补充一点,启动方法支持依赖项注入。因此,您可以插入一个存储库/一个绑定到存储库的接口,而不是硬编码\App\Setting
,这对于测试非常有用
更新2:因为,应用程序将根据每个请求查询数据库。为了阻止这种情况,您可以缓存设置。基本上有两种方法可以做到这一点
每次管理员更新数据时,将数据放入缓存
设置
只需记住缓存中的设置一段时间,并在管理员每次更新设置时清除缓存
为了使思考更具容错性,我会使用第二个选项。缓存可能会被无意中清除。只要管理员没有设置设置,或者您在服务器崩溃后重新安装,第一个选项将在新安装时失败
对于第二个选项,请更改服务提供程序启动方法:
/**
*引导应用程序服务。
*
*@param\light\Contracts\Cache\Factory$Cache
*@param\App\Setting$设置
*
*@返回无效
*/
公共功能启动(工厂$cache,设置$settings)
{
$settings=$cache->memory('settings',60,function()使用($settings)
{
//Laravel>=5.2,对于Laravel Pull('value','name')->all(),使用'list'代替'pull';
});
config()->set('settings',$settings);
}
现在,管理员更新设置后,您只需让缓存忘记设置键:
/**
*更新设置。
*
*@param int$id
*@param\light\Contracts\Cache\Factory$Cache
*
*@return\light\Http\RedirectResponse
*/
公共函数更新($id,工厂$cache)
{
// ...
//更新设置后,清除“设置”键的缓存:
$cache->forget('settings');
//例如,重定向回设置索引页面,并显示一条成功闪光消息
return redirect()->route('admin.settings.index'))
->带有('updated',true);
}
为了避免在每次请求时查询数据库,您应该在管理员/用户每次更改设置时将其保存到配置文件中
// Grab settings from database as a list
$settings = \App\Setting::lists('value', 'name')->all();
// Generate and save config file
$filePath = config_path() . '/settings.php';
$content = '<?php return ' . var_export($settings, true) . ';';
File::put($filePath, $content);
我想分享我的用例,我的答案可能不是直接回答OP,而是希望回答未来的开发者
这是在Laravel8应用程序中测试的,但我相信它在Laravel5.5及更高版本中可以正常工作
在我的例子中,我有一个带有键和值字段的设置表,您可以在这个迁移文件中看到
<?php
use...;
class CreateSettingsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('settings', function (Blueprint $table) {
$table->id();
$table->string('key')->unique();
$table->text('value');
$table->timestamps();
});
}
//...
}
我又做了一件事,在.gitignore
文件中添加了/config/app\u settings.php
。你到底想做什么?为什么不使用配置文件或环境变量?也许他是想让自己的配置流畅——可以随时更改。顺便说一句,您可以通过blade调用任何类(尽管没有人会推荐这样做),使用完整的名称空间,比如,\App\Settings
。如果你
config('settings.variable_name');
<?php
use...;
class CreateSettingsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('settings', function (Blueprint $table) {
$table->id();
$table->string('key')->unique();
$table->text('value');
$table->timestamps();
});
}
//...
}
<?php
namespace App\Models;
use...;
class Setting extends Model
{
use HasFactory;
//...
/**
* The "booted" method of the model.
*
* @return void
*/
protected static function booted()
{
static::saved(function () {
$settings = static::pluck('value', 'key')->toArray();
$stringify_settings = var_export($settings, true);
$content = "<?php return {$stringify_settings};";
File::put(config_path('app_settings.php'), $content);
});
}
}