模型和行为中的会话可访问性 [英] Session accessibility in model and behavior

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

问题描述

我在Cake 3.x中工作,需要登录的用户ID。
在Cake 2.x中,您可以通过会话或AuthComponent(多么脏)

  AuthComponent ::用户(); 

但是现在在Cake 3.x中...我如何能够干净地访问会话获取用户ID的方法?



我发现: http://book.cakephp.org/3.0/en/development/sessions.html
但它说从控制器,组件,视图中获取会话很容易,以及更多...



编辑:一个非常非常肮脏的解决方案可能是获取 $ _ SESSION 变量。 CakePHP不建议使用此选项...因此,我推荐其他解决方案:)



谢谢!

解决方案

您将需要手动传递值或将其置于可全局访问的对象中。检查此插件以了解如何以一种干净的方式完成它,也有可能该插件实现的是您无论如何都想做的事情:)



https://github.com/hmic/cakephp-blame



编辑:我刚刚检查了该插件中的源代码,似乎它改变了我不同意的方法。这个其他插件( https://github.com/ceeram/blame )包含了我原来的实现



它的作用是将事件附加到您的模型,以便将当前登录的用户传递给表事件,并且可以通过任何行为读取。 / p>

I am working in Cake 3.x and need the logged in users id. In Cake 2.x you were able to get this via the session or the AuthComponent (how dirty)

AuthComponent::user();

But now in Cake 3.x... How am I able to access the Session in a clean way to get the users id?

I've found: http://book.cakephp.org/3.0/en/development/sessions.html But it says it's easy to get the session from Controllers, Components, Views, and more...

EDIT: A very very dirty solution could be to get the $_SESSION variable. CakePHP does not recommend this option... So, I prever another solution :)

Thank you!

解决方案

You will need to manually pass the value or put it available in an object that is globally accessible. Check this plugin to get an idea of how it can be done in a clean way, it is also probable that what this plugin implements is what you were trying to do anyway :)

https://github.com/hmic/cakephp-blame

Edit: I just checked the source code in that plugin and it seems like it changed the approach to one I don't agree with. This other plugin (https://github.com/ceeram/blame) contains the original implementation that I had in mind.

What it does is attaching an event to your models so that the currently logged in user is passed to the table events and can be read by any behavior.

这篇关于模型和行为中的会话可访问性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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