php - 面向对象的 PHP 中的实例配置

标签 php static-methods

我正在寻找将一组属性(配置)应用于新创建的实例的最有效方法。我的第一个目标是保持应用程序面向对象,第二个目标是使用 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...

最佳答案

我不明白你为什么需要 ViewLogin1。如果您想在您的框架中准备它并立即在应用程序中使用它,即使没有新功能,我也会在框架中使用 ViewLoginAbstract 并在应用程序中使用 ViewLogin介绍(请记住,您可能希望将重定向替换为 die('What the hack are you trying to do?') 或类似的内容)。

另一方面,当您的应用程序中有多个登录表单时,我会按照 Zend Framework 这样的方式进行操作正在进行。

当您查看他们如何使用 *Controller class 时他们为每个 Controller 使用一个类和一个通用类 ViewModel class意见。

更详细的默认indexAction :

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

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

在我看来,登录后重定向页面的悬停应该是 Controller 而不是 View 的责任( View 应该只负责显示 html + 其他前端内容)所以我不太确定你为什么要放置 redirect 进入视野。

关于php - 面向对象的 PHP 中的实例配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16003116/

相关文章:

php - 获取谷歌字体列表

php - 在静态函数中使用 $this 失败

java - 将方法更改为静态 - 错误?

c++ - 静态工厂方法和静态对象内存泄漏

java - 我试图找出为什么我的类(class)工资单没有正确添加所有工资......帮助我找到错误

c++ - 友元和静态成员函数有哪些类型的成员访问权限?

php - 如何在mysql语句中使用LIKE和通配符

php array_intersect 关联和索引数组

php - 无法更改 php.ini 中的 max_input_time

javascript - 向 PHP 脚本提交 PDF 表单仅适用于 Adob​​e Reader XI