使用 Kohana/MVC 框架访问模型内的控制器方法
我需要能够使用 Kohana V2.3 框架从模型访问控制器方法。目前,我正在将控制器对象(通过参考)传递给创建时的模型,该模型工作得很好,但我不禁认为有一种更“干净”的方法 - 有人有任何建议吗? Kohana V3 会通过其 HMVC 模式解决这个问题吗?
这可能会有所帮助: http://www .ifc0nfig.com/accessing-the-calling-controller-in-a-model-within-kohana/
I need to able to access controller methods from a model using the Kohana V2.3 framework. At the moment I'm passing the controller object (by ref.) to the model on creation which works perfectly fine but I can't help think there is a more "cleaner" way - does anybody have any suggestions? Would Kohana V3 resolve this with its HMVC pattern?
This may help: http://www.ifc0nfig.com/accessing-the-calling-controller-in-a-model-within-kohana/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么模型中需要控制器?这违反了 MVC 的概念,因为现在模型(数据层)依赖于控制器层。
您的模型在控制器中所需的功能应卸载到通用库中。然后可以从控制器和模型进行访问。
Why do you need the controller inside the model? This violates the concept of MVC because now the model (data layer) is dependent on the Controller layer.
The functions your model needs in your controller should be offloaded to a generic library. Then accessible from both the controller and model.
您正在控制器中实例化 Facebook 连接器,并且您不想执行两次,因此您希望模型能够访问它是有道理的。到目前为止,一切都很好。有两种方法可以做到这一点。
1) 创建一个库,其中包含包装 Facebook 实例的单例实例。看起来像这样:
您的控制器和模型都将像这样访问它:
Kohana 2.x 的示例代码:
http://dev.kohanaframework.org/ items/kohana2/repository/entry/trunk/system/libraries/Database.php
2) 由于除了访问 Facebook 类之外,您可能不会对实际库执行任何操作,因此只需创建一个简单的帮助程序包装一个单例:
您的控制器和模型都将像这样访问它:
You're instantiating the Facebook connector in the controller, and you don't want to do that twice so it makes sense that you'd want the model to have access to it. So far so good. There are two ways to do this.
1) Create a library which has a singleton instance that wraps the Facebook instance. That would look like this:
both your controller and your model would access it like this:
Example code from Kohana 2.x:
http://dev.kohanaframework.org/projects/kohana2/repository/entry/trunk/system/libraries/Database.php
2) Since you're probably not going to do anything with an actual library other than just access the Facebook class, just create a simple helper that wraps a singleton:
both your controller and your model would access it like this: