首页 > 解决方案 > TYPO3 处理弃用问题 #90803

问题描述

我以下列方式使用 ObjectManager::get:

$objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
$sqlSel = $objectManager->get('HGA\\Mairlist\\Utilities\\SqlSelect');
$Setup = $sqlSel->getUid("cr", "lastplay", 3);

我读过了

https://docs.typo3.org/c/typo3/cms-core/master/en-us/Changelog/10.4/Deprecation-90803-DeprecationOfObjectManagergetInExtbaseContext.html#changelog-deprecation-90803-objectmanagerget

几次,但我不明白。我得到$objectManager->get('HGA\\Mairlist\\Utilities\\SqlSelect')了一个指向这个函数的指针,但是应该怎么做呢Service $service

如何获得指向我的程序的指针?

标签: typo3typo3-10.x

解决方案


您正在谈论 DI(依赖注入)。objectManager->get()已被标记为已弃用,它将在 TYPO3 12 上删除。这意味着必须根据使用情况将其替换为DIGeneralUtility ::makeInstance

在构造函数中注入依赖项的推荐方法。在您的情况下,它看起来像这样:

use HGA\Mairlist\Utilities\SqlSelect;

class YourClass 
{
    /**
    * @var SqlSelect
    */
    protected $sqlSel;

    public function __construct(SqlSelect $sqlSel)
    {
      $this->sqlSel = $sqlSel;
    }

    public function yourMethod()
    {
      $Setup = $this->sqlSel->getUid("cr", "lastplay", 3);
    }
}

另一种方法是Georg描述的。您可以使用GeneralUtility::makeInstance()

use HGA\Mairlist\Utilities\SqlSelect;

class YourClass 
{
    public function yourMethod()
    {
      $sqlSel = GeneralUtility::makeInstance(SqlSelect::class);
      $Setup = $sqlSel->getUid("cr", "lastplay", 3);
    }
}

在这两种情况下,您必须记住,为了使 DI 工作,必须在 PUBLIC 上设置类,否则您将收到以下错误:

函数 HGA\Mairlist\Utilities\SqlSelect::__construct() 的参数太少,0 在第 3691 行传入 /path/to/your/typo3/installation/typo3/sysext/core/Classes/Utility/GeneralUtility.php预计 1 个

你可以在你的Services.yaml上做到这一点

your_extension/Configuration/Services.yaml

# Configuration/Services.yaml
services:
  _defaults:
    autowire: true
    autoconfigure: true
    public: false

HGA\Mairlist\:
  resource: '../Classes/*'

HGA\Mairlist\Utilities\SqlSelect:
  public: true

毕竟,您需要清除所有缓存,特别是维护模块下的缓存。

希望对您有所帮助。

此致


推荐阅读