如何在 Magento 2 的观察者中注入 "customer session" 模型

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

我无法将 \Magento\Customer\Model\Session 模型注入我的观察者。我收到 "Circular dependency" 错误。有什么想法吗?

想法是在所有前端页面上强制登录。我已成功注入 URL 接口以获取当前 URL 和 HTTP class 以将访客用户重定向到登录页面。

现在唯一缺少的部分是客户会话模型。

这是我的代码:

<?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 );
    }
}

错误信息如下:

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}

谢谢!

编辑:

无法将 \Magento\Customer\Model\Session 模型注入“visitor_init”和“的观察者中customer_session_init”事件。

我现在正在使用“controller_action_predispatch”并且可以成功注入客户会话模型

这是我模块的 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>

Sooo .. 原来“customer_session”对象在我的 Observer 中的 $observer 对象中可用。在我的 execute() 方法中,我做了:

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

在其他事件挂钩中,例如“controller_action_predispatch”,customer_session 对象不可用。我找到了另一种查看客户是否使用 HTTP 上下文对象登录的方法:

/**
 * 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;
        }
    }
}