• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Hooks on controller methods

#1
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

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
Reply


Messages In This Thread
Hooks on controller methods - by milengardev1994 - 10-11-2019, 02:06 PM
RE: Hooks on controller methods - by InsiteFX - 10-12-2019, 04:10 AM
RE: Hooks on controller methods - by InsiteFX - 10-12-2019, 11:33 AM
RE: Hooks on controller methods - by dave friend - 10-12-2019, 01:27 PM

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


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