dscdttg4389 2014-10-21 07:15
浏览 29
已采纳

从其他类访问登录用户对象的最佳实践[关闭]

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

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.

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.

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
            // ...
        }
    }
}
?>

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?

  • 写回答

2条回答 默认 最新

  • dongshenchi5364 2014-10-21 07:50
    关注

    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.

    There are several standalone PHP dependency injection libraries out there:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效