I want to use Dependency Injection in Pimcore. Luckily this is possible out of the box since Pimcore 4.x.
But I must admit that I can't get it to work. I read those sites: DI, DI, DI
as well as the documentation of php-di since Pimcore is using it.
Now I have a plugin, a simple search, that I want to inject into one of my controller.
The plugins structure looks like this:
plugins
- MyPlugin
- lib
- MyPlugin
- Models
Search.php
- static
- plugin.xml
I want to inject the class inside Search.php
into my controller.
# plugins/MyPlugin/lib/MyPlugin/Models/Search.php
class MyPlugin_Models_Search
The class itself has no namespace, but has one defined in plugin.xml
# plugins/MyPlugin/plugin.xml
<pluginNamespace>MyPlugin</pluginNamespace>
I copied the di.example.php
to website/config/di.php
and it is called, I veryfied that.
My definitions look like this:
# website/config/di.php
<?php
return [
'MyPlugin' => DI\object()->property('myPlugin', DI\get('MyPlugin_Models_Search')),
# 'myPlugin' => \DI\object()->constructor(DI\get('MyPlugin_Models_Search'))
# 'myPlugin' => new MyPlugin_Models_Search() // crashes everything :)
# 'MyPlugin_Models_Search' => new MyPlugin_Models_Search()
# many more ...
];
My controller:
# website/controllers/FooController.php
<?php
use Website\Controller\Action;
class FooController extends Action
{
public $myPlugin;
# this won't work: Declaration of FooController::__construct() must be
# compatible with Zend_Controller_Action_Interface::__construct(
# Zend_Controller_Request_Abstract $request, Zend_Controller_Response_
# Abstract $response, array $invokeArgs = Array)
public function __construct($plugin) {
$this->myPlugin = $plugin;
}
public function FooAction() { var_dump($this->myPlugin); }
}
I even tried to set the definition directly in pimcore/lib/Pimcore.php
in function getDiContainer()
but no success.
Any ideas? Thanks you and have a good day!