Access a Symfony user session in a model (Doctrine)

How to access current Symfony user session in Doctrine model?

Two ways (what I know) to do this is to either pull it out of sfContext inside the model:

sfContext::getInstance()->getUser()->getCanSwim(); 

Or pass the sfUser instance (or part) directly to the model from the controller:

 UserTable::goSwimming($sf_user->can_swim); 

But is any of these methods better than the other, or is this not the right way to do all this?

+4
source share
3 answers

For such situations, you should consider using the dependency injection design pattern as the Fabien Potencier clearly explains .

The idea is that you must enter all your dependencies into your dependent object, for example, in your case, the user or the context.

This (second option) would be a less MVC-killer way, afaic.

+4
source

Dependency injection is an exceptional context, but I think sometimes it’s overkill.

Why introduce an additional method or redefine the constructor if the only thing you need in your example is to know if the current user can swim?

So IMMO, if the use case is simple, you can very well go for the second option that you have provided and omit the dependency only on the value on which it depends:

 goSwimming($sf_user->can_swim); 

Of course, it all depends on the actual concepts used and on how extended one class is from another.

If this is only this case (the result depends on user negligence to swim), than this is easy to simplify. But if the called method / class can ultimately use more attributes than this, it is probably best to go with the Injection Dependency technology that has already been discussed. UserTable probably depends on sfUser for other things, so this seems like a complete class dependency.

+2
source

Source: https://habr.com/ru/post/1332247/


All Articles