2015-02-06 95 views
0

我正在構建一個Symfony 2.6 web應用程序和一個作曲家庫。作曲家庫對Symfony一無所知,需要使用其他框架(或根本沒有框架)進行操作。從圖書館重定向

在某些時候,庫需要重定向用戶。當然,在一個簡單的庫中調用PHP的header('Location: x')是很自然的。當使用直接PHP和沒有框架測試庫時,此工作正常。但是在Symfony應用程序中,調用庫的控制器仍然需要創建一個Response對象並將其返回。實際上,創建一個空的Response最終會清除重定向。我假設Symfony類創建了一組全新的標題,覆蓋了庫中設置的Location

因此,不要讓我的庫依賴於Symfony,它如何重定向用戶?

回答

3

使用您的庫通過依賴注入定義和使用的接口。

interface Redirector { 
    public function redirect($location, $code); 
} 

在庫中,然後你可以把它作爲參數傳遞給類的構造函數,例如:

class FooBar { 
    private $redirector; 

    public function __construct(Redirector $red) { 
     $this->redirector = $red; 
    } 

    // ... 
} 

該接口可以使用的symfony的機制來執行實際的重定向的實現,和你庫不依賴於任何實現。

一個可能的實現可能是:

class SimpleRedirector implements Redirector { 
    public function redirect($location, $code) { 
      header('Location: ' . $location, true, $code); 
      die(); 
    } 
} 
+0

這麼簡單和聰明。我會嘗試一下,看看它的感覺。 – 2015-02-06 15:48:28

+0

然後看看PSR7 – 2015-02-06 18:08:14

1

與SirDarius完全同意。 這是一個簡單的Design By Contract(DbC)模式。 您的組件正在聲明任何應用程序可以以自己的方式實現的接口。

我想過如何實現它symfony。簡單的舊PHP重定向方式非常簡單。但是一個乾淨的Symfony實現更加困難,因爲控制器操作必須返回一個響應對象,並且不能因爲內核必須終止而死掉。在這種情況下,重定向器是有狀態的請求範圍服務,保存重定向數據並提供getResponse方法。

<?php 

class RedirectionService implements Redirector { 
    private $location; 
    private $code; 

    public function redirect($location, $code) { 
     $this->location = $location; 
     $this->code = $code; 
    } 

    public function getResponse() { 
     $response = new RedirectResponse($this->location, $this->code); 
     return $response; 
    } 
} 

// ... 

public function someAction() { 
    // defined in services.yml and gets our service injected 
    $libraryService = $this->get('library_service'); 
    $libraryService->work(); 

    $redirectionService = $this->get('redirection_service'); 
    $response = $redirectionService->getResponse(); 
    return $response; 
}