TYPO3 12中实现svconnector及CSV读取:代码放置位置咨询
在TYPO3 12中正确放置SV Connector CSV实例代码的方法
核心逻辑
TYPO3 12对依赖注入的要求更严格,不能再像TYPO3 11那样在控制器里硬编码获取服务实例,推荐通过依赖注入注入Connector服务,这也是TYPO3 12的标准实践。
步骤1:重构控制器代码(推荐方式:构造函数注入)
把之前的控制器代码改成通过构造函数注入ConnectorCsv服务,示例如下:
<?php namespace YourVendor\YourExtension\Controller; use Cobweb\SvconnectorCsv\Service\ConnectorCsv; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Mvc\Controller\ActionController; class PublicationsController extends ActionController { protected ConnectorCsv $csvConnector; // 通过构造函数注入CSV连接器服务 public function __construct(ConnectorCsv $csvConnector) { $this->csvConnector = $csvConnector; } public function listAction() { // 配置CSV读取参数 $csvPath = GeneralUtility::getFileAbsFileName('EXT:your_extension/Resources/Private/Data/publications.csv'); $configuration = [ 'filename' => $csvPath, 'delimiter' => ',', 'enclosure' => '"', 'skipFirstRow' => true // 若CSV首行是表头,开启此参数跳过 ]; // 获取并转换CSV数据 $rawData = $this->csvConnector->fetch($configuration); $publications = $this->csvConnector->convertToArray($rawData); // 将数据传递给Fluid模板 $this->view->assign('publications', $publications); } }
步骤2:确认Services.yaml配置正确
TYPO3 12会自动识别构造函数注入,无需额外配置服务,但要确保你的扩展基础服务配置正确:
services: _defaults: autowire: true autoconfigure: true public: false YourVendor\YourExtension\: resource: '../Classes/*' # 若你自定义的Publications抽象类有具体实现类,需注册(抽象类无需注册) # YourVendor\YourExtension\Service\YourPublicationsImplementation: # parent: Cobweb\Svconnector\Service\ConnectorBase # autowire: true
替代方案:通过服务容器获取(不推荐,仅兼容旧代码)
如果暂时不想重构为依赖注入,也可以通过对象管理器获取服务,但这不符合TYPO3 12的最佳实践:
<?php namespace YourVendor\YourExtension\Controller; use Cobweb\SvconnectorCsv\Service\ConnectorCsv; use TYPO3\CMS\Extbase\Object\ObjectManagerInterface; use TYPO3\CMS\Extbase\Mvc\Controller\ActionController; class PublicationsController extends ActionController { protected ObjectManagerInterface $objectManager; public function __construct(ObjectManagerInterface $objectManager) { $this->objectManager = $objectManager; } public function listAction() { $csvConnector = $this->objectManager->get(ConnectorCsv::class); // 后续数据读取逻辑同步骤1 } }
常见问题排查
- 确认
svconnector_csv扩展已安装并激活 - 用
GeneralUtility::getFileAbsFileName()转换CSV路径,避免相对路径导致的文件找不到问题 - 查看TYPO3日志(
var/log/typo3_*.log),若出现服务注入失败,检查类命名空间和类名是否完全匹配
内容的提问来源于stack exchange,提问作者Urs Bo
相关产品推荐
相关产品推荐

