10-11-2019, 02:06 PM
(This post was last modified: 10-12-2019, 03:00 AM by milengardev1994.)
Hello,
I have been building RESTful API using CI 3 and I have came to a situation where there is a lot of duplicated code so I was thinking if it's possible to achieve something like a hook on a function inside a controller. As far as my knowledge gets we can add hooks on the controller itself but thats on the actual initialisation and destruction. What I want is to have a hook that is triggered before a call of a function inside the controller.
Here is some example of my code
As you can see the private method 'exist' is duplicated couple of times.
I would like to make the code cleaner by extracting this functionality out of the function body so it can be re-used on multiple places.
Maybe there some other solution that are not related with Hooks and I love to hear about it.
I hope I have explained clear enough.
Regards
I have been building RESTful API using CI 3 and I have came to a situation where there is a lot of duplicated code so I was thinking if it's possible to achieve something like a hook on a function inside a controller. As far as my knowledge gets we can add hooks on the controller itself but thats on the actual initialisation and destruction. What I want is to have a hook that is triggered before a call of a function inside the controller.
Here is some example of my code
PHP Code:
public function update($id)
{
if (!$this->exist($id)) {
return;
}
//Do something
}
public function delete($id)
{
if (!$this->exist($id)) {
return;
}
//Do something
}
public function add_image($id)
{
if ( ! $this->exist($id)) {
return;
}
// Do something
}
private function exist($id)
{
if ( ! $this->Example_model->exist($id)) {
return false;
}
return true;
}
As you can see the private method 'exist' is duplicated couple of times.
I would like to make the code cleaner by extracting this functionality out of the function body so it can be re-used on multiple places.
Maybe there some other solution that are not related with Hooks and I love to hear about it.
I hope I have explained clear enough.
Regards