Based on runtime set variables, I want a given factory to create an instance of a class. However, I find that the only way the auto-generated factories get the concrete class is via xml <preference>
.
namespace Vendor\Module\Api;
interface CustomInterface {}
namespace Vendor\Module\Model;
class First implements CustomInterface {}
namespace Vendor\Module\Model;
class Second implements CustomInterface {}
namespace Vendor\Module\Model;
class Thing {
public function __construct(
\Vendor\Module\Api\CustomInterfaceFactory $customObjectFactory
){
$this->customObjectFactory = $customObjectFactory;
}
public function getCustomObject($thing){
if($thing){
// should return First instance
return $this->customObjectFactory->create();
}else{
// should return Secong instance
return $this->customObjectFactory->create();
}
}
}
The above will fail, trying to instantiate interface CustomInterface.
Am I stuck creating identical interfaces (duplicates in content, but with different names) in order to get multiple (auto-generated) factories, that will return the specific class? I mean, calling a different factory based on the above if($thing){}
I want to keep using the ObjectManager DI chain, since the objects First and Second make use of DI.
Or is there a canonical way to build a CustomFactory class? Something like:
namespace Vendor\Module\Model;
class CustomObjectFactory {
public function __construct(
\Magento\Framework\ObjectManagerInterface $objectManager
){
$this->objectManager = $objectManager;
}
public function create($className, array $data = [])
{
return $this->_objectManager->create($className, $data);
}
}
What would be the Magento2 approach?
Thanks!
PS: I get the feeling this daisy chaining of DI will turn into a Mocking nightmare...