Welcome Guest, Not a member yet? Register   Sign In
Hooks on controller methods
#5

(This post was last modified: 10-12-2019, 01:39 PM by dave friend.)

While it isn't a direct plug-in for your wishes, ion_auth implements an ad-hoc "hook / trigger_events" scheme that could probably be adapted. The ion_auth GitHub repo is here.

Similarly, CI v4 has an Events class that you could maybe use and adapt to CI v3.

But unless the exist() method you show is a stand-in for something a lot more complex it would not be a good candidate for a hook/event system. There is barely more code in exist() than it replaces in the other functions. In fact your version of exist

PHP Code:
private function exist($id)
{
    if ( ! $this->Example_model->exist($id)) {
        return false;
    }
    return true;


could be rewritten as

PHP Code:
private function exist($id)
{
    return $this->Example_model->exist($id));


So, baring complexity you're not showing us, there is no need for the exist() function to... pardon the pun, exist.

This code
 
PHP Code:
public function update($id)
{
    if (!$this->exist($id)) {
        return;
    }
  //Do something


should be rewritten as

PHP Code:
public function update($id)
{
    if ( ! $this->Example_model->exist($id)) {
        return;
    }
   //Do something


Any hook or event system is going to involve executing a lot more code than is shown here. Just to be clear, I'm not against some sort of hook/event system. It's just that your example isn't a good fit.

(10-12-2019, 06:01 AM)milengardev1994 Wrote: ... my problem is about repeating 'exist' on every function that 'exist' is required.

There are other solutions that don't require the overhead of the kind you are seeking.

Assuming all those methods that call exist($id) are in a controller I have to ask, Where does $id come from? Likely it was a GET or POST item - right?

Why not simply verify that the $id is valid the first time you touch it? Maybe even in the controller constructor. Once verified your other methods don't have to worry about whether it exists or not. You could also store the verified $id in a class property that other methods can access. If the property is set then other methods know the $id cleared for use.

There are other possible easy ways to make the code cleaner.
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



Theme © iAndrew 2016 - Forum software by © MyBB