Is it possible to DI dependencies in Drupal 8 but initialize it with values from a config object?
For example, SoapClient requires specifying the WSDL when called. I have different WSDL URLs depending on what environment I am using (test/prod etc).
I know you can do this from the services yaml file, but I have not read of a way where you can reference a value or value(s) from a config object.
My ultimate goal is to create a decorator or factory for SoapClient, but I'm not sure which.
edit: updated with code.
An interface:
<?php
namespace Drupal\iana_netforum_auth\Factory;
use SoapClient;
interface SoapClientFactoryInterface {
/**
* Create a SoapClient.
*
* This method should prepopulate the SoapClient with values from our
* module configuration so it is ready to use.
*
* @return SoapClient
*/
public function create() : SoapClient;
}
The factory:
<?php
namespace Drupal\iana_netforum_auth\Factory;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\iana_netforum_auth\Exception\NetforumException;
use SoapClient;
class SoapClientFactory implements SoapClientFactoryInterface {
public function __construct(ConfigFactoryInterface $config_factory) {
$this->configFactory = $config_factory;
}
public function create() : SoapClient {
$config = $this->configFactory->get('iana_netforum_auth.settings');
$arguments = [];
try {
if ($config->get('mode') == 'live') {
$endpoint = $config->get('live_endpoint');
}
else {
$endpoint = $config->get('dev_endpoint');
$arguments = [
'trace' => $config->get('enable_trace'),
'exceptions' => $config->get('enable_exceptions')
];
}
return new SoapClient($endpoint, $arguments);
}
catch (SoapFault $error) {
throw new NetforumException('Invalid WSDL endpoint specified.');
}
}
}
The class:
class NetforumClient implements NetforumClientInterface {
protected $username;
protected $password;
protected $token;
protected $authorizationHeaders;
/**
* Drupal\Core\Config\ConfigFactoryInterface definition.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* Drupal\iana_netforum_auth\Factory\SoapClientFactoryInterface definition.
*
* @var \Drupal\iana_netforum_auth\Factory\SoapClientFactoryInterface
*/
protected $soapClient;
/**
* Class constructor.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* An instance of ConfigFactoryInterface.
* @param \Drupal\iana_netforum_auth\Factory\SoapClientFactoryInterface $soap_client_factory
* An instance of SoapClientFactoryInterface.
*/
public function __construct(ConfigFactoryInterface $config_factory, SoapClientFactoryInterface $soap_client_factory) {
$this->configFactory = $config_factory;
$this->soapClient = $soap_client_factory->create();
}