GET and POST functions in PHP / CodeIgniter
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();
The parameters only allow you to retrieve GET
variables. If you want to get the POST
variables, you need to use the Input library which is automatically loaded by CodeIgniter:
$this->input->post('data');
So, in your case, it would be:
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') }}
Note that you can also use this library to obtain GET
, COOKIE
and SERVER
variables:
$this->input->get('data');$this->input->server('data');$this->input->cookie('data');