Skip to content

Instantly share code, notes, and snippets.

@herveguetin
Last active October 25, 2018 20:45
Show Gist options
  • Save herveguetin/0ce677397a29037033a5e49b8f4f9307 to your computer and use it in GitHub Desktop.
Save herveguetin/0ce677397a29037033a5e49b8f4f9307 to your computer and use it in GitHub Desktop.
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