3

In Magento 2 we have to create a lot of data for ourselves using helper-modules. In the Vendor/Example/Helper/Data.php I often see either of these two at the top of the file:

  • use Magento\Framework\App\Helper\AbstractHelper;

  • class Data extends \Magento\Framework\App\Helper\AbstractHelper

And sometimes both: use Magento\Framework\App\Helper\AbstractHelper; class Data extends AbstractHelper

And I'm wondering, is there any difference to either use or extend the AbstractHelper? Is there a right or wrong?

A simple answer I found is this:

You can use multiple traits, you can't extend multiple classes.

Does this translate into you either extend to add new stuff to it, and use it to get existing data? And again, is there an upside or downside in using either in Magento?

1
  • The use keyword just allows you to reference that class without supplying the full namespace, thereby improving the readability of code. It's purely aesthetic. Commented Dec 16, 2016 at 13:23

1 Answer 1

3

You are mixing up the use operator.

Using the operator outside of a class definition or inside of a function allows you to import/alias namespaces, which are used for aesthetic purposes only. It also helps to keep the code more readable, because you get rid of unnecessary fully qualified names.

namespace Vendor\Module;

use My\Class;

class Foo
{
    public function Bar()
    {
        use My\Class2;

        $foo = new Class();
        $bar = new Class2();
    }
}

Using the operator inside the class definition allows you to add traits.

namespace Vendor\Module;

class Foo
{
    use My\Trait;

    public function Bar()
    {
        return $this->myTraitFuntion();
    }
}

Regarding your question when to use extend and traits:

Extend when you need to override methods, extend a more generic class or you want to extend core classes.

Use a trait when you have reusable methods like a simple logger method or a format method you want to use in multiple classes.

PS: Magento 2 has only less than 10 traits in its core.

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.