在PHP MVC中,将控制器数据传递到模型类的正确方法是什么? [英] In a PHP MVC, what's the correct way of passing controller data to model classes?

查看:104
本文介绍了在PHP MVC中,将控制器数据传递到模型类的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我目前正在开发的PHP MVC中,基本控制器检查用户是否已登录,如果是,则更新其属性(请参见代码).

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

推荐答案

我正在这样做:模型的构造函数接受身份验证类.该请求通过自动装配/自动依赖注入来实现.我的注射器被编程为在任何要求的地方都传递身份验证类的相同实例,这样就不会出现差异(即,身份验证类是共享的").

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.

我从这部视频中学到了这项技术,值得一看到底.上面只是我的实现方法的摘录,但是有一些可用于自动装配的教程和库可能会以不同的方式实现.尝试搜索"php自动装配"或"php自动依赖项注入".

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."

执行所需操作的另一种方法是仅向控制器中使用的服务添加参数.您的控制器应该有权访问模型层,因此调用add参数函数没什么大不了的.

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.

这篇关于在PHP MVC中,将控制器数据传递到模型类的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆