Laravel:如何针对自定义实现更改UrlGenerator(核心绑定)?

Tim*_*idt 3 php ioc-container laravel

我需要使用的自定义实现UrlGenerator。因此,我该如何更改laravel的默认绑定,该默认绑定在内核深处实现为

 'url'                  => ['Illuminate\Routing\UrlGenerator', 'Illuminate\Contracts\Routing\UrlGenerator'],
Run Code Online (Sandbox Code Playgroud)

反对我自己的实现?

此外,我也不是很自信。我认为上面的这一行实际上做了两件事。它将bindinung存储在键“ url”下,并且还将接口映射到类。所以我实际上需要覆盖两者!怎么做?此外,如何确定是否必须将其绑定为“共享”(单例)或“每次新实例”?

非常感谢!

Nes*_*ert 5

看看服务容器指南http://laravel.com/docs/5.1/container

在这种情况下,我认为您需要做的就是告诉应用程序替换已经存在的别名。

为此,我建议创建一个ServiceProvider,将config/app.php文件注册为int,然后在register方法中的该文件中放入如下内容:

$this->app->bind('Illuminate\Routing\UrlGenerator', 'yourownclasshere');
Run Code Online (Sandbox Code Playgroud)

让我们知道它是否有效。

更新:我删除了无效的选项,只留下了有效的选项。


Kos*_*sta 5

我按照内斯特在他的回答中所说的做了,但这对我来说不太有效。所以这就是我所做的让它发挥作用。在我的服务提供商内部,register我首先尝试了以下方法:

$this->app->bind('url', MyCustomProvider::class);
Run Code Online (Sandbox Code Playgroud)

这确实注册了我的 URL 提供程序,而不是默认的提供程序。问题是现在我的提供商无法访问路由。我检查了 Laravel 代码,\Illuminate\Routing\RoutingServiceProvider因为它有一个registerUrlGenerator注册 URL 提供程序的方法。该方法直接实例化了 Laravel URL 生成器Illuminate\Routing\UrlGenerator,并在构造函数中给出了正确的参数。

因此,我在我的服务提供商中也做了同样的事情。$this->app->bind我没有这样做$this->app->singleton('url', function ($app) { ... }),而是在闭包函数中提供了基本相同的代码,RoutingServiceProvider::registerUrlGenerator但创建了 URL 生成器的实例。然后就可以正常工作了,我的生成器现在每次都会被调用。最终的代码是这样的:

// the code is copied from the \Illuminate\Routing\RoutingServiceProvider::registerUrlGenerator() method
$this->app->singleton('url', function ($app) {
    /** @var \Illuminate\Foundation\Application $app */
    $routes = $app['router']->getRoutes();

    $app->instance('routes', $routes);

    // *** THIS IS THE MAIN DIFFERENCE ***
    $url = new \My\Specific\UrlGenerator(
        $routes,
        $app->rebinding(
            'request',
            static function ($app, $request) {
                $app['url']->setRequest($request);
            }
        ),
        $app['config']['app.asset_url']
    );

    $url->setSessionResolver(function () {
        return $this->app['session'] ?? null;
    });

    $url->setKeyResolver(function () {
        return $this->app->make('config')->get('app.key');
    });

    $app->rebinding('routes', static function ($app, $routes) {
        $app['url']->setRoutes($routes);
    });

    return $url;
});
Run Code Online (Sandbox Code Playgroud)

我讨厌复制代码,所以在我看来问题出在基本实现中。它应该为 URL 生成器采用正确的约定,而不是直接实例化基类。