Kaizokupuffball Kaizokupuffball - 3 months ago 9
PHP Question

PHP MVC structure where to put own classes

I just started taking a look at the MVC pattern.
My question is:

Where would I put my other class files (Database, User, Logger, Mailer, etc)? Should I create a new directory for them, e.g.

libs
?

Should I instantiate the classes in the
Controller
inside the
model
function?

<?php

class Controller {
protected function model($model) {
require_once('../app/models/'. $model .'.php');

return new $model();
}

protected function view($view, $data = []) {
require_once '../app/views/'. $view .'.php';
}
}

Answer

Where would I put my other class files (Database, User, Logger, Mailer, etc)? Should I create a new directory for them, e.g. libs?

Putting them in separate files since they all provide different functionality should be fine. There is no difference in your directory naming - as long as it matches the naming conventions of your project or general (probably, even better).

Should I instantiate the classes in the Controller inside the model function?

No. As far as I see it, the flow could be similar to:

  1. The index file receives the request and initiates a new bootstrap instance
  2. bootstrap sets the throwable handler and the router
  3. router then calls the respective method basing on the request method and uri provided by matching against a set of routes
  4. The matching route initializes all the components of the MVC triad and the callable method. The components (Model layer, View layer, and Controller layer) are passed to the method called by the router. In my case, I call the class FrontController, the method init.
  5. Basically, the init is the place where the MVC triad is actually made. Model layer is responsible for business logic, persistence, etc. It is important to note that Model is not a single file or class (the same for View and Controller). Both View layer and Controller layer consult the Model layer to do the respective actions. View layer's mission is to manage the output, for example, decide wether the output will have Content-Type of application/json or text/plain, or which Template to render. Also, Views are not Templates, which are meant for displaying the data. Note here, Views ask the necessary data directly from the Model layer; there is no interaction with the Controller layer whatsoever. Finally, Controller layers steps in when there is a need for interaction, for example, a user submits a form, the respective Controller filter the input and calls the method from the Model layer.