且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Laravel服务提供者覆盖连接器类

更新时间:2023-01-10 15:08:26

Laravel无法从容器中解析Connector类,因此尝试按类名覆盖连接器将不起作用.

Laravel does not resolve the Connector classes from the container, so attempting to override the connector by class name will not work.

您可以在中看到Illuminate/Database/Connectors/ConnectionFactory::createConnector 连接器的解析方式. Laravel只会执行return new PostgresConnector(或适合驱动程序的任何一个),因此它不会在容器中查找类名.

You can see in Illuminate/Database/Connectors/ConnectionFactory::createConnector how the connectors are resolved. Laravel just does a return new PostgresConnector (or whichever one is appropriate for the driver), so it does not look in the container for the class name.

但是,在它新"建立一个Connector之前,它会确实检查容器以查看是否存在使用字符串'db.connector.[driver]'绑定到驱动程序的连接器,其中[driver]是db驱动程序名称.

However, before it "new"s up a Connector, it does check the container to see if there is a connector bound to the driver using the string 'db.connector.[driver]', where [driver] is the db driver name.

因此,您无需绑定容器中的类名,而需要绑定字符串'db.connector.your-driver-name'.因此,如果您创建了自己的自定义驱动程序(例如vertica),则可以将连接器绑定到'db.connector.vertica'.或者,如果您想覆盖内置的postgres连接器,则可以将连接器绑定到'db.connector.pgsql'.

Therefore, instead of attempting to bind the class name in the container, you need to bind the string 'db.connector.your-driver-name'. So, if you created your own custom driver (e.g. vertica), you would bind your connector to 'db.connector.vertica'. Or, if you want to overwrite the built in postgres connector, you would bind your connector to 'db.connector.pgsql'.

基于您要覆盖postgres连接器的假设,您的服务提供商注册方法如下:

Based on the assumption you're trying to overwrite the postgres connector, your service provider register method would look like:

public function register()
{
    $this->app->bind('db.connector.pgsql', \App\Vertica\PostgresConnector::class);
}