【问题标题】:Instantiate which PHP class based on dev or production environment根据开发或生产环境实例化哪个 PHP 类
【发布时间】:2016-09-22 06:46:17
【问题描述】:

我有 integrated SimpleSAMLphp with my application,但它仅适用于生产环境,因为与其他地方的 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;
    }
}

但这意味着我必须在所有需要身份验证的页面上在 SAMLWrapperDummySAML 类之间切换:

if (getenv('SLIM_MODE') === 'DEV') {
    // instantiate DummySAML with test attributes
} else {
    // instantiate SAMLWrapper with service provider name
}

有没有更简单更好的方法?

【问题讨论】:

    标签: php environment simplesamlphp dev-to-production


    【解决方案1】:

    一种选择是将基于 env 的切换移动到单个包装类中。一个显而易见的缺点是您的测试属性需要在类中进行硬编码,或者即使在生产中也总是传递给构造函数。否则,您将无法使用单个构造函数支持这两种情况。

    在我自己的应用程序中,我可能会从依赖注入容器中获取身份验证包装器,注册一个检查环境并返回适当类(真实或虚拟)实例的工厂。如果您尚未使用 DI,迁移可能会很痛苦,但您始终可以创建一次性静态工厂来处理适当包装器的实例化,以减少每个文件顶部的样板数量。

    【讨论】:

      猜你喜欢
      • 2015-12-07
      • 2011-08-06
      • 1970-01-01
      • 2010-09-29
      • 2021-09-10
      • 1970-01-01
      • 2018-06-04
      • 2012-05-21
      • 1970-01-01
      相关资源
      最近更新 更多