I am actually trying to instanciate a class dynamically with these arguments.
Here is the code I use in class A:
/** @var string $source */
$source = '\Foo\Bar\My\Class'; // Dynamic value that I am not aware because it is from other extensions
/** @var bool $isClassLoadable */
$isClassLoadable = $this->definedClasses->isClassLoadable($source);
if (!$isClassLoadable) {
return false;
}
/** @var Model $model */
$model = $this->getModel(); // loaded model with data
/** @var \Magento\Framework\Simplexml\Config $config */
$config = $this->getConfig(); // loaded configuration with data
/** @var ProcessorInterface $processorInstance */
$processorInstance = $this->objectManager->create(
$source,
[
$model,
$config,
]
);
The \Foo\Bar\My\Class class code:
public function __construct(
Model $model,
Config $config
) {
$this->model = $model;
$this->config = $config;
\Zend_Debug::dump($this->model->debug());
\Zend_Debug::dump($this->config);
}
Here my two parameters are an empty model and an empty configuration.
Questions
- Is it a good practice to use ObjectManager to create class from a "string" ?
- If it is a "good practice" what is the way to keep my data between my class A and the \Foo\Bar\My\Class instanciation ?
EDIT
I am aware that using ObjectManager is a bad practice and Factory are here to avoid that but the $source is from a configuration and maybe third part extensions, I don't know his value. I hardcoded it for the purpose of my example.
Factoryto my$sourcestring and mix the two methods ? – Matthéo Geoffray Nov 24 '16 at 13:39$sourceclass to myclass Adepending on my edit informations – Matthéo Geoffray Nov 24 '16 at 13:53CustomProcessorFactorythat I inject in myClass A. In that class I use the OM to create the source. So in myClass AI callcustomProcessorFactoryas in you example which it is using the OM right ? If that is it I did not see what will change, that will just move my ObjectManager initial issue. Did I misunderstood your reasoning or maybe my example is not that clear ? – Matthéo Geoffray Nov 24 '16 at 14:10$sourceinstantiation to a separate class that just only instantiates it and does nothing else, you are off the hook. You are allowed to use OM. The effect will be the same but your code will be best practice compliant. – Marius Nov 24 '16 at 14:11[$model,$config]just like you do, but you have to give array keys to your array in order to work properly. – Marius Nov 24 '16 at 14:23