返回必须通过某些功能

时间:2015-11-27 08:36:07

标签: php

我有一个班有几种方法。我希望以这样的方式限制代码,即只要有任何方法return,就必须通过sendResponse()方法完成。不允许直接退货。

是否有任何模式或技巧可以实现这一目标?

由于

class Foo {

function a(){
 ...
 $response = ...;
 return $this->sendResponse($response);
}

function b(){
 ...
 $response = ...;
 return $this->sendResponse($response);
}

function c(){
 ...
 $response = ...;
 return $response // This should not be allowed
}

function sendResponse($response){
  // do something with $response
  return $response;
}

}

1 个答案:

答案 0 :(得分:1)

您可以使用__call魔术方法。如果使用此方法,则必须确保方法已有详细记录,因为其他程序员可能认为不能使用这些方法,因为它们受保护/私有。

class Foo {

    protected $notAllowedMethods = array('sendResponse');

    public function __call($method, $args)
    {
        if (in_array($method, $this->notAllowedMethods)) {
            throw new BadMethodCallException('This method cannot be called directly.');
        }

        $response = call_user_func_array(array($this, $method), $args);

        if (!is_array($response)
            || !isset($response['sendResponseUsed'])
            || !$response['sendResponseUsed']
        ) {
            $response = $this->sendResponse($response);
        }

        return $response['response'];
    }

    protected function a()
    {

       echo 'a' . PHP_EOL;
       return $this->sendResponse('test');
    }

    protected function b()
    {

       echo 'b' . PHP_EOL;
       return $this->sendResponse('test');
    }

    protected function c()
    {

       echo 'c' . PHP_EOL;
       return 'test';
    }

    protected function sendResponse($response)
    {
        echo 'sendResponse' . PHP_EOL;
        // do something with $response
        return array(
            'sendResponseUsed' => true,
            'response' => $response
        );
    }

}

$foo = new Foo;

$foo->a();
$foo->b();
$foo->c();