Use controller class as helper or model
I have a bunch of controllers i.e. users
, admin
And guest
I have a ton of the controller functions admin
that I want to use users
. Since accessing the controller would mean a redirect, I would like this behavior not to be enforced, so the question is
- Can I use the controller as a helper / model and load it? loading it as a helper / model would be easier for me as there are many controllers and I don't want to add a new file.
im still new in CI please name me.
source to share
You can load it like a regular model or library using
$this->load->library()
here is a LIKE QUESTION that you might want to look at, the answer you are looking for is the third.
Note:
If you are using CI3 this will not work. this is useful if you also read comments.
source to share
You can create helper classes that will do some logic, and you can call them in either controllers or views. I don't know if this is so. For example, I created a folder called Repository (repository template) where I implement, for example, the logic to display the menu:
public class reposAccount
{
public static List<Sp_ShowMenuList_Result> ShowMenuList(int RoleID)
{
myEntities db = new myEntities();
List<Sp_ShowMenuList_Result> ListShowMenu = db.Sp_ShowMenuList(RoleID).ToList();
return ListShowMenu;
}
}
And in the view, I just call it "Helper":
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
//do some preparatory activities, then i call the helper:
foreach (var obj in reposAccount.ShowMenuList(RoleId).Where(z => z.ParentMenu == null).OrderBy(z => z.MenuOrder).ToList())
{
@: <li>@Html.ActionLink(obj.MenuName, "Index", obj.Controler_Name)</li>
}
}
Same behavior or methods, you can call them on every controller.
source to share