一、保存复杂的配置
场景:
例如对于一个用户系统,需要很多字段来保存不同的配置,如果要为每个配置都添加一个字段的话,数据表会非常大,而且如果需要经常往里面加入新的内容,则需要经常变更这个表的结构
解决方案:
可以考虑用一个json字段来保存所有的配置
结合laravel model里面的cast等特性,也可以比较方便的读取和存储配置值
再结合request validation和自定义哪些字段允许设置就可以实现比较灵活的配置
优劣:
优势是可以很灵活的新增配置,劣势是配置的读取和存储稍复杂了一些,而且如果后期还需要对这些配置进行查询的话,比较困难(不过一般应该不会有很多这方面的需求)
例子:
1、Setting类
<?php
namespace App;
use Exception;
class Settings
{
/**
* The User instance.
*
* @var User
*/
protected $user;
/**
* The list of settings.
*
* @var array
*/
protected $settings = [];
/**
* Create a new settings instance.
*
* @param array $settings
* @param User $user
*/
public function __construct(array $settings, User $user)
{
$this->settings = $settings;
$this->user = $user;
}
/**
* Retrieve the given setting.
*
* @param string $key
* @return string
*/
public function get($key)
{
return array_get($this->settings, $key);
}
/**
* Create and persist a new setting.
*
* @param string $key
* @param mixed $value
*/
public function set($key, $value)
{
$this->settings[$key] = $value;
$this->persist();
}
/**
* Determine if the given setting exists.
*
* @param string $key
* @return boolean
*/
public function has($key)
{
return array_key_exists($key, $this->settings);
}
/**
* Retrieve an array of all settings.
*
* @return array
*/
public function all()
{
return $this->settings;
}
/**
* Merge the given attributes with the current settings.
* But do not assign any new settings.
*
* @param array $attributes
* @return mixed
*/
public function merge(array $attributes)
{
$this->settings = array_merge(
$this->settings,
array_only($attributes, array_keys($this->settings))
);
return $this->persist();
}
/**
* Persist the settings.
*
* @return mixed
*/
protected function persist()
{
return $this->user->update(['settings' => $this->settings]);
}
/**
* Magic property access for settings.
*
* @param string $key
* @throws Exception
* @return
*/
public function __get($key)
{
if ($this->has($key)) {
return $this->get($key);
}
throw new Exception("The {$key} setting does not exist.");
}
}
2、singleton(AppServiceProvider)
public function register()
{
$this->app->singleton('App\Settings', function() {
return User::first()->settings();
});
}
3、helper
<?php
function settings($key = null)
{
$settings = app('App\Settings');
return $key ? $settings->get($key) : $settings;
}
参考网站:
Laravel
登陆发表评论