I need to use a service by value in an "Utils" Class method called from a controller which implements AbstractControllerInterface.
I have an entity in my project which have some mappings. Some of them have a Utils Class. Some of them implement myInterface.
I have a loop to check every one of those mapping fields, get each correct utils class name, check for its existence and the implementation of myInterface.
In that case I want to instantiate that class (or use them as a service) and call my method.
Every Util class can have different constructor parameters and I thought Autowiring could help.
I can't pass the container and use container get method because the AbstractControllerInterface implementation and can't just make "new $myClassName" because I don't know how every construct definition in each Utils class can be.
my service definition:
App\Utils\MyUtilsClass:
class: App\Utils\MyUtils
public: true
arguments:
- '@doctrine.orm.entity_manager'
- '@App\Helper\MyHelper'
part of my code:
# src\Utils\MyUtilsClass.php
namespace App\Utils
use Doctrine\ORM\EntityManagerInterface;
class MyUtilsClass{
protected $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
# $name = 'App\\Utils\\MyOtherUtilsClass'
public function myMethod($name)
{
$containerBuilder = new ContainerBuilder();
$fileLocator = new FileLocator(__DIR__ . '/../../config');
$loader = new YamlFileLoader($containerBuilder, $fileLocator);
$loader->load('services.yaml');
$containerBuilder->compile();
$utils = $containerBuilder->get($name);
This throws me "service or alias has been removed or inlined when the container was compiled. You should either make it public, or stop using the container directly and use dependency injection instead."
Edit: Trying to make it public throws a non-existent service exception witdDoctrine\ORM\EntityManagerInterface in my container
public function myMethod($name)
{
....
$containerBuilder->getDefinition($claseUtils)->setPublic(true);
$utils = $containerBuilder->get($name);
Every help is appreciated and sorry about my bad English.
Thank you.