Magento 2: The direct use of ObjectManager is discouraged [duplicate]
-
10-12-2020 - |
Question
when I am check using object manager it gives me warning that The direct use of ObjectManager is discouraged. Inject necessary dependencies via constructor". How to solve this problem and I also want to know that how to call block file's objectmanager in template file. I am checking customer is login or not using below code.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
if ($customerSession->isLoggedIn()) {
//my custom code goes here;
}
I am already using below way but it doesn't work for me.
private $_objectManager;
public function __construct(
\Magento\Framework\ObjectManagerInterface $objectmanager)
{
$this->_objectManager = $objectmanager;
}
$customerSession = $objectmanager->get('Magento\Customer\Model\Session');
if ($customerSession->isLoggedIn()) {
//my custom code goes here;
}
Solution
Use objectManager by Factory Method to avoid "The direct use of ObjectManager is discouraged." error.
For example To check customer login or not using objectManager
private $_objectManager;
public function __construct(
\Magento\Framework\ObjectManagerInterface $objectmanager
) {
$this->_objectManager = $objectmanager;
}
$customer = $this->_objectManager->get('Magento\Customer\Model\Session');
if ($customer->isLoggedIn()) {
//my custom code goes here;
}
To check customer login or not using \Magento\Customer\Model\Session
class
private $_customerSession;
public function __construct(
...
\Magento\Customer\Model\Session $customerSession,
...
) {
...
$this->_customerSession = $customerSession;
...
}
if ($this->_customerSession->isLoggedIn()) {
//my custom code goes here;
}
OTHER TIPS
in your code
private $_objectManager;
public function __construct(
\Magento\Framework\ObjectManagerInterface $objectmanager)
{
$this->_objectManager = $objectmanager;
}
$customerSession = $this->_objectManager->get('Magento\Customer\Model\Session');
if ($customerSession->isLoggedIn()) {
//my custom code goes here;
}
Use factory method instead
namespace Test\Module\Block;
class Test extends \Magento\Framework\View\Element\Template
{
protected $_session;
public function __construct(
\Magento\Customer\Model\Session $session,
) {
parent::__construct($context);
$this->_session = $session;
}
public function _isLoggedIn()
{
if($this->_session->isLoggedIn()):
return true;
endif;
return false;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange