Durian Nangka
Durian Nangka

Reputation: 255

In a PHP MVC, what's the correct way of passing controller data to model classes?

In the PHP MVC I'm currently developing, the base controller checks if a user is logged in and, if so, updates its properties (see code).

Since these properties are used in various methods of model classes, I'd like to pass them from the base controller to the (base) model. What's the proper way of doing this?

class Controller {

     protected $user_logged_in = false;
     protected $logged_in_user_id = null;

     function __construct() {
         if(isset($_SESSION['user_id'])) {
              $this->user_logged_in = true;
              $this->logged_in_user_id = $_SESSION['user_id'];
         }
     }
 }

Upvotes: 2

Views: 762

Answers (1)

jeremy
jeremy

Reputation: 10047

I'm doing it like this: the model's constructor accepts an authentication class. This request is fulfilled via autowiring/automatic dependency injection. My injector is programmed to pass the same instance of the authentication class wherever it is asked for so there are no discrepancies (i.e., the authentication class is "shared").

In this way, you aren't actually passing data from the controller to a class in the model layer. Instead, the class/service in the model layer is given direct access to the class it needs through injecting a dependency.

I learned the technique from this video, which is worth watching through the end. Above is just a snippet from my implementation method, however there are tutorials and libraries available for autowiring that may do it different ways. Try searching "php autowiring" or "php automatic dependency injection."

An alternative way to do what you want is to just add a parameter to the service being used in your controller. Your controller should have access to the model layer, so calling an add parameter function shouldn't be a big deal.

Upvotes: 1

Related Questions