如何创建服务提供商(单身人士)?

时间:2018-01-30 10:40:22

标签: php laravel laravel-5

我有这样的功能,当我调用它时会创建新的连接:

public function newBaseQueryBuilder()
{
   ...
   $host = config('sphinx.connection.host');
   $port = config('sphinx.connection.port');
   $pdo = new \PDO("mysql:host={$host};port={$port};", '', '');
   $connection = new SphinxConnection($pdo);
   ...
}

创建只创建一个连接的服务提供商吗?

1 个答案:

答案 0 :(得分:0)

将课程绑定为singleton

$this->app->singleton('SphinxConnection', function ($app) {
    $host = config('sphinx.connection.host');
    $port = config('sphinx.connection.port');
    $pdo = new \PDO("mysql:host={$host};port={$port};", '', '');
    return new SphinxConnection($pdo);
});

通过构造函数或方法注入并使用。或者手动注入:

$connection = app('SphinxConnection');