在服务 class 内重定向?

Redirect inside a service class?

我已经创建了我自己的服务 class 并且我在其中有一个函数,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(); 的最佳方式是什么(或者我是否应该在这里访问)。

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

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

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

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();