phpdryrequire-once

Split PHP code of a module into separated include files


I have a block of code that I need to use in so many places of my app.

Example:

$count_device = VSE::count_device($cpe_mac);
$c_devices   = $count_device['Count_of_devices'];
$c_active    = $count_device['Count_of_active'];
$c_inactive  = $count_device['Count_of_inactive'];
$c_offline   = $count_device['Count_of_offline'];

Right now, they in are 10 of my controllers. If I need to fix anything, I need to fix in 10 places.

I'm seeking a better way to control this.


I thought of writing a function

public static function get_device_info($cpe_mac){

    $count_device = VSE::count_device($cpe_mac);
    $c_devices   = $count_device['Count_of_devices'];
    $c_active    = $count_device['Count_of_active'];
    $c_inactive  = $count_device['Count_of_inactive'];
    $c_offline   = $count_device['Count_of_offline'];

}

When I call that function: $devices = get_device_info($cpe_mac);

I only have access to 1 variable which is $devices.

I won't have access to all my 5 variables in that function.

I've found get_defined_vars, but that is not really what I am looking for.


Questions

How would one go about and implement this?

How do I move a block of code and include it back?

Should I start look into PHP's require/include?


Solution

  • I do this all the time, particularly to use the same header/footer across the site. Simply place this line in the document in which you want to require the code.

    <?php require_once('php/code_block_one.php'); ?>
    

    If you want to call the same block of code multiple times in a single page, change require_once to require.