• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
MVC Best Practices

#1
[eluser]darkhouse[/eluser]
I'm just trying to find out how the best way to do things are. For instance, I have a site that's almost done, and I need to add an "alerts" area into the header of all pages if a user is logged in. If they have at least 1 new alert, the link will say "You have 1 new alert". The HTML for the area is in just one view file, but the view is loaded from every controller, so it seems like I need to add the functionality to get the number of alerts into every controller wherever the view is loaded, but it seems redundant to me.

Can somebody enlighten me on some best practices for this sort of thing, or any other tips, I'm still fairly new to the concept of MVC, though I love it.

#2
[eluser]gon[/eluser]
I would write a library for that.

So you just have to load the library, and it automatically checks if the user is logged, and if it has alerts or not.
In the library you could write a method like "get_alerts_html". So it will return null if there is no alerts, or the html for showing the alerts.
You won't have to put logic in the controllers or views. Just put <?=$user_alerts?> in the views. If there are no alerts, nothing will be shown.

#3
[eluser]darkhouse[/eluser]
Well, I did write a library to control the alerts, for sending, reading, etc. But how do I get $user_alerts into the view without putting something in the controller?

#4
[eluser]darkhouse[/eluser]
I guess I could autoload the alerts library, and just do $this->alerts->alerts_html in the view. Is that the best method?

#5
[eluser]wiredesignz[/eluser]
Hi darkhouse, Welcome to CI forums.

You could also use the MY_Controller extension to manage your alerts and then extend your own Controllers from this.

Code:
class MY_Controller extends Controller
{
    public function __construct()
    {
        parent::__construct();

        $this->load->library('alerts');

        $this->load->vars($this->alerts->get_alerts());  // extracts alerts into view buffer
    }
}

class Page_Controller extends MY_Controller
{
    public function __construct() {}
}

#6
[eluser]darkhouse[/eluser]
I had thought about this also, and I will probably do this from now on. The issue in this case was the site was almost completely done, and it's not a small site, so I needed a way to retrofit.

What gon suggested is what I did in this case, just autoload the alerts library, and then have a function to output the link text which is called from the view. Works perfect.

But, since my question was about best practices, I think extending the controller to be able to do these sort of things, and then extending from that for all the different pages makes the most sense.

Thanks for the help guys.


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2019 MyBB Group.