会话和PHP类 [英] Sessions and PHP classes

查看:70
本文介绍了会话和PHP类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯了Java,目标c和一些c ++. 现在,我想使用PHP创建网站.我创建了几个类,但为了简单起见,共创建了3个类.

I'm used to java, objective c and a little c++. Now i want to use PHP to create a website. I created several classes but to keep it simple: 3 classes.

帐户-DataMapper-DataManager

Account - DataMapper - DataManager

这意味着我可以从数据库中获得一个帐户.在DataManager中,我跟踪所有事物.就像用户的userId一样.

This means that i can get an account from the database. In DataManager i keep track of all things. Like the userId of the user.

问题是,通常所有设置的变量都保持设置"状态,但是现在我使用的是php,因此我迫切需要通过会话来存储它们. 数据管理器:

The thing is, normally all setted variables stay 'set', but now i'm using php i apperently need to store them by using a session. DataManager:

<? php
class DataManager
{
    // Hold an instance of the class
    private static $dm;
    private $dataMapper;
    private $dictationView;
    private $userId;

    private function __construct()
    {
        $this->dataMapper = new DataMapper();
        $this->dictationView = new DictationView();
    }

    // The singleton method
    public static function singleton()
    {
        if (!isset(self::$dm)) {
            $c = __CLASS__;
            self::$dm = new $c;
        }

        return self::$dm;
    }

    // Prevent users to clone the instance
    public function __clone()
    {
        trigger_error('Clone is not allowed.', E_USER_ERROR);
    }


    function __get($prop) {
        return $this->$prop;
        }

    function __set($prop, $val) {
        $this->$prop = $val;
        }
}

?>

如果我在单例DataManager类中设置了userId,则下次我 调用DataManager类的实例,它将不会记住用户ID.我猜我必须在某个地方处理会议.如何在DataManager中以良好的OOP方式使用会话?谢谢!

If i set the userId in the singleton DataManager class, the next time i call an instance of the DataManager class it will not rememeber the userId. Somewhere i have to deal with session i guess. How to use sessions in a good OOP way in the DataManager? Thanks!

推荐答案

如果需要,可以为PHP中的会话创建包装器.这实际上可能是有益的,尤其是如果您的应用程序后来不得不迁移到服务器集群并且会话将被移动到分布式缓存时,尤其如此.然后,为促进这种迁移,您只需要在相同的Session类接口的情况下提供不同的实现.

If you want you can create a wrapper for sessions in PHP. It actually could be beneficial, especially if your application later had to migrate to a cluster of servers and sessions would be moved to a distributed cache. Then, to facilitate this migration you would only have to provide different implementation if same Session class interface.

那是

此代码本身不是是好的OOP.您应该停止使用单例.而且,如果您的类需要DataMapperDictationView的实例,则应在类外部创建它们并在构造函数中提供它们. 代替创建紧密耦合,因为构造函数正在制作其他对象.

This code there itself is not a good OOP. You should stop using singletons. And, if you class require instances of DataMapper and DictationView, then they should be created outside the class and provided in the constructor. Instead of creating a tight coupling because you constructor is making other objects.

这篇关于会话和PHP类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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