问题描述
我有这个用户类
class User{
private $logged = false;
private $id;
public function User() {
//> Check if the user is logged in with a cookie-database and set $logged=true;
}
public function isLogged() {}
public function editPerms() {}
//> other methods
}
现在考虑到我不能有超过1个用户登录当然,因为我们正在谈论一个单一的http请求)在哪里应该存储我的信用证?
Well now considering I can't have more than 1 user logged (of course because we are talking for a single http request) in Where should i store the ref of my istance?
这是单例将是有用的,但这些日子大家都说单身是邪恶的(如静态方法)。
This is the case where singleton would be useful but these days everyone say singleton is evil (like static methods).
- http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/
- http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/
我可以做一个 $ GLOBALS ['currentUser'] = new User();
并拥有无处不在,但我认为这比一个单身人士更糟糕。
I could do a $GLOBALS['currentUser'] = new User();
and having it accesible everywhere but I think this is worse than a singleton.
那么我可以o?
请注意,我不需要在请求之间保存此实例。 我只需要在同一个请求中的框架中访问这个实例。
So what Can I do?
Please note I don't need to save this instance between requests. I just need a way to access this instance in my framework within the same request.
如果你想知道我现在所做的一切我的帮助对象是一个服务容器(被认为是坏的):
If you want to know what i do now for all of my Helper Objects is a Service Container (that's considered as well bad):
function app($class) { //> Sample
static $refs = array();
if (!isset($refs[$class]))
$refs[$class] = new $class();
return $refs[$class];
}
//> usage app('User')->methods();
(IE what )
推荐答案
模式应该是一个有用的指导,像以前成功的软件抽象图书馆。这些日子过去,人们将模式视为某种宗教信仰,无论是正确还是错误,无论方案的内容如何。
Patterns are supposed to be a helpful guide, like a library of previously successful software abstractions. Too often these days people view patterns as being some kind of religion where things are either "right" or "wrong" regardless of the context of the program.
想想什么你想以一种对你有意义的方式实现和映射。用这种模式和这种模式之间的微小区别来思考错过了这一点,它不会得到你的程序的写作。通过学习
Think about what you want to achieve and map in out in a way that makes sense to you. Fuggering about with minute distinctions between this pattern and that pattern misses the point, and it won't get your program written. Learn by doing!
HTH。
这篇关于我应该为User类的唯一实例使用哪种模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!