Search code examples
magentosessiondependency-injectionmagento2magento-2.0

How can I inject "customer session" model in an observer in Magento 2


I am having trouble injecting the \Magento\Customer\Model\Session model into my observer. I am getting a "Circular dependency" error. Any ideas?

The idea is to force login on all frontend pages. I have successfully injected the URL interface to get the current URL and the HTTP class to redirect guest users to the login page.

The only missing piece now is the customer session model.

Here is my code:

<?php

/**
 * Namespace
 */
namespace VendorName\CustomerLoginRedirect\Observer;

/**
 * Dependencies
 */
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;

/**
 * Observer Class
 */
class CustomerInit implements ObserverInterface {
    /**
     * Constructor
     */
    protected $_url;
    protected $_http;
    protected $_session;

    public function __construct(
        \Magento\Framework\UrlInterface $url,
        \Magento\Customer\Model\Session $session,
        \Magento\Framework\App\Response\Http $http
    ) {
        $this->_url = $url;
        $this->_session = $session;
        $this->_http = $http;
    }

    /**
     * Manages redirect
     */
    public function execute(Observer $observer) {
        $url = $this->_url->getCurrentUrl();
        $path = parse_url($url, PHP_URL_PATH);

        // Allowed strings to match against URL
        $allow = [
            '/customer'
        ];

        // Ignore customer pages
        foreach ($allow as $s) {
            if (stripos($path, $s) !== false) {
                return;
            }
        }

        // Check if customer logged in
        // if ( $this->_session->isLoggedIn() ) {
        //     die('Is logged in!!');
        //     return;
        // }

        return;

        // Redirect to login
        $this->_http->setRedirect( $this->_url->getBaseUrl().'customer/account/login/', 301 );
    }
}

Here is the error message:

Circular dependency: VendorName\CustomerLoginRedirect\Observer\CustomerInit depends on VendorName\CustomerLoginRedirect\Observer\CustomerInit and vice versa.
#0 /home/user/public_html/vendor/magento/framework/ObjectManager/ObjectManager.php(71): Magento\Framework\ObjectManager\Factory\Dynamic\Developer->create('VendorName\\Custo...')
#1 /home/user/public_html/vendor/magento/framework/Event/ObserverFactory.php(33): Magento\Framework\ObjectManager\ObjectManager->get('VendorName\\Custo...')
#2 /home/user/public_html/vendor/magento/framework/Event/Invoker/InvokerDefault.php(59): Magento\Framework\Event\ObserverFactory->get('VendorName\\Custo...')
#3 /home/user/public_html/vendor/magento/framework/Event/Manager.php(66): Magento\Framework\Event\Invoker\InvokerDefault->dispatch(Array, Object(Magento\Framework\Event\Observer))
#4 /home/user/public_html/var/generation/Magento/Framework/Event/Manager/Proxy.php(95): Magento\Framework\Event\Manager->dispatch('customer_sessio...', Array)
#5 /home/user/public_html/vendor/magento/module-customer/Model/Session.php(177): Magento\Framework\Event\Manager\Proxy->dispatch('customer_sessio...', Array)
#6 [internal function]: Magento\Customer\Model\Session->__construct(Object(Magento\Framework\App\Request\Http), Object(Magento\Framework\Session\SidResolver\Proxy), Object(Magento\Framework\Session\Config), Object(Magento\Framework\Session\SaveHandler), Object(Magento\Framework\Session\Validator), Object(Magento\Customer\Model\Session\Storage), Object(Magento\Framework\Stdlib\Cookie\PhpCookieManager), Object(Magento\Framework\Stdlib\Cookie\CookieMetadataFactory), Object(Magento\Framework\App\State), Object(Magento\Customer\Model\Config\Share\Proxy), Object(Magento\Framework\Url\Helper\Data), Object(Magento\Customer\Model\Url\Proxy), Object(Magento\Customer\Model\ResourceModel\Customer\Proxy), Object(Magento\Customer\Model\CustomerFactory), Object(Magento\Framework\UrlFactory), Object(Magento\Framework\Session\Generic), Object(Magento\Framework\Event\Manager\Proxy), Object(Magento\Framework\App\Http\Context), Object(Magento\Customer\Api\CustomerRepositoryInterface\Proxy), Object(Magento\Customer\Model\GroupManagement), Object(Magento\Framework\App\Response\Http\Interceptor))
#7 /home/user/public_html/vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php(202): ReflectionClass->newInstanceArgs(Array)
#8 /home/user/public_html/vendor/magento/framework/ObjectManager/Factory/Dynamic/Developer.php(89): Magento\Framework\ObjectManager\Factory\AbstractFactory->createObject('Magento\\Custome...', Array)
#9 /home/user/public_html/vendor/magento/framework/ObjectManager/ObjectManager.php(71): Magento\Framework\ObjectManager\Factory\Dynamic\Developer->create('Magento\\Custome...')
#10 /home/user/public_html/vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php(236): Magento\Framework\ObjectManager\ObjectManager->get('Magento\\Custome...')
#11 /home/user/public_html/vendor/magento/framework/ObjectManager/Factory/Dynamic/Developer.php(53): Magento\Framework\ObjectManager\Factory\AbstractFactory->resolveArgument(Array, 'Magento\\Custome...', NULL, 'session', 'VendorName\\Custo...')
#12 /home/user/public_html/vendor/magento/framework/ObjectManager/Factory/Dynamic/Developer.php(82): Magento\Framework\ObjectManager\Factory\Dynamic\Developer->_resolveArguments('VendorName\\Custo...', Array, Array)
#13 /home/user/public_html/vendor/magento/framework/ObjectManager/ObjectManager.php(71): Magento\Framework\ObjectManager\Factory\Dynamic\Developer->create('VendorName\\Custo...')
#14 /home/user/public_html/vendor/magento/framework/Event/ObserverFactory.php(33): Magento\Framework\ObjectManager\ObjectManager->get('VendorName\\Custo...')
#15 /home/user/public_html/vendor/magento/framework/Event/Invoker/InvokerDefault.php(59): Magento\Framework\Event\ObserverFactory->get('VendorName\\Custo...')
#16 /home/user/public_html/vendor/magento/framework/Event/Manager.php(66): Magento\Framework\Event\Invoker\InvokerDefault->dispatch(Array, Object(Magento\Framework\Event\Observer))
#17 /home/user/public_html/var/generation/Magento/Framework/Event/Manager/Proxy.php(95): Magento\Framework\Event\Manager->dispatch('customer_sessio...', Array)
#18 /home/user/public_html/vendor/magento/module-customer/Model/Session.php(177): Magento\Framework\Event\Manager\Proxy->dispatch('customer_sessio...', Array)
#19 [internal function]: Magento\Customer\Model\Session->__construct(Object(Magento\Framework\App\Request\Http), Object(Magento\Framework\Session\SidResolver\Proxy), Object(Magento\Framework\Session\Config), Object(Magento\Framework\Session\SaveHandler), Object(Magento\Framework\Session\Validator), Object(Magento\Customer\Model\Session\Storage), Object(Magento\Framework\Stdlib\Cookie\PhpCookieManager), Object(Magento\Framework\Stdlib\Cookie\CookieMetadataFactory), Object(Magento\Framework\App\State), Object(Magento\Customer\Model\Config\Share\Proxy), Object(Magento\Framework\Url\Helper\Data), Object(Magento\Customer\Model\Url\Proxy), Object(Magento\Customer\Model\ResourceModel\Customer\Proxy), Object(Magento\Customer\Model\CustomerFactory), Object(Magento\Framework\UrlFactory), Object(Magento\Framework\Session\Generic), Object(Magento\Framework\Event\Manager\Proxy), Object(Magento\Framework\App\Http\Context), Object(Magento\Customer\Api\CustomerRepositoryInterface\Proxy), Object(Magento\Customer\Model\GroupManagement), Object(Magento\Framework\App\Response\Http\Interceptor))
#20 /home/user/public_html/vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php(202): ReflectionClass->newInstanceArgs(Array)
#21 /home/user/public_html/vendor/magento/framework/ObjectManager/Factory/Dynamic/Developer.php(89): Magento\Framework\ObjectManager\Factory\AbstractFactory->createObject('Magento\\Custome...', Array)
#22 /home/user/public_html/vendor/magento/framework/ObjectManager/ObjectManager.php(71): Magento\Framework\ObjectManager\Factory\Dynamic\Developer->create('Magento\\Custome...')
#23 /home/user/public_html/vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php(236): Magento\Framework\ObjectManager\ObjectManager->get('Magento\\Custome...')
#24 /home/user/public_html/vendor/magento/framework/ObjectManager/Factory/Dynamic/Developer.php(53): Magento\Framework\ObjectManager\Factory\AbstractFactory->resolveArgument(Array, 'Magento\\Custome...', NULL, 'customerSession', 'Magento\\Weee\\Mo...')
#25 /home/user/public_html/vendor/magento/framework/ObjectManager/Factory/Dynamic/Developer.php(82): Magento\Framework\ObjectManager\Factory\Dynamic\Developer->_resolveArguments('Magento\\Weee\\Mo...', Array, Array)
#26 /home/user/public_html/vendor/magento/framework/ObjectManager/ObjectManager.php(71): Magento\Framework\ObjectManager\Factory\Dynamic\Developer->create('Magento\\Weee\\Mo...')
#27 /home/user/public_html/vendor/magento/framework/Interception/PluginList/PluginList.php(234): Magento\Framework\ObjectManager\ObjectManager->get('Magento\\Weee\\Mo...')
#28 /home/user/public_html/vendor/magento/framework/Interception/Interceptor.php(139): Magento\Framework\Interception\PluginList\PluginList->getPlugin('Magento\\Cms\\Con...', 'weee-app-action...')
#29 /home/user/public_html/var/generation/Magento/Cms/Controller/Index/Index/Interceptor.php(39): Magento\Cms\Controller\Index\Index\Interceptor->___callPlugins('dispatch', Array, Array)
#30 /home/user/public_html/vendor/magento/framework/App/FrontController.php(55): Magento\Cms\Controller\Index\Index\Interceptor->dispatch(Object(Magento\Framework\App\Request\Http))
#31 [internal function]: Magento\Framework\App\FrontController->dispatch(Object(Magento\Framework\App\Request\Http))
#32 /home/user/public_html/vendor/magento/framework/Interception/Interceptor.php(74): call_user_func_array(Array, Array)
#33 /home/user/public_html/vendor/magento/framework/Interception/Chain/Chain.php(70): Magento\Framework\App\FrontController\Interceptor->___callParent('dispatch', Array)
#34 /home/user/public_html/vendor/magento/framework/Interception/Chain/Chain.php(63): Magento\Framework\Interception\Chain\Chain->invokeNext('Magento\\Framewo...', 'dispatch', Object(Magento\Framework\App\FrontController\Interceptor), Array, 'requestPreproce...')
#35 /home/user/public_html/vendor/magento/module-store/App/FrontController/Plugin/RequestPreprocessor.php(89): Magento\Framework\Interception\Chain\Chain->Magento\Framework\Interception\Chain\{closure}(Object(Magento\Framework\App\Request\Http))
#36 [internal function]: Magento\Store\App\FrontController\Plugin\RequestPreprocessor->aroundDispatch(Object(Magento\Framework\App\FrontController\Interceptor), Object(Closure), Object(Magento\Framework\App\Request\Http))
#37 /home/user/public_html/vendor/magento/framework/Interception/Chain/Chain.php(68): call_user_func_array(Array, Array)
#38 /home/user/public_html/vendor/magento/framework/Interception/Chain/Chain.php(63): Magento\Framework\Interception\Chain\Chain->invokeNext('Magento\\Framewo...', 'dispatch', Object(Magento\Framework\App\FrontController\Interceptor), Array, 'install')
#39 /home/user/public_html/vendor/magento/framework/Module/Plugin/DbStatusValidator.php(69): Magento\Framework\Interception\Chain\Chain->Magento\Framework\Interception\Chain\{closure}(Object(Magento\Framework\App\Request\Http))
#40 [internal function]: Magento\Framework\Module\Plugin\DbStatusValidator->aroundDispatch(Object(Magento\Framework\App\FrontController\Interceptor), Object(Closure), Object(Magento\Framework\App\Request\Http))
#41 /home/user/public_html/vendor/magento/framework/Interception/Chain/Chain.php(68): call_user_func_array(Array, Array)
#42 /home/user/public_html/vendor/magento/framework/Interception/Chain/Chain.php(63): Magento\Framework\Interception\Chain\Chain->invokeNext('Magento\\Framewo...', 'dispatch', Object(Magento\Framework\App\FrontController\Interceptor), Array, 'front-controlle...')
#43 /home/user/public_html/vendor/magento/module-page-cache/Model/App/FrontController/BuiltinPlugin.php(68): Magento\Framework\Interception\Chain\Chain->Magento\Framework\Interception\Chain\{closure}(Object(Magento\Framework\App\Request\Http))
#44 [internal function]: Magento\PageCache\Model\App\FrontController\BuiltinPlugin->aroundDispatch(Object(Magento\Framework\App\FrontController\Interceptor), Object(Closure), Object(Magento\Framework\App\Request\Http))
#45 /home/user/public_html/vendor/magento/framework/Interception/Chain/Chain.php(68): call_user_func_array(Array, Array)
#46 /home/user/public_html/vendor/magento/framework/Interception/Interceptor.php(136): Magento\Framework\Interception\Chain\Chain->invokeNext('Magento\\Framewo...', 'dispatch', Object(Magento\Framework\App\FrontController\Interceptor), Array, 'front-controlle...')
#47 /home/user/public_html/vendor/magento/module-page-cache/Model/App/FrontController/VarnishPlugin.php(55): Magento\Framework\App\FrontController\Interceptor->Magento\Framework\Interception\{closure}(Object(Magento\Framework\App\Request\Http))
#48 [internal function]: Magento\PageCache\Model\App\FrontController\VarnishPlugin->aroundDispatch(Object(Magento\Framework\App\FrontController\Interceptor), Object(Closure), Object(Magento\Framework\App\Request\Http))
#49 /home/user/public_html/vendor/magento/framework/Interception/Interceptor.php(141): call_user_func_array(Array, Array)
#50 /home/user/public_html/var/generation/Magento/Framework/App/FrontController/Interceptor.php(26): Magento\Framework\App\FrontController\Interceptor->___callPlugins('dispatch', Array, Array)
#51 /home/user/public_html/vendor/magento/framework/App/Http.php(115): Magento\Framework\App\FrontController\Interceptor->dispatch(Object(Magento\Framework\App\Request\Http))
#52 /home/user/public_html/vendor/magento/framework/App/Bootstrap.php(258): Magento\Framework\App\Http->launch()
#53 /home/user/public_html/index.php(39): Magento\Framework\App\Bootstrap->run(Object(Magento\Framework\App\Http))
#54 {main}

Thank you!

EDIT:

The \Magento\Customer\Model\Session model could not be injected into the observers for the "visitor_init" and "customer_session_init" events.

I am now using "controller_action_predispatch" and can successfully inject the Customer Session Model

Here is my module's etc/frontend/events.xml:

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="controller_action_predispatch">
        <observer 
            name="vendorname_controller_action_predispatch"
            instance="VendorName\ForceLogin\Observer\ControllerPredispatch" />
    </event>
</config>

Solution

  • Sooo .. Turns out the "customer_session" object was available inside the $observer object in my Observer. In my execute() method, I did:

    public function execute(Observer $observer) {
        $session = $observer->getCustomerSession();
        if ($session->isLoggedIn()) {
            return;
        }
    }
    

    In other event hooks such as "controller_action_predispatch", the customer_session object is not available. I found another way to see if a customer is logged in using the HTTP Context object:

    /**
     * Observer Dependencies
     */
    use Magento\Framework\Event\ObserverInterface;
    use Magento\Framework\Event\Observer;
    
    class ControllerPredispatch implements ObserverInterface {
        protected $_context;
    
        public function __construct(
            \Magento\Framework\App\Http\Context $context
        ) {
            $this->_context = $context;
        }
    
        public function execute(Observer $observer) {
            $loggedIn = $this->_context->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
            if ( $loggedIn ) {
                return;
            }
        }
    }