I have a class which is dependent on a DB connection, something like this:
class Test
{
private $conn;
public function __construct(Connection $conn) {
$this->conn = $conn;
}
}
The service for this could look like this:
services:
service.test:
class: Test
arguments:
- ["@database_connection"]
Now, I'd like to pass my own connection service / object that at startup creates a Connection
. But I can't pass it as an argument as it wants a Connection
object, not a factory.
How can I best approach this?
I've tried adding a setConnection
on the Test
class, but it would be nicer to keep the current definition and service intact.
There is actually ready solution for that in Symfony's Service Container.
Your database_connection
service should be configured to use a factory to create its instance. That would be something like this:
services:
database_connection:
class: Connection
factory: [ConnectionFactory, createConnection]
And if the factory is a service too, it might look like this:
services:
database_connection:
class: Connection
factory: ["@connection_factory", createConnection]
More information about that can be found here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With