Welcome Guest, Not a member yet? Register   Sign In
Hooks to achieve redundant code.
#1

[eluser]eedfwChris[/eluser]
I am trying to figure out how to call a set of code that would always be called at the loading of a controller. For instance the code below gets the title prefix from a config file after loading the config file and also sets the previously visited URI
Code:
$this->config->load('app_config');
$this->view->set('title_prefix', $this->config->item('title_prefix'));

$this->session->set_userdata('last_uri', $this->uri->uri_string());

Would I use a hook?
#2

[eluser]deviant[/eluser]
You could extend the Controller class and stick it in the constructor.
#3

[eluser]Jim OHalloran[/eluser]
A hook should work for this, as would extending the controller class.

Jim.
#4

[eluser]eedfwChris[/eluser]
Hrm... I haven't done either of these. Could you guys refer me to some examples?
#5

[eluser]eedfwChris[/eluser]
[quote author="deviant" date="1185543519"]You could extend the Controller class and stick it in the constructor.[/quote]
All I am finding is how to extend a library in the user guide... Could someone lend me a hand?
#6

[eluser]Colin Williams[/eluser]
Ha! I just logged in to say how great hooks are for running code on all page loads (in ANY controller.. so just extending the base Controller class for one controller doesn't cut it, neither does "hacking core").

I just wrote a hook that runs post_controller_constructor. Its function is to build the site's navigation menu. It classes all menu items that link to the current page as "active" so they can be styled with CSS. A rendered UL is then loaded as a global var (with $this->load->vars()) and becomes one simple variable to print out in my main template.

I don't know another elegant way to achieve this without a hook (accepting running the code in every controller's constructor). I'm finding them more and more useful for staying DRY.

Just follow the steps in the user guide, Athfar.
#7

[eluser]eedfwChris[/eluser]
Here's a tricky question...

If I have a class called Settings() and I want one function to be called pre_controller and another to be called post_controller_constructor will CI load the class twice?
#8

[eluser]deviant[/eluser]
From looking at the Hooks library it looks like it will load the class twice.




Theme © iAndrew 2016 - Forum software by © MyBB