Do controllers necessarily need to be classes?

Asked

Viewed 335 times

3

When we are developing a system using MVC from scratch, each controller needs to be a class or I can simply use a file containing some functions that will be called as the action sent by View?

Example, I have a controller for the "profile" view that displays the user’s data and updates them if necessary.

include_once('model/usuario.php');
class Controller{
  public $dadosUser;

  function __construct($action = null){
    if(empty($action)){
        $user = new Usuario();
        $id = $user->id;
        $this->dadosUser =  $user->loadUsr($id);
     }
  }
}

In this case, you can change the value of $action when a new Controller is instantiated?

Another example is a generic file that I am implementing as follows:

 include_once('../model/usuario.php');

 $action = isset($_POST['action']) ? $_POST['action'] : "";

 if($action){
  switch($action){
    case 'login':login(); break;
    case 'listar':getAllAqr();break;
    default: break;
  }
 }

 function login(){
   $email = isset($_POST['email']) ? $_POST['email'] : "";
   $pwd = isset($_POST['senha']) ? $_POST['senha'] : "";

   $usr = new Usuario();
   $usr->login($email, $pwd);

   $id = $usr->id;
   if($id){
    header("Location: http://localhost/aldeia/dashboard.php");
   }else
    header("Location: http://localhost/aldeia/login.php");
 }

Which of these two forms is the most suitable?

1 answer

3


The ideal is to always use classes, this will make your life much easier. I also advise you to leave the management of includes automatically, if you are not going to use any framework and do everything in the nail invest a little time studying the http://php.net/manual/en/function.spl-autoload-register.php, I believe that will motivate you to use classes. About doing a generic control by changing the data in the constructor, make sure that instead it no longer suits you to create an abstract class and use the concept of inheritance and polymorphism to better suit your needs.

In this link you can find more object orientation concepts in php In this link you can find more concepts of MVC Another suggestion would be the use of namespace

MVC however does not require you to use Classes, The concept of MVC can be applied even in languages that are not Object Oriented, but PHP allows Object Orientation, based on this: Among the options presented I would choose the first as the most suitable between the two.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.