从 Magento 2 中的配置路径获取 system.xml 中的后端模型

Getting backend model in system.xml from config path in Magento 2

我正在尝试从 system.xml 获取后端模型 class 名称 现在我正在使用这段代码。

magento/app/code/Company/Sso/etc/adminhtml/system.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
<system>
    <section id="admin">
        <group id="sso_saml" translate="label" sortOrder="100" showInDefault="1" showInWebsite="0" showInStore="0" >
            <label>Single Sign on(SAML)</label>
            <field id="is_enabled" translate="label comment" type="select" sortOrder="0" showInDefault="1" showInWebsite="0" showInStore="0">
                <label>Is Enabled SAML</label>
                <comment>Enable Single Sign On</comment>
                <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
            </field>
        </group>
    </section>
</system>

Magento 代码

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$structure = $objectManager->create('Magento\Config\Model\Config\StructureFactory');
$field = $objectManager->create('Magento\Config\Model\Config\Structure')->getElementByConfigPath('admin/sso_saml/is_enabled');
print json_encode($field->getData());

输出:

{"id":"is_enabled","path":"admin/sso_saml","_elementType":"field"}

但是我需要source_model,有人可以帮忙吗?

您需要进入 adminhtml 区域才能加载其余数据: 例如

<?php
require __DIR__ . '/app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$appState = $objectManager->get('Magento\Framework\App\State');
$appState->setAreaCode('adminhtml');
$field = $objectManager->create('Magento\Config\Model\Config\Structure')->getElementByConfigPath('customer/create_account/auto_group_assign');
echo $field->getData()['source_model'];
> Magento\Config\Model\Config\Source\Yesno

如有必要,您可以使用 \Magento\Framework\App\State::emulateAreaCode 从非管理员上下文中获取数据。

这是实施 Matt 的解决方案后的完整解决方案。

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$appState = $objectManager->get('Magento\Framework\App\State');
$field = $appState->emulateAreaCode('adminhtml', function($path){
    $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $appState = $objectManager->get('Magento\Framework\App\State');
    $appState->setAreaCode('adminhtml');
    $field = $objectManager->create('Magento\Config\Model\Config\Structure')
        ->getElementByConfigPath($path->getPath());
    return $field;
}, [$path]);

$value = $path->getData()['backend_model'];