6

I was wondering how i should load my namespaces.

<?php
namespace MyVendor\MyModule\Cron;

use \MyVendor\MyModule\Model\ResourceModel\Message\Collection;

class Order 
{
    protected $_logger;
    protected $_messages;

    public function __construct(
        \Psr\Log\LoggerInterface $logger,
        Collection $_message
    ) 
    {
        $this->_logger = $logger;
        $this->_messages = $_message;
    }

    public function execute(\Magento\Cron\Model\Schedule $schedule) 
    {
        return $this;
    }
}

In this short example \MyVendor\MyModule\Model\ResourceModel\Message\Collection is loaded using "use" but \Psr\Log\LoggerInterface is loaded in the constructor.

Is there a significant difference? If yes, what is it?

3
  • No, there is no difference. If you are using same class multiple times, in that case it is recommended to use "use".
    – Sandipan S
    Mar 3, 2017 at 12:19
  • @SandipanS what does it have to do with the number of usages? Mar 3, 2017 at 13:10
  • @FabianSchmengler .. i mean if I use the same class twice then it better to include the class using "use"
    – Sandipan S
    Mar 4, 2017 at 13:54

1 Answer 1

6

Only readability. Technically there is no difference.

Note that you can avoid name conflicts or confusions by using one of these alternatives as well:

  • Import parent namespace instead of class:

    use \MyVendor\MyModule\Model\ResourceModel\Message;
    
    Message\Collection $_messages
    
  • Import class with alias:

    use \MyVendor\MyModule\Model\ResourceModel\Message\Collection as Messages;
    
    Messages $_messages
    
1
  • Thank you very much! I marked your response as the answer! Mar 3, 2017 at 14: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.