4

I've created a setup script to load from a source model

$eavSetup->addAttribute(
    \Magento\Catalog\Model\Category::ENTITY,
    'location_reference',
    [
        'type' => 'varchar',
        'label' => 'Location Reference',
        'input' => 'select',
        'sort_order' => 500,
        'source' => 'Xigen\Data\Model\Category\Attribute\Source\LocationReference',
        'global' => 1,
        'visible' => true,
        'required' => false,
        'user_defined' => false,
        'default' => null,
        'group' => 'General Information',
        'backend' => '',
    ]
);

Works great. However using the official https://github.com/magento/magento-coding-standard ruleset it showed the following warning.

Use ::class notation instead

And sure enough checking a file in vendor at random

Magento\Catalog\Setup\UpgradeData

$categorySetup->addAttribute(
    \Magento\Catalog\Model\Product::ENTITY,
    'custom_layout',
    [
        'type' => 'varchar',
        'label' => 'New Layout',
        'input' => 'select',
        'source' => \Magento\Catalog\Model\Product\Attribute\Source\Layout::class,
        'required' => false,
        'sort_order' => 50,
        'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE,
        'group' => 'Schedule Design Update',
        'is_used_in_grid' => true,
        'is_visible_in_grid' => false,
        'is_filterable_in_grid' => false
    ]
);

Can someone explain more in detail why this syntax is used? Why it is recommended?

1 Answer 1

6
  1. Strings can contain typos.
  2. You can not use the "jump to class" feature on strings from your IDE.
  3. Refactoring in an IDE will find ::class notations and not strings.
6
  • 1
    @tvanriel I greatly apprecheate your edit! valid point! Commented Jun 6, 2019 at 8:39
  • hmm .. i still don't know what to do with this when we check by magento standard code.
    – fudu
    Commented Jul 16, 2021 at 8:41
  • @fudu what is your actual problem ? Commented Oct 3, 2021 at 22:10
  • @MuhammadOmerAslam now i know what to do, but before, when i read this answer, i don't understand what he saying and what to do to resolve the problem.
    – fudu
    Commented Oct 5, 2021 at 7:21
  • @fudu you need to change the 'source' => 'Xigen\Data\Model\Category\Attribute\Source\LocationReference', to 'source' => Xigen\Data\Model\Category\Attribute\Source\LocationReference::class, hope that clears the confusion Commented Oct 5, 2021 at 9:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.