2

I'm writing a wordpress plugin using the https://github.com/DevinVinson/WordPress-Plugin-Boilerplate template and I'm trying to configure PHP-DI (http://php-di.org/) to handle injection of classes across my plugin.

My composer config is this

{
  "name" : "emeraldjava/bhaa_wordpress_plugin",
  "description" : "bhaa_wordpress_plugin",
  "type" : "wordpress-plugin",
  "require": {
    "php-di/php-di": "^6.0"
  },
  "autoload" : {
    "psr-4" : {
      "BHAA\\" : "src"
    }
  }
} 

In my Main.php class I'm creating the PHP-DI Container object and i'm expecting that autowiring should take effect, so I don't need to register a lot of objects in the addDefinitions() method.

use DI\ContainerBuilder;

use function DI\autowire;
use function DI\create;

class Main {

    public function __construct() {
        // This is the current manual initialisation of the Loader class. I want to be able to inject this object reference
        $this->loader = new utils\Loader();
        $this->buildContainer();
    }

    private function buildContainer() {
        $builder = new ContainerBuilder();
        $builder->addDefinitions([
            // I add the object definition to the container here
            'loader' => $this->loader,
        ]);
        $this->container = $builder->build();
    }    
}

I have a new class called LeagueCPT where i'd like to inject the Loader object reference

namespace BHAA\front\cpt;

use BHAA\utils\Loader;

class LeagueCPT {

    private $loader;

    public function __construct(Loader $loader) {
        // i'm expecting that Loader will be injected here but it's null
    }
}

In the original code I would have manually created the LeagueCPT and passed the reference manually, like this

class Main {

    public function __construct() {
        $this->leagueCpt = new front\cpt\LeagueCPT($this->loader);
    }
}

I'm expecting now that I should be able to call the Container to create me a new object for League with the correct constructor injected

class Main {

    public function __construct() {
        $this->leagueCpt = $this->getContainer()->get(LeagueCPT);
    }
}

but in each case, i can't see the LeagueCPT getting initialised by PHP-DI. I'd appreciate any suggestion on how i can correctly configure the DI system in this case.

emeraldjava
  • 10,894
  • 26
  • 97
  • 170

1 Answers1

2

Autowiring works by checking out the type-hints of parameters. In your constructor you have Loader $loader.

You need to put your loader in the PHP-DI config under the BHAA\utils\Loader key, not just loader (PHP-DI will not guess things magically with just loader).

So replace 'loader' => $this->loader, by \BHAA\utils\Loader::class => $this->loader, and you should be good.

Matthieu Napoli
  • 48,448
  • 45
  • 173
  • 261