How can I set an event observer for customer logout action in magento2?
-
you can see list of all events from this link cyrillschumacher.com/magento2-list-of-all-dispatched-events– RushviJun 29, 2016 at 5:17
2 Answers
you can observe one of the events controller_action_predispatch_customer_account_logout
or controller_action_postdispatch_customer_account_logout
depending on when you want to observe things. before loging out or after.
or you can observe the customer_logout
event for the exact logout moment.
To write an observer you need to create in your module the file etc/frontend/events.xml
with this content:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="{event_name_here}"> <!-- use one of the events above -->
<observer name="[namespace]_[module]" instance="[Namespace]\[Module]\Observer\Logout" />
</event>
</config>
then create the file [Namespace]/[Module]/Observer/Logout.php
<?php
namespace [Namespace]\[Module]\Observer;
class Logout implements \Magento\Framework\Event\ObserverInterface
{
public function execute(\Magento\Framework\Event\Observer $observer)
{
//your code here
}
}
The event name is customer_logout
In your custom module create app/code/{Company}/{Module}/etc/frontend/events.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="customer_logout">
<observer name="{company_module}_customer_logout" instance="{Company}\{Module}\Observer\Frontend\CustomerLogOutObserver" />
</event>
</config>
Then create your observer in {Company}{Module}\Observer\Frontend\CustomerLogOutObserver.php
namespace {Company}\{Module}\Observer\Frontend;
use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;
class CustomerLogOutObserver implements ObserverInterface
{
public function execute(EventObserver $observer)
{
//do stuff here
}
}
Take a look at app/code/Magento/Customer/Controller/Account/Logout.php
/**
* Customer logout action
*
* @return \Magento\Framework\Controller\Result\Redirect
*/
public function execute()
{
$lastCustomerId = $this->session->getId();
$this->session->logout()->setBeforeAuthUrl($this->_redirect->getRefererUrl())
->setLastCustomerId($lastCustomerId);
....
Then app/code/Magento/Customer/Model/Session.php
/**
* Logout customer
*
* @api
* @return $this
*/
public function logout()
{
if ($this->isLoggedIn()) {
$this->_eventManager->dispatch('customer_logout', ['customer' => $this->getCustomer()]);
$this->_logout();
....