[英]Instantiate which PHP class based on dev or production environment
我已經將SimpleSAMLphp與我的應用程序集成在一起 ,但是它僅在生產環境中可用,因為在其他地方沒有與IdP服務器的連接。 如何在需要認證的事物上繼續在開發環境中工作?
我編寫了一個包裝器類,該類將必需的方法公開給SimpleSAML_Auth_Simple
類。 相關代碼如下:
<?php
// (assume autoloading)
$saml = new SAMLWrapper('name-of-sp');
$saml->requireAuthentication('https://[::1]/app/saml-controller.php?callback=1');
$userAttributes = $saml->getAttributes();
// rest of application code below...
class SAMLWrapper extends IAuthentication
{
private $as;
public function __construct($sp) {
require_once('/var/simplesamlphp/lib/_autoload.php');
// THIS PATH DOES NOT EXIST ON DEV
$this->as = new \SimpleSAML_Auth_Simple($sp);
}
public function requireAuthentication($callback) {
$this->as->requireAuth(array('ReturnTo' => $callback));
}
public function getAttributes() {
return $this->as->getAttributes();
}
}
我已經考慮過編寫一個虛擬包裝器,如下所示:
class DummySAML extends IAuthentication
{
private $attrs;
public function __construct(array $attrs) {
$this->attrs = $attrs;
}
public function requireAuthentication() {
return;
}
public function getAttributes() {
return $this->attrs;
}
}
但是,這意味着我必須在所有需要身份驗證的頁面上的SAMLWrapper
和DummySAML
類之間進行切換:
if (getenv('SLIM_MODE') === 'DEV') {
// instantiate DummySAML with test attributes
} else {
// instantiate SAMLWrapper with service provider name
}
有沒有更簡單更好的方法?
一種選擇是將基於環境的開關移到單個包裝器類中。 一個顯而易見的缺點是,您的測試屬性要么需要在類內部進行硬編碼,要么即使在生產中也必須始終傳遞給構造函數。 否則,您將無法使用單個構造函數來支持這兩種方案。
在我自己的應用程序中,我可能會從依賴項注入容器中獲取身份驗證包裝,並注冊一個工廠來檢查環境並返回適當類(真實或虛擬)的實例。 如果您還沒有使用DI,那么遷移可能會很麻煩,但是您始終可以創建一個一次性的靜態工廠來處理適當包裝器的實例化,以減少每個文件頂部的樣板數量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.