我正在尝试设置一些默认路由参数,无论上下文如何,这些参数都将在我的应用程序中全局工作。在 documentation for URL generation给出的示例是使用适用于 HTTP 的中间件,但在非 HTTP 上下文中不会被调用。当从 CLI 调用时,我也需要它来工作。
我的第一个想法是有一个调用 defaults
的服务提供商。开机方法:
<?php
namespace App\Providers;
use Illuminate\Routing\UrlGenerator;
use Illuminate\Support\ServiceProvider;
class UrlDefaults extends ServiceProvider
{
public function boot(UrlGenerator $urlGenerator): void
{
$urlGenerator->defaults([
'foo' => 'abc',
'bar' => 'xyz',
]);
}
}
但这不适用于 HTTP 请求:
Route::get('test', function (\Illuminate\Routing\UrlGenerator $urlGenerator) {
dump($urlGenerator->getDefaultParameters());
});
输出
[]
我相信这是因为在
UrlGenerator
, setRequest
方法无条件设置routeGenerator
属性(property)给 null
.我的服务提供者的引导方法在引导过程中被调用,但随后设置的请求破坏了我的默认设置。//Illuminate/Routing/UrlGenerator.php
public function setRequest(Request $request)
{
$this->request = $request;
$this->cachedRoot = null;
$this->cachedSchema = null;
$this->routeGenerator = null;
}
倾倒
UrlGenerator
boot
期间然后在我的路线文件中再次可以证明这一点:如您所见,
UrlGenerator
实例两次都相同,但 RouteUrlGenerator
在 routeGenerator
属性变了。我不确定设置这些默认值的更好方法。
最佳答案
不知道为什么将近一年后这会引起关注,但我最终自己找到了解决方案。
为了在原始问题中添加更多信息,这样做的目的是让我们拥有相同的代码实例,为我们的实时应用程序和沙盒应用程序提供动力。让这个工作涉及更多,但这个问题只是关于 View 中链接的 URL 生成。生成的所有链接始终同时包含子域和 tld,因此此代码始终注入(inject)这些值。
这些 View 都呈现为对 HTTP 请求的响应,例如在我们的客户区域,但也作为非 HTTP 请求的一部分,例如生成发票并将其通过电子邮件发送给客户的计划任务。
无论如何,解决方案:
对于非 HTTP 上下文,服务提供者可以设置默认值:
<?php namespace App\Providers;
use App\Support\UrlDefaults;
use Illuminate\Routing\UrlGenerator;
use Illuminate\Support\ServiceProvider;
class UrlDefaultsServiceProvider extends ServiceProvider
{
public function boot(UrlGenerator $urlGenerator): void
{
$urlGenerator->defaults(UrlDefaults::getDefaults());
}
}
由于没有路由会导致我最初提出的问题,所以这很有效。
对于 HTTP 上下文,
RouteMatched
监听事件并注入(inject)默认值:<?php namespace App\Listeners;
use App\Support\UrlDefaults;
use Illuminate\Routing\Router;
use Illuminate\Routing\UrlGenerator;
/**
* Class SetUrlDefaults
*
* This class listeners for the RouteMatched event, and when it fires, injects the route paramaters (subdomain, tld,
* etc) into the defaults of the UrlGenerator
*
* @package App\Listeners
*/
class SetUrlDefaults
{
private $urlGenerator;
private $router;
public function __construct(UrlGenerator $urlGenerator, Router $router)
{
$this->urlGenerator = $urlGenerator;
$this->router = $router;
}
public function handle(): void
{
$paramaters = array_merge(UrlDefaults::getDefaults(), $this->router->current()->parameters);
$this->urlGenerator->defaults($paramaters);
}
}
UrlDefaults
只是一个返回数组的简单类:<?php namespace App\Support;
class UrlDefaults
{
public static function getDefaults(): array
{
return [
'tld' => config('app.url.tld'),
'api' => config('app.url.api'),
'foo' => config('app.url.foo'),
'bar' => config('app.url.bar'),
];
}
}
关于php - Laravel:如何设置全局可用的默认路由参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54218181/