PHP Soap Server How to know called method

Guile picture Guile · May 22, 2012 · Viewed 9k times · Source

In PHP I would like to know what will be the method called by SOAP. Here is a sample to understand...

$soapserver = new SoapServer();
$soapserver->setClass('myClass');
$soapserver->handle();

What I would like to know is the name of the method that will be executed in handle()

Thank you !!

Answer

zafarkhaja picture zafarkhaja · May 23, 2012

In my opinion, the cleanest and most elegant way to access the called operation's name in this situation would be using some kind of Wrapper or Surrogate design pattern. Depending on Your intent You would use either the Decorator or the Proxy.

As an example, let's say We want to dynamically add some additional functionality to our Handler object without touching the class itself. This allows for keeping the Handler class cleaner and, thus, more focused on its direct responsibility. Such functionality could be logging of methods and their parameters or implementing some kind of caching mechanism. For this We will use the Decorator design pattern. Instead of doing this:

class MyHandlerClass
{
    public function operation1($params)
    {
        // does some stuff here
    }

    public function operation2($params)
    {
        // does some other stuff here
    }
}

$soapserver = new SoapServer(null, array('uri' => "http://test-uri/"));
$soapserver->setClass('MyHandlerClass');
$soapserver->handle();

We'll do the following:

class MyHandlerClassDecorator
{
    private $decorated = null;

    public function __construct(MyHandlerClass $decorated)
    {
        $this->decorated = $decorated;
    }

    public function __call($method, $params)
    {
        // do something with the $method and $params

        // then call the real $method
        if (method_exists($this->decorated, $method)) {
            return call_user_func_array(
                array($this->decorated, $method), $params);
        } else {
            throw new BadMethodCallException();
        }
    }
}

$soapserver = new SoapServer(null, array('uri' => "http://test-uri/"));
$soapserver->setObject(new MyHandlerClassDecorator(new MyHandlerClass()));
$soapserver->handle();

If You want to control the access to the Handler's operations, for instance, in order to impose access rights use the Proxy design pattern.