Magento 2:使用语句还是直接类路径?


14

我可能遗漏了一点,但我只是想知道为什么有时对于特定的类有一个“使用”语句,而有时却没有。

示例:app\code\Magento\Email\Model\Template.php,我们位于文件顶部:

namespace Magento\Email\Model;

use Magento\Store\Model\ScopeInterface;
use Magento\Store\Model\StoreManagerInterface;

然后,在该__construct方法中,我们具有以下参数:

public function __construct(
    \Magento\Framework\Model\Context $context,
    \Magento\Framework\View\DesignInterface $design,
    \Magento\Framework\Registry $registry,
    \Magento\Store\Model\App\Emulation $appEmulation,
    StoreManagerInterface $storeManager,
    \Magento\Framework\View\Asset\Repository $assetRepo,
    \Magento\Framework\Filesystem $filesystem,
    \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
    \Magento\Email\Model\Template\Config $emailConfig,
    \Magento\Email\Model\TemplateFactory $templateFactory,
    \Magento\Framework\Filter\FilterManager $filterManager,
    \Magento\Framework\UrlInterface $urlModel,
    \Magento\Email\Model\Template\FilterFactory $filterFactory,
    array $data = []
)

因此,我们可以清楚地看到,正如我们use Magento\Store\Model\StoreManagerInterface;在类顶部调用的那样,我们能够StoreManagerInterface $storeManager在构造函数参数中进行操作。

我的问题是:

  • 为什么我们只为一个班级这样做?
  • 为什么我们不能use为构造函数的每个类添加一条语句,以便不必键入完整的类路径?
  • 或反过来,为什么我们不删除该use语句并键入StoreManagerInterfaceclass 的完整路径?

Answers:


15

除了存在名称冲突(例如不同的“ Context”类)外,没有技术上的原因要优先选择另一个。但这可以用别名来解决,这就是我通常要做的:

use Magento\Framework\Model\Context as ModelContext;

假设在核心中,许多方法(尤其是构造函数)最初是由诸如转换工具之类的工具生成的,后来又没有更改为使用“ use”导入。

因此,我建议您在自己的代码中始终导入带有“ use”的类,以使实际代码不那么冗长且更具可读性。


因此,仅是澄清一下,核心团队use为我指出的特定课程添加的内容没有意义吗?
拉斐尔(Raphael)在Digital Pianism上

1
否。对我来说,它似乎是稍后使用IDE的人添加的,该IDE在使用自动完成功能时会自动添加use语句。
Fabian Schmengler '16

2

用法取决于具体情况。我的方法是:

在文件中仅提及一次类-FQN

留下全限定名。这可以提高可读性,因为您无需再次查看“ 使用”部分。

类名多次使用- 导入

将其放在使用部分中。这使代码在提到类的地方更短。

该类曾经使用过,但是我需要一个简短的符号-import

用一个例子更好地解释。

FQN

$collection->getSelect()
           ->joinInner(['campaign_products' => $subSelect],
               'campaign_products.product_id = e.entity_id',
               [self::FIELD_SORT_ORDER => "IFNULL(IF(0 = " . \Custome\Module\Api\Data\ProductListInterface::SORT_ORDER . ", NULL, " . \Custome\Module\Api\Data\ProductListInterface::SORT_ORDER . "), {$defaultSortValue})"]
           );

进口

$collection->getSelect()
           ->joinInner(['campaign_products' => $subSelect],
               'campaign_products.product_id = e.entity_id',
               [self::FIELD_SORT_ORDER => "IFNULL(IF(0 = " . ProductListInterface::SORT_ORDER . ", NULL, " . ProductListInterface::SORT_ORDER . "), {$defaultSortValue})"]
           );

我认为第二个示例更易于阅读。(但是说实话,我更喜欢在这里使用变量而不是常量,以使其更具可读性。)

Magento 2 API接口

有关M2自动暴露的API端点的通知。在用于REST / SOAP方法的接口中,您应始终使用FQN。

Magento框架将解析注释,以确定如何将数据与JSON或XML相互转换。

不应用类导入(即,类之上的use语句)!

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.