【问题标题】:Changing the app url inside a Laravel 4.2 Artisan command在 Laravel 4.2 Artisan 命令中更改应用程序 url
【发布时间】:2016-01-11 05:15:30
【问题描述】:

我运行一个用 Laravel 4.2 构建的多租户站点。在 App 配置中,我知道您可以设置单个基本 URL,例如

/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/

'url' => 'http://apples.local',

我已经构建了一个 Artisan 命令来向用户发送预定的电子邮件,无论他们通过哪个域访问该站点。因此该命令需要生成具有不同域的 url,例如http://oranges.local.

在我的命令中,我试图在生成 URL 之前更改 app.url 配置变量,但它似乎没有影响:

Config::set('app.url', 'http://oranges.local');
$this->info('App URL: ' . Config::get('app.url'));
$this->info('Generated:' . URL::route('someRoute', ['foo', 'bar']));

尽管在运行时物理上改变了配置,但这仍然总是产生:

App URL: http://oranges.local
Generated: http://apples.local/foo/bar

URL 生成器完全忽略了应用配置!

我知道我可以设置多个环境并将--env=oranges 传递给 Artisan,但在我的用例中这并不实用。我只想要在运行时设置应用程序 url 站点范围的能力。

有什么想法吗?

【问题讨论】:

  • 从 URL 生成器获取路由路径(不是绝对路径)并单独附加域是否可行?例如,URL::route('someRoute', ['foo', 'bar'], false); 只会生成 /foo/bar
  • 谢谢,是的,我也考虑过,但问题还是我的用例。您的建议适用于我自己生成的 url,但我也使用生成自己的 url 的包,例如。 github.com/iwyg/jitimage 并且这些也需要呈现正确的域,而不仅仅是默认的根 url。

标签: php laravel laravel-4 laravel-artisan


【解决方案1】:

好的,whoacowboy 是对的,并且根本没有考虑配置。我发现该站点的基本 URL(即使在 Artisan 命令中)似乎完全来自 Symphony Request 对象。

因此,要在 Artisan 中更改/欺骗域,以下方法将起作用:

Request::instance()->headers->set('host', 'oranges.local');

在完成更改后再次恢复主机名可能是明智之举,但至少在我的用例中,这解决了我的所有问题!

【讨论】:

    【解决方案2】:

    URL::route() 调用 $route->domain()$route->action['domain'] 获取域

    /**
     * Get the domain defined for the route.
     *
     * @return string|null
     */
    public function domain()
    {
        return isset($this->action['domain']) ? $this->action['domain'] : null;
    }
    

    所以它看起来不像是使用Config::get('app.url') 来设置网址。

    benJ 似乎有个好主意。为什么不手动写网址呢?

    $emailURL = Config::get('app.url') . '/foo/bar/' 并收工。

    【讨论】:

    • 感谢您的建议。重复我对 benJ 的评论,这是对我自己编写的 url 的完美建议,但是我用于调整大小/缓存图像的 iwyg/jitimage 等软件包会生成它们自己的 url,它们也需要正确的域。但是,是的,这可能是我最终必须做出的牺牲。
    猜你喜欢
    • 2016-05-09
    • 2018-06-22
    • 1970-01-01
    • 2016-02-07
    • 1970-01-01
    • 2015-02-21
    • 2016-09-11
    • 2017-01-18
    • 2021-05-10
    相关资源
    最近更新 更多