Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call method before another

Tags:

php

I have bunch of methods in which i need to test whether remote server has been reached or not and if not, reach it.

My first idea was __call magic method, but the method is called only when real method (with the original name) is not presented.

<?php
public function __call( $name, $arguments ) {
    $needsExecution = array(
        'getBody', 'getHeader', 'getHeaders', 'getRawOutput',
        'getStatusCode', 'getFullHttp'
    );

    if ( in_array( $name, $needsExecution ) ) {
        if ( !$this->hasBeenExecuted() ) {
            $this->execute();
        }
    }
}

public function getBody() {
    return $this->responseBody;
}


public function getHeaders() {
    return $this->responseHeaders;
}

?>

Do I really need to have bunch of if's in each method or there's a way how to do that better?

like image 484
Radek Simko Avatar asked May 19 '26 11:05

Radek Simko


1 Answers

What about changing up your code like this:

<?php
public function __call( $name, $arguments ) {
    $needsExecution = array(
        'getBody', 'getHeader', 'getHeaders', 'getRawOutput',
        'getStatusCode', 'getFullHttp'
    );

    if ( in_array( $name, $needsExecution ) ) {
        if ( !$this->hasBeenExecuted() ) {
            $this->execute();
        } 
        return $this->{'_' . $name}();
        //return call_user_func(array($this, '_' . $name));
    }
}

protected function _getBody() {
    return $this->responseBody;
}


protected function _getHeaders() {
    return $this->responseHeaders;
}

?>
like image 116
sberry Avatar answered May 22 '26 03:05

sberry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!