GET and POST functions in PHP / CodeIgniter

J86 picture J86 · Apr 29, 2013 · Viewed 9.6k times · Source

I like MVC (a lot), and I am trying to teach myself a framework of MVC architecture in all the major web languages of today.

I am currently on CodeIgniter and PHP. I searched online for a way to make the same function behave different for a POST and GET but couldn't find anything. Does CodeIgniter have this feature?

If you've used Ruby On Rails or ASP.NET MVC you'll know what I'm talking about, in them frameworks we can do this:

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

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

I am so used to this, that I am finding it hard wrapping my head around how to get the same smooth functionality without that useful ability.

Am I missing something? How can I achieve the same thing in CodeIgniter?

Thanks

Answer

Yang picture Yang · Apr 29, 2013

Am I missing something? How can I achieve the same thing in CodeIgniter?

if you want to learn how to truly approach MVC in PHP, you can learn it from Tom Butler articles

CodeIgniter implements Model-View-Presenter pattern, not MVC (even if it says so). If you want to implement a truly MVC-like application, you're on the wrong track.

In MVP:

  • View can be a class or a html template. View should never be aware of a Model.
  • View should never contain business logic
  • A Presenter is just a glue between a View and the Model. Its also responsible for generating output.

Note: A model should never be singular class. Its a number of classes. I'll call it as "Model" just for demonstration.

So it looks like as:

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();
    } 
}

In MVC:

  • Views are not HTML templates, but classes which are responsible for presentation logic
  • A View has direct access to a Model
  • A Controller should not generate a response, but change model variables (i.e assign vars from $_GET or $_POST
  • A controller should not be aware of a view

For example,

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();