Magento 2.3 example of where proxy is used but not explicitly requested in constructors
-
20-03-2021 - |
题
I'm trying to find an example in M2 repo where a proxy is used but not explicitly requested in a constructor. Can anyone point me in the right direction?
This is in response to phpcs Magento2 ruleset error
Proxies and interceptors MUST never be explicitly requested in constructors.
解决方案 2
Here's what an actual working example looks like
Before
/**
* {@inheritdoc}
*/
public function __construct(
$name,
Data\Proxy $data,
SentryLog\Proxy $sentryLog,
DeploymentConfig\Proxy $deploymentConfig,
array $handlers = [],
array $processors = []
) {
$this->sentryHelper = $data;
$this->sentryLog = $sentryLog;
$this->deploymentConfig = $deploymentConfig;
parent::__construct($name, $handlers, $processors);
}
After
use JustBetter\Sentry\Model\SentryLog;
/**
* {@inheritdoc}
*/
public function __construct(
$name,
Data $data,
SentryLog $sentryLog,
DeploymentConfig $deploymentConfig,
array $handlers = [],
array $processors = []
) {
$this->sentryHelper = $data;
$this->sentryLog = $sentryLog;
$this->deploymentConfig = $deploymentConfig;
parent::__construct($name, $handlers, $processors);
}
etc/di.xml
<type name="JustBetter\Sentry\Plugin\MonologPlugin">
<arguments>
<argument name="name" xsi:type="string"></argument>
<argument name="data" xsi:type="object">JustBetter\Sentry\Helper\Data\Proxy</argument>
<argument name="sentryLog" xsi:type="object">JustBetter\Sentry\Model\SentryLog\Proxy</argument>
<argument name="deploymentConfig" xsi:type="object">Magento\Framework\App\DeploymentConfig\Proxy</argument>
<argument name="handlers" xsi:type="array"></argument>
<argument name="processors" xsi:type="array"></argument>
</arguments>
</type>
其他提示
Proxies are injected via di.xml.
<type name="Your\Class">
<arguments>
<argument name="slowLoading" xsi:type="object">SlowLoading\Class\Proxy</argument>
</arguments>
</type>
Mostly used them in console commands for now. Generally you can use them everywhere you want to delay the instantiation of a class with all its own dependencies until it is directly called upon.