我应该扩展控制器还是创建助手? [英] Should I extend Controller or Create Helper?
问题描述
我需要访问CodeIgniter应用程序中多个控制器中的某些功能。目前,这些功能实际上是基本功能,例如:
I need to access some functions in multiple controllers in a CodeIgniter application. At the moments the functions are really basic and a few, For example:
generate_random_key() //just a random string
is_logged() //check if user is logged or not
logged_user_only() //if unlogged, redirect
unlogged_user_only() //if logged, redirect
由于这些功能与登录相关,因此我可以将它们放在帮助程序文件中,然后放置在 Application / helpers / login_helper中.php
As these functions are related to login, I can either put them in a helper file and place in Application/helpers/login_helper.php
OR
我可以扩展CI_Controller,方法是创建 MY_Controller.php
并将其放在 Application / Core / MY_Controller.php
i can extend the CI_Controller, by creating MY_Controller.php
and put it in Application/Core/MY_Controller.php
这两种方法均有效,但我想知道哪种方法更适合此类任务。我认为应该有一些规则,何时扩展Controller或何时使用辅助程序?
Both of the methods work, but I am wondering which one fits better for this kind of task. I think there should be some rules, when the Controller should be extended or when the helper should be used?
推荐答案
在其他控制器中(并且仅在其他控制器中)重新使用这些函数,我建议将它们重构为MY_Controller。
这也使您可以直接访问$ CI实例(而不是调用get_instance())
If you're using these functions in your other controllers (and only in your other controllers) I would suggest refactoring them into MY_Controller. This would also give you direct access to the $CI instance (instead of calling get_instance())
另一方面,您可以创建一个身份验证库。
On the other hand, you could create an Authentication library. This might be more suitable..
编辑:
我建议使用MY_Controller作为基础,包含身份验证包装函数,可从管理此类内容的库中调用功能。
I would recommend having a MY_Controller as a base, that contains auth wrapper functions, which invoke functionality from a Library that manages this type of thing.
这篇关于我应该扩展控制器还是创建助手?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!