Injecting interfaces, singleton, factory, models in Magento 2
<?php | |
class SomeClass | |
{ | |
/** | |
* @var \Magento\Framework\App\Config\ScopeConfigInterface | |
*/ | |
private $configInterface; | |
/** | |
* @var \Magento\Framework\App\Config | |
*/ | |
private $concreteConfig; | |
/** | |
* @var \Magento\Framework\App\ConfigFactory | |
*/ | |
private $configFactory; | |
public function __construct( | |
// Preferred for singleton => Inject a singleton but let Magento chose which concrete class thanks to DI | |
\Magento\Framework\App\Config\ScopeConfigInterface $configInterface, // Resolves to \Magento\Framework\App\Config | |
// Inject a concrete singleton | |
\Magento\Framework\App\Config $concreteConfig, | |
// Inject the factory of the model for later instanciation. Magento will automatically create the class in the /generated dir when required | |
\Magento\Framework\App\ConfigFactory $configFactory | |
) | |
{ | |
$this->configInterface = $configInterface; | |
$this->concreteConfig = $concreteConfig; | |
$this->configFactory = $configFactory; | |
} | |
public function someMethod() | |
{ | |
// Singleton: first way | |
$firstSingleton = $this->configInterface->getValue('some/path'); | |
// Singleton: second way | |
$secondSingleton = $this->concreteConfig->getValue('some/path'); | |
// New instance | |
/** @var \Magento\Framework\App\Config $newConfig */ | |
$newConfig = $this->configFactory->create(); | |
$newValue = $newConfig->getValue('some/path'); | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment