在服务类内重定向?

问题描述 投票:3回答:1

我已经创建了自己的服务类,我在其中有一个函数,handleRedirect()应该在选择重定向路径之前执行一些最小的逻辑检查。

class LoginService
{
    private $CartTable;
    private $SessionCustomer;
    private $Customer;

    public function __construct(Container $SessionCustomer, CartTable $CartTable, Customer $Customer)
    {
        $this->SessionCustomer  = $SessionCustomer;
        $this->CartTable        = $CartTable;
        $this->Customer         = $Customer;

        $this->prepareSession();
        $this->setCartOwner();
        $this->handleRedirect();
    }

    public function prepareSession()
    {
        // Store user's first name
        $this->SessionCustomer->offsetSet('first_name', $this->Customer->first_name);
        // Store user id
        $this->SessionCustomer->offsetSet('customer_id', $this->Customer->customer_id);
    }

    public function handleRedirect()
    {
        // If redirected to log in, or if previous page visited before logging in is cart page:
        //      Redirect to shipping_info
        //  Else
        //      Redirect to /
    }

    public function setCartOwner()
    {
        // GET USER ID FROM SESSION
        $customer_id = $this->SessionCustomer->offsetGet('customer_id');
        // GET CART ID FROM SESSION
        $cart_id = $this->SessionCustomer->offsetGet('cart_id');
        // UPDATE
        $this->CartTable->updateCartCustomerId($customer_id, $cart_id);
    }
}

成功登录或注册后,将在控制器中调用此服务。我不确定从这里访问redirect()->toRoute();的最佳方法是什么(或者如果我在这里应该这样做的话)。

此外,如果您对我的代码的结构有其他意见,请随时留下。

service zend-framework2
1个回答
2
投票

在服务中使用插件是一个坏主意,因为它们需要设置控制器。创建服务并注入插件时,它不知道控制器实例,因此会导致错误异常。如果要重定向用户,可以像重定向插件一样编辑响应对象。

请注意,我删除了代码以使示例清晰简单。

class LoginServiceFactory implements FactoryInterface
{
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        return new LoginService($container->get('Application')->getMvcEvent());
    }
}

class LoginService
{
    /**
     * @var \Zend\Mvc\MvcEvent
     */
    private $event;

    /**
     * RedirectService constructor.
     * @param \Zend\Mvc\MvcEvent $event
     */
    public function __construct(\Zend\Mvc\MvcEvent $event)
    {
        $this->event = $event;
    }

    /**
     * @return Response|\Zend\Stdlib\ResponseInterface
     */
    public function handleRedirect()
    {
        // conditions check
        if (true) {
            $url = $this->event->getRouter()->assemble([], ['name' => 'home']);
        } else {
            $url = $this->event->getRouter()->assemble([], ['name' => 'cart/shipping-info']);
        }

        /** @var \Zend\Http\Response $response */
        $response = $this->event->getResponse();
        $response->getHeaders()->addHeaderLine('Location', $url);
        $response->setStatusCode(302);

        return $response;
    }
}

现在,从您的控制器中,您可以执行以下操作:

return $loginService->handleRedirect();

© www.soinside.com 2019 - 2024. All rights reserved.