Injecting Model into core block module
Question
I want to inject Model into core block module. That it's a simple thing to do in the wrong way (Editing core block). But i want to know how to do it in the right way. Because i want to retrieve User data in the main page.
So, how can i do it, without editing core files?
Im customizing my templates and i want to show users name into the main page, Magento_CatalogWidget/templates/product/widget/content/grid.phtml.
To do that i need to inyect \Magento\Customer\Model\Session
, the answer is where?
For now i have into grid.phtml the follwing code :
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$name = $objectManager->create('\Magento\Customer\Model\Session')
->getCustomer()->getName();
Thanks!
Solution
You can inject customer model file into your block using __consturct()
function.
public function __construct(
\Magento\Customer\Model\Session $customerSession
) {
$this->customerSession = $customerSession;
}
public function myCustom(){
if ($this->customerSession->isLoggedIn()) {
echo $this->customerSession->getCustomer()->getName();
}
}
OTHER TIPS
In Magento 1 you'd get someone's session using:
Mage::getSingleton('core/session')
From there if you want to set a variable you can use:
$session = Mage::getSingleton('core/session')
$session->setVariableName('yourvalue')
And to retrieve your variable
$session->getVariableName();
core/session is not present in Magento2. There are these ones:
\Magento\Backend\Model\Session
\Magento\Catalog\Model\Session
\Magento\Checkout\Model\Session
\Magento\Customer\Model\Session
\Magento\Newsletter\Model\Session
You need to inject an instance of the session you need in your block. Let's take for example \Magento\Catalog\Model\Session.
protected $catalogSession;
public function __construct(
....
\Magento\Catalog\Model\Session $catalogSession,
....
){
....
$this->catalogSession = $catalogSession;
....
}
Then you can use the catalog session inside the class like this:
$this->catalogSession->setMyValue('test_value');
$this->catalogSession->getMyValue();
Hope it helps