PHP 设计模式 : Multiple websites inside one script

标签 php design-patterns

通常使用什么解决方案、模式?

我想摆脱我的 Controller 、模型等中的 if/else 语句。

例如:

if($domain==1) {
// do this
}
elseif($domain==2) {
// do this
}
elseif...

想摆脱这种疯狂。无法想象当至少有 20 个网站时会是怎样的困惑局面。

目前我正在为每个域使用配置和路由文件。但这还不够。

无法摆脱模型和 Controller 内部的这种困惑。

我正在考虑某种占位符和每个域的单独静态类,以及用于这些占位符的方法 + 魔术调用。

例如我在 Controller 中有 Action :

public function postAction(){

$model=new Model();
$this->view->data=$model->get($placeholder_generates_and_return_settings_array); // else default is used

// custom placeholder
// execute custom class method if it's exist

// some model again

// custom placeholder
// execute custom class method if it's exist 

// etc

}

当前 View 里面提供了占位符类,类型可以赋值。如数据修改、模型配置生成等。

如果不克隆 Controller 、模型或为其中的每个域创建无数的 if/elseif 语句,您将如何解决多个域的这个问题?

更新

如何描述我的需求。我正在尝试创建具有默认逻辑的可重用 Controller 。只需在所需位置(占位符)、数据修改等处使用域相关逻辑填充/混合 Controller 。可能存在 Controller 模板之类的东西,是否存在任何模式?

为占位符提供所有必需的(当前)数据,以便在需要时进行修改或进一步处理并将其返回。

我想我必须要制造自己的“自行车”。 :D

最佳答案

根据您提供的信息,我假设您希望根据域以不同方式显示数据。还假设您的数据保持不变,您可以使用策略模式来解决您的问题。

您的类结构将如下所示:

    class yourClass
    {
        protected $_strategy;

        public function setStrategy($strategy)
        {
            $this->_strategy = $strategy;
        }

        public function showYourData()
        {
            return $this->_strategy->show($this)
        }
    }

对于每个域,您构建一个单独的策略类,如下所示:

    class domainStrategy
    {
        public function show(yourClass $yourClass)
        {
             // Get your classdata here
             $data = $yourClass->whateverFunctionYouNeed();
             // Do what you want for this domain
             return $output;
        }
    }

我希望这能让你开始,我相信你可以在需要时找到更多关于 strategypattern 的文档

关于PHP 设计模式 : Multiple websites inside one script,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8224936/

相关文章:

php - WordPress -> 仅显示二级类别

php - 如何重组数组

php - 响应式布局中的动态列数和行数

c# - MVVM 数据访问层放在哪里?

design-patterns - 带有 Backbone、API 设计理念的基于事件的权限?

web-services - 最佳实践 - REST API 版本控制 : Where and How to physically store source code

php - 如何将 2 个数组分组

php - 插入时 Doctrine 自动截断值

java - 这个问题的最佳设计模式

java - 用于标记应同步的对象的属性的配置机制