ThomasReggi
ThomasReggi

Reputation: 59355

Create function that accepts function

I have a function that runs some fairly generic code that does a lot of work connection to a database and setting up different configuration variables. I have within a couple of if statements of this top-level function code that I run that is actually different from function to function.

This is how it looks now.

function get_users(){
  // config
  // set application keys
  // connect to database
  // retrieve user data
  // authentication to foreign api
  if(something){
    // some more red-tape
    if(something){
      //more more
      if(something){
        /* finally the good stuff */

        // the code here varies from function to function
        // eg. get users
        // probably will run: inner_get_users();

      }
    }
  }
}

function get_data(){
  // config
  // set application keys
  // connect to database
  // retrieve user data
  // authentication to foreign api
  if(something){
    // some more red-tape
    if(something){
      //more more
      if(something){
        /* finally the good stuff */

        // the code here varies from function to function
        // eg. get data
        // probably will run: inner_get_data();

      }
    }
  }
}

How I want it to work, perhaps using anonymous functions:

function instance($inner){
  // config
  // set application keys
  // connect to database
  // retrieve user data
  // authentication to foreign api
  if(something){
    // some more red-tape
    if(something){
      //more more
      if(something){
        /* finally the good stuff */

        Call inner

      }
    }
  }
}

function get_data(){

  instance(function(
    // get the data
  ));

}

or maybe

function get_users(){

  $var = function(
    // get the users
  );

  instance($var);

}

I'm looking for better, dryer, and more maintainable code.

Upvotes: 2

Views: 97

Answers (1)

Emil Vikström
Emil Vikström

Reputation: 91932

This is something which PHP calls variable functions. This works both when $inner is the string name of a function and when it's an anonymous function (although the manual page for variable functions doesn't explain that).

function instance($inner){
  // config
  // set application keys
  // connect to database
  // retrieve user data
  // authentication to foreign api
  if(something){
    // some more red-tape
    if(something){
      //more more
      if(something){
        /* finally the good stuff */

        return $inner();

      }
    }
  }
}

Upvotes: 1

Related Questions