how to instantiate PHP SYMFONY ReflectionClass and dependecy injection

I have this class

class foo {
    private Serializer $serializer;

    public function __construct(Serializer $dtoSerializer)
    {
        $this->serializer = $dtoSerializer;
    }
}

my Serializer $dtoSerializer is bind in yaml file for the parameters like this

services:
    dto.serializer:
        class: SymfonyComponentSerializerSerializer
        arguments:
            -
                - '@serializer.normalizer.json_serializable'
                - '@AppSymfonySerializerNormalizerEnumNormalizer'
                - '@SymfonyComponentSerializerNormalizerObjectNormalizer'
            -
                - '@serializer.encoder.json'

And i use this resolve to get instance from className

public function resolve($class)
    {
        $reflector = new ReflectionClass($class);

        if (!$reflector->isInstantiable()) {
            throw new Exception("[$class] is not instantiable");
        }
        
        $constructor = $reflector->getConstructor();
        
        if (is_null($constructor) === true) {
            return new $class;
        }

        $parameters = $constructor->getParameters();
        $dependencies = $this->getDependencies($parameters);

        return $reflector->newInstanceArgs($dependencies);
    }
    
    public function getDependencies($parameters)
    {
        $dependencies = array();

        foreach ($parameters as $parameter) {
            $dependency = $parameter->getClass();

            if (is_null($dependency) === true) {
                $dependencies[] = $this->resolveNonClass($parameter);
            } else {
                $dependencies[] = $this->resolve($dependency->name);
            }
        }

        return $dependencies;
    }

    public function resolveNonClass(ReflectionParameter $parameter)
    {
        if ($parameter->isDefaultValueAvailable()) {
            return $parameter->getDefaultValue();
        }

        throw new Exception("Erm.. Cannot resolve the unkown!?");
    }

how to force my Serializer to get config in yaml file when i resolve Foo Clas ?
or how to invoke __construct of class and let him autowire all the dependency dynamically ?

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *