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

南楼画角 提交于 2019-12-24 00:48:44

问题


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'];
         }
     }
 }

回答1:


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.



来源:https://stackoverflow.com/questions/36260830/in-a-php-mvc-whats-the-correct-way-of-passing-controller-data-to-model-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!