2011-11-28 95 views
3

我有很多方法需要測試遠程服務器是否已經到達,如果沒有,達到它。在另一個之前調用方法

我的第一個想法是__call魔術方法,但該方法被調用只有當真正的方法(與原來的名稱)沒有提出

<?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; 
} 

?> 

我真的需要在每種方法中都有一堆if,或者有一種方法可以做得更好嗎?

回答

2

什麼改變了你這樣的代碼:

<?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; 
} 

?> 
+0

是的,它是合法的:'$ this - > {'_'。$ funtionName}()' – webbiedave

+0

謝謝,重新加入。 – sberry

0

在我看來像你這個過於複雜。 (假設我理解你的問題。)

爲什麼不在遠程服務器上設置一個標誌的功能呢?

爲什麼你需要檢查每個連接階段?爲什麼他們分開了舞臺呢?難道他們都沒有按照特定的順序一起工作,也從來沒有從任何其他的代碼中工作?沒有任何理由讓它們成爲單獨的功能。 (除非你的代碼更多,我不知道)

1

我不知道你在做什麼......但如果你想攔截每一個方法調用。

class ObjectProxy { 
    protected $obj; 
    function __construct($obj) { 
     $this->obj = $obj; 
    } 
    function __call($methodName, $arguments) { 
     //do stuff 
     return call_user_func_array($methodName, $this->obj, $arguments); 
    } 
} 

$proxied = new ObjectProxy(new OrigionalType()); 
$proxied->getBody(); 

您可能想要實現更多的魔術方法,以使其適用於多個實例方法調用,但您明白了。這不是所有情況下的解決方案,但有時可能非常方便。

相關問題