0

I have an easy one (I think).

I have a Silex application...I created a service services.yml file, with my services with their arguments. Of coruse, arguments can be instance of another classes:

services:
   Service:
      class: App\Services\xxxxxService
      arguments:
         - App\Lib\Parser\JsonParser
         - xxxxxx

So, in my init application, I have this piece of code:

$services = $this['config']['services'];

    foreach ($services as $name => $service) {
        $className = $service['class'];

        $args = array_map(function ($arg) {
            if(class_exists($arg)){
                return new $arg;
            } else {
                return $arg;
            }
        }, $service['arguments']);
        $args = implode(',', $args);

        $this[$name] = new $className($this, $args);
    }

This code gives me the error:

Catchable fatal error: Object of class App\Lib\Parser\JsonParser could not be converted to string in /app/src/Application.php on line 252

My goal is to have $this[$name] = new $className($this, $args[0], $args[1] ....) , but I cant use implode function.

Any ideas???

Thank you in advance!!

M.

Mauro
  • 189
  • 2
  • 14

1 Answers1

1

I suggest to use ReflectionClass to instantiate your $className

After you collect all your $args do not use implode method as it can not pass correctly the args to class constructor.

So you have $args as array

array_unshift($args, $this); # Prepend $this in args
$refl = new ReflectionClass($className);
$this[$name] = $refl->newInstanceArgs($args); #Instatiate $className with appropriate args.
Whiteulver
  • 828
  • 7
  • 12
  • Yesss!!! ... the Reflection does the trick! +1 fo you! Do you think Reflection is too expensive in terms of memory usage? Viewing my code, do you think I am in right on do this? .... I have an Application wrapper of Silex\Application, and before run this, I start all the controllers, the parameters and services into $app, that is an instance of Pimple. So in my application now I have $app['myService'] and I can re-use everywhere. – Mauro Aug 08 '16 at 18:25
  • You are trying to build a DependencyInjection tool. Althought there are plenty of them, it is not bad to build your own since you can learn a lot things in the proccess. For preformance, it is better to benchmark your application and then profiling it, if you think it is slow. In profiling you can see where bottleneck is. ReflectionClass is also used from Symfony DI, and i think that is the only wawy in php to create a class instance from args. – Whiteulver Aug 09 '16 at 09:43