2017-12-28 61 views
2

내 서비스 클래스를 만들었고 리디렉션 할 경로를 선택하기 전에 최소한의 논리 검사를 수행해야하는 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();에 액세스하는 가장 좋은 방법이 무엇인지 잘 모르겠습니다. (또는 여기에서해야합니다.)

또한 코드 작성 방법에 대한 다른 의견이 있으면 언제든지 남겨 두십시오.

답변

0

서비스 내에서 플러그인을 사용하는 것은 컨트롤러를 설정해야하기 때문에 바람직하지 않습니다. 서비스가 생성되고 플러그인을 삽입 할 때 컨트롤러 인스턴스를 모르기 때문에 오류 예외가 발생합니다. 사용자를 리디렉션하려면 리디렉션 플러그인처럼 응답 객체를 편집하면됩니다.

예를 명확하고 단순하게 유지하기 위해 코드를 삭제했습니다. 컨트롤러 내에서

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

+0

명확하고 참으로 간단, 감사합니다! – herondale