2

我喜欢 MVC(非常喜欢),我正在尝试用当今所有主要的 Web 语言自学一个 MVC 架构框架。

我目前正在使用 CodeIgniter 和 PHP。我在网上搜索了一种方法,使相同的函数对 POST 和 GET 表现不同,但找不到任何东西。CodeIgniter 有这个功能吗?

如果您使用过 Ruby On Rails 或 ASP.NET MVC,您就会知道我在说什么,在它们的框架中我们可以这样做:

[GET]
public ActionResult Edit(int Id)
{
    // logic here for GET
}

[POST]
public ActionResult Edit(EntityX EX)
{
    // logic here for POST
}

我已经习惯了这一点,以至于我发现很难在没有这种有用能力的情况下获得同样流畅的功能。

我错过了什么吗?如何在 CodeIgniter 中实现相同的目标?

谢谢

4

2 回答 2

5

我错过了什么吗?如何在 CodeIgniter 中实现相同的目标?

如果你想学习如何在 PHP 中真正实现 MVC,你可以从 Tom Butler 的文章中学习

CodeIgniter 实现了 Model-View-Presenter 模式,而不是 MVC(即使它这么说)。如果你想实现一个真正类似于 MVC 的应用程序,那么你就走错了路。

在 MVP 中:

  • View 可以是类或 html 模板。视图永远不应该知道模型。
  • 视图不应该包含业务逻辑
  • Presenter 只是 View 和 Model 之间的粘合剂。它还负责生成输出。

注意:模型永远不应该是单数 class。它有许多类。我将其称为“模型”只是为了演示。

所以它看起来像:

class Presenter
{
    public function __construct(Model $model, View $view)
    {
       $this->model = $model;
       $this->view = $view;
    }

    public function indexAction()
    {
         $data = $this->model->fetchSomeData();

         $this->view->setSomeData($data);

         echo $this->view->render();
    } 
}

在 MVC 中:

  • 视图不是 HTML 模板,而是负责表示逻辑的类
  • 视图可以直接访问模型
  • 控制器不应生成响应,而是更改模型变量(即从$_GET或分配变量$_POST
  • 控制器不应该知道视图

例如,

class View
{
   public function __construct(Model $model)
   {
       $this->model = $model;
   }

   public function render()
   {
      ob_start();

      $vars = $this->model->fetchSomeStuff();

      extract($vars);

      require('/template.phtml');

      return ob_get_clean();
   }
}

class Controller
{
    public function __construct(Model $model)
    {
      $this->model = $model;
    }

    public function indexAction()
    {
        $this->model->setVars($_POST); // or something like that
    }
}

$model = new Model();
$view = new View($model);

$controller = new Controller($model);

$controller->indexAction();

echo $view->render();
于 2013-04-29T09:21:30.797 回答
2

参数仅允许您检索GET变量。如果要获取POST变量,需要使用 CodeIgniter 自动加载的 Input 库:

$this->input->post('data');

因此,在您的情况下,它将是:

public function edit($id = -1)
{
    if($id >= 0 && is_numeric($id))
    {
        // logic here for GET using $id
    }
    else if($id === -1 && $this->input->post('id') !== false)
    {
        // logic here for POST using $this->input->post('id')
    }
}

请注意,您还可以使用此库来获取GET,COOKIESERVER变量:

$this->input->get('data');
$this->input->server('data');
$this->input->cookie('data');
于 2013-04-29T09:01:29.693 回答