我需要检查当前域是什么,并根据它设置配置变量(或其他?)。然后它可以用在控制器中。模型或视图。我们的想法是构建一个"模板"网站有一个数据库,但提供的数据将取决于使用的域。
我正考虑在中间件或服务提供商中这样做(我是Laravel 5的新手)。
最好的方法是什么?任何建议/意见表示赞赏:)
答案 0 :(得分:9)
这就是我最终做的事情: 1 - 检测App \ Providers \ ConfigServiceProvider中的域并将其添加到config:
public function register() {
switch (Request::server("HTTP_HOST")) {
case 'domain1.com':
$country = 'AA';
break;
case 'domain2.com':
$country = 'BB';
break;
default:
$country = 'CC';
break;
}
$config = app('config');
$config->set('country', $country);
}
2 - 通过将其添加到基本控制器和模型类(如果有的话),使其在所有控制器和模型中可用:
abstract class Controller extends BaseController {
use DispatchesCommands,
ValidatesRequests;
function __construct() {
$this->country = config('country');
}
}
3 - 在我的情况下,创建全局范围和特征以在需要按国家/地区过滤所有查询的模型中注册它是很有用的。我已将它们添加到Models的子目录中:
<强>范围强>
use Illuminate\Database\Eloquent\ScopeInterface;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
class CountryScope implements ScopeInterface {
/**
* Apply scope on the query.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function apply(Builder $builder, Model $model) {
//$builder->whereNull($model->getQualifiedDeletedAtColumn());
$column = $model->getCountryIDColumn();
$builder->where($column, $model->country);
}
/**
* Remove scope from the query.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function remove(Builder $builder, Model $model) {
$query = $builder->getQuery();
$column = $model->getCountryIDColumn();
foreach ((array) $query->wheres as $key => $where)
{
if ($where['column'] == $column) {
unset($query->wheres[$key]);
$query->wheres = array_values($query->wheres);
}
}
}
}
<强>性状强>
trait CountryTrait {
/**
* Boot the country trait for a model.
*
* @return void
*/
public static function bootCountryTrait()
{
static::addGlobalScope(new CountryScope);
}
/**
* Get the country id column name for applying the scope.
*
* @return string
*/
public function getCountryIDColumn()
{
return $this->getTable().'.'.'country_id';
//return 'country_id';
}
}
在每个需要它的模型中
class Project extends Model {
use Traits\CountryTrait;
...
}
如果您知道更好的方法,请发布新的答案,如果您有改进建议,请发表评论。