【问题标题】:Instance configuration in Object Oriented PHP面向对象 PHP 中的实例配置
【发布时间】:2013-04-14 19:05:16
【问题描述】:

我正在寻找将一组属性(配置)应用到新创建的实例的最有效方法。我的第一个目标是保持应用程序面向对象,第二个目标是使用 DI 容器的能力。这是我到目前为止提出的一个示例:

class ViewLogin {
  public $msgLoginGranted;
  public $msgLoginFailed;

  public function __construct(){
  }

  protected function onSuccess() {
    return $this->msgLoginGranted;
  }

  protected function onFailure() {
    return $this->msgLoginFailed;
  }
}

class ControllerLogin {
  public function __construct(ModelLogin $model, ViewLogin $view) {
  }
}

为了保持 ViewLogin 干净,并将配置数据与代码分开,最好的做法是:

创建一个新类 ViewLogin1

class ViewLogin1 extends ViewLogin {
  public function __construct() {
    $this->msgLoginGranted = 'Welcome!';
    $this->msgLoginFailed = 'Login Failed!';
  }
}

缺点:静态类内容,没有新功能,污染类空间

将配置对象传递给 ViewLogin

class ViewLogin {
  public function __construct(Config1 $config) {
    $this->msgLoginGranted = $config->msgLoginGranted;
    $this->msgLoginFailed = $config->msgLoginFailed;
  }
}

为 ViewLogin 创建一个装饰器?

将配置移至 XML/JSON/YAML...

【问题讨论】:

    标签: php static-methods


    【解决方案1】:

    我不明白你为什么需要ViewLogin1。如果你想在你的框架中准备它并立即在应用程序中使用它,我会在框架中使用ViewLoginAbstract,在应用程序中使用ViewLogin,即使不会引入新功能(记住你可能想要替换使用die('What the hack are you trying to do?') 或类似的东西重定向)。

    另一方面,当您的应用程序中有多个登录表单时,我会像Zend Framework 那样走。

    当您查看他们如何使用*Controller class 时,他们为每个控制器使用一个类,为视图使用一个通用ViewModel class

    更详细的默认indexAction

    public function indexAction()
    {
        return new ViewModel(array(
            'content' => 'Placeholder page'
        ));
    }
    

    所以我会重用 ViewLogin 并只传递配置,因为没有引入新功能(只要确保您以后不想添加日志记录或其他功能)。

    在我看来,登录后重定向页面的悬停应该是控制器而不是视图的责任(视图应该只负责显示 html + 其他前端内容)所以我不确定你为什么将redirect 放入视图中。

    【讨论】:

    • 你对重定向的事情是正确的......我在尝试编写这个虚构的例子时搞砸了。改为消息传递。
    • @user1517081 在这种情况下,您肯定只使用选项。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-25
    • 2014-01-03
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    • 1970-01-01
    • 2014-08-25
    相关资源
    最近更新 更多