Controllers need to be classes?

3

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

Example, I have a controler for the "profile" view that displays user 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, is it possible to change the value of $ action when instanciating a new Controller?

Another example is a generic file that I'm 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 appropriate?

    
asked by anonymous 20.03.2015 / 18:06

1 answer

3

The ideal is to always use classes, this will make your life much easier. I also advise to leave the management of the includes automatically, if not use any framework and to do everything in the nail invest a little time studying link , I believe this will already motivate you to use classes. On making a generic control by changing the data in the constructor, make sure instead you no longer want to create an abstract class and use the concept of inheritance and polymorphism to better serve your needs.

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

The MVC concept can be applied even in languages that are not Object Oriented, but PHP allows Object Guidance, based on this: Among the options presented I would choose the first one as the most appropriate between the two.

    
20.03.2015 / 18:25