【问题标题】:PHP Custom MVC Framework using FrontController使用 FrontController 的 PHP 自定义 MVC 框架
【发布时间】:2013-05-26 19:36:24
【问题描述】:

我有点困惑。我想构建自己的框架只是为了了解一切是如何工作的,而不是将其用于大型项目。

我有一个 FrontController 类,这个类里面有路由功能。

  1. 设置/获取控制器参数的函数
  2. 从控制器设置/获取操作(方法)的函数
  3. 解析请求的 URI 并返回适当的控制器(如果存在)的函数,如果不存在则返回默认控制器,即 IndexController。
  4. Run() 方法执行以下操作:

    public function run() {
        $method    = new \ReflectionMethod($this->controller, $this->action);
        $numParams = $method->getNumberOfParameters();
    
        //fill missing parameters with null values
        if (count($this->params) != $numParams) {
           $tempArray = array_fill(0, $numParams, null);
           $this->setParams($this->params + $tempArray);
        }
    
        $controller   = new $this->controller;
    
        $userInstance = User::getInstance();
    
        //just creates a model based on the controller name by default its
        //Index.php (model)
        $model        = DB::createModel($this->getControllerName());
    
        //run _before before any function
        $controller->_before($model, $userInstance);
    
        call_user_func_array(array($controller, $this->action), $this->params);
        return;
    }
    

    现在我看过教程,他们使用BaseController,然后每个控制器都从这个basecontroller扩展。我的控制器没有从 FrontController 扩展。

我的问题是我需要单独的路由类吗?我需要将 FrontController 拆分成

  1. 基础控制器
  2. Route.php
  3. 模型.php

由于 run() 函数实际上将模型和用户对象传递给控制器​​。

【问题讨论】:

    标签: php model-view-controller


    【解决方案1】:

    要记住的一个基本原则是Single Responsibility Principle。一个设计良好的类只有一个职责。

    所以是的。您需要将路由和所有其他职责分开。

    还要注意,模型必须被视为一个层,而不是一个类或对象。模型层是类(数据访问、服务)的集合。事实上,您的 User 类应该被视为该层的一部分。

    Here's an article which can help you understand the MVC pattern a bit better.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-09
      • 1970-01-01
      • 1970-01-01
      • 2012-03-18
      • 2011-06-21
      相关资源
      最近更新 更多