PHP / CodeIgniter中的GET和POST函数


GET and POST functions in PHP / CodeIgniter

我喜欢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中实现同样的事情?

谢谢

我错过了什么吗?我怎样才能达到同样的效果呢CodeIgniter吗?

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

CodeIgniter实现模型-视图-呈现者模式,而不是MVC(即使它这么说)。如果你想实现一个真正类似mvc的应用程序,那你就错了。

在MVP:

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

注意:模型不应该是单一类。有很多类。为了便于演示,我把它命名为"Model"。

它看起来像:

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模板,而是负责表示逻辑的类
  • View可以直接访问Model
  • 控制器不应生成响应,但应更改模型变量(即从$_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();

参数只允许检索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');