从其他类访问已登录的User对象的最佳实践 [英] Best practices accessing a logged in User object from other classes

查看:77
本文介绍了从其他类访问已登录的User对象的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是有关从另一个类存储和访问对象的最佳实践的问题.

This is a question regarding best practice for storing and accessing an object from another class.

我在 PHP 中使用了一个简单的自制MVC范例,该类称为 User ,并且具有其自己的方法和var,它们基本上用作数据库抽象层.

I'm using a simple homemade MVC paradigm in PHP, the class is called User and has its own methods and vars that essentially works as a database abstraction layer.

通过调用new User($userID) 实例化此类,该类将从给定$ userID的数据库中检索数据,如果没有使用该ID的用户,则引发异常.

This class is instantiated by calling newUser($userID) which retrieves the data from a database given $userID or throws an exception if there is no user with that ID.

每个页面都有自己的WebViewController类来管理页面的内容,在某些情况下,页面需要调用$loggedInUser依赖函数,例如WebViewController->displayUserFriends(),如下所示:

Every page has its own WebViewController class governing the content of the page, and in some instances the page needs to call $loggedInUser dependent functions such as WebViewController->displayUserFriends(), which might look like this:

<?php
class WebViewController extends WVCTemplate
{
    // Class vars and methods
    // ...

    public function displayUserFriends()
    {
        foreach($loggedInUser->getFriends() as $friend) {
            // Do something
            // ...
        }
    }
}
?>

是否有一种(符合最佳实践的)方法来将LoggedInUser存储为一种 global 对象,因此可以在任何类或WebViewController内部进行访问没有实例化在每个使用的类中使用它?

Is there a (best practice compliant) way to store LoggedInUser as a sort of global object, so it could be accessed inside of any class or WebViewController without instantiating it inside every class it's used?

推荐答案

最简单的解决方案是使用依赖注入.由于您可能需要多个控制器中的当前用户,因此最好创建一个AuthenticationService(或类似名称),该AuthenticationService提供的方法可以检查用户是否已登录并获取当前登录的用户,并封装该通用功能.然后,您可以在所需的所有控制器中注入服务实例.

The most elegant solution to your problem is to use dependency injection. As you may need the current user in multiple controllers it would be best to create an AuthenticationService (or similar) that provides methods to check whether a user is logged in and to get the currently logged in user and encapsulates that common functionality. You can then inject the service instance in all the controllers where you need it.

那里有几个独立的PHP依赖注入库:

There are several standalone PHP dependency injection libraries out there:

  • PHP-DI
  • Pimple
  • Aura.DI
  • Dice

这篇关于从其他类访问已登录的User对象的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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