Mar*_*ine 9 php laravel laravel-4
我正在构建一个子域指向用户的应用程序.我怎样才能获得地址的子域名 - 除了路线之外的其他地址?
Route::group(array('domain' => '{subdomain}.project.dev'), function() {
Route::get('foo', function($subdomain) {
// Here I can access $subdomain
});
// How can I get $subdomain here?
});
Run Code Online (Sandbox Code Playgroud)
不过,我已经建立了一个混乱的解决方案:
Route::bind('subdomain', function($subdomain) {
// Use IoC to store the variable for use anywhere
App::bindIf('subdomain', function($app) use($subdomain) {
return $subdomain;
});
// We are technically replacing the subdomain-variable
// However, we don't need to change it
return $subdomain;
});
Run Code Online (Sandbox Code Playgroud)
我想在路由之外使用变量的原因是基于该变量建立数据库连接.
xma*_*cos 10
$subdomain在实际的Route回调中注入,它在group闭包内是未定义的,因为Request尚未解析.
我不明白为什么你需要把它现有的组瓶盖内但实际的外Route回调.
如果你想要的是Request在解析后的任何地方都可以使用它,你可以设置一个后置过滤器来存储$subdomain值:
Config::set('request.subdomain', Route::getCurrentRoute()->getParameter('subdomain'));
Run Code Online (Sandbox Code Playgroud)
更新:应用组过滤器来设置数据库连接.
Route::filter('set_subdomain_db', function($route, $request)
{
//set your $db here based on $route or $request information.
//set it to a config for example, so it si available in all
//the routes this filter is applied to
Config::set('request.subdomain', 'subdomain_here');
Config::set('request.db', 'db_conn_here');
});
Route::group(array(
'domain' => '{subdomain}.project.dev',
'before' => 'set_subdomain_db'
), function() {
Route::get('foo', function() {
Config::get('request.subdomain');
});
Route::get('bar', function() {
Config::get('request.subdomain');
Config::get('request.db');
});
});
Run Code Online (Sandbox Code Playgroud)
Mos*_*atz 10
在提出这个问题后不久,Laravel实现了一种在路由代码中获取子域的新方法.它可以像这样使用:
Route::group(array('domain' => '{subdomain}.project.dev'), function() {
Route::get('foo', function($subdomain) {
// Here I can access $subdomain
});
$subdomain = Route::input('subdomain');
});
Run Code Online (Sandbox Code Playgroud)
请参阅文档中的 "访问路径参数值" .
以上不适用于 Laravel 5.4 或 5.6。请测试这个:
$subdomain = array_first(explode('.', request()->getHost()));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20078 次 |
| 最近记录: |