Search code examples
oopsoapcontrollerwsdllaravel-5.1

How to call a function within the same controller?


I have to call a soap service using laravel and done so correctly. This soap service requires me to send a login request prior to sending any other request.

The code I'm using works, but I want to improve by removing the login from all the functions and creating one function. I tried changing the following for one function:

public function getcard($cardid)
{
SoapWrapper::add(function ($service) {
   $service
   ->name('IS')
   ->wsdl(app_path().'\giftcard.wsdl')
   ->trace(true);
 });
$data = [
     'UserName' => 'xxxx',
     'Password'   => 'xxxx',
    ];
$card = [
     'CardId' => $cardid,
     ];
SoapWrapper::service('IS', function ($service) use ($data,$card) {
$service->call('Login', [$data]);
$cardinfo=$service->call('GetCard', [$card]);
dd($cardinfo->Card);
});
}

Into:

public function login()
{
SoapWrapper::add(function ($service) {
    $service
    ->name('IS')
    ->wsdl(app_path().'\giftcard.wsdl')
    ->trace(true);
});
$data = [
     'UserName' => 'xxxx',
     'Password'   => 'xxxx',
    ];
SoapWrapper::service('IS', function ($service) use ($data) {
return $service->call('Login', [$data]);
//$service->call('Login', [$data]);
//return $service;
});
}

public function getcard($cardid)
{
$this->login();
$card = [
     'CardId' => $cardid,
    ];
$cardinfo=$service->call('GetCard', [$card]);
dd($card);
}

But this doesn't work. I also tried it with the commented out part, but that doesn't work. Both options result in an error that it didn't find 'service'. I know it has something to do with oop, but don't know any other option.

I took this as an example, but I probably implemented it wrong?

So my question is: How do I reuse the login part for all other functions?


Solution

  • Your return statement in the login() method is within the scope of that closure. You need to return the result of the closure as well.

    return SoapWrapper::service('IS', function ($service) use ($data) {
         return $service->call('Login', [$data]);
    });
    

    EDIT: To explain a little bit. You have a function:

    SoapWrapper::service('IS' ,function() {}

    Inside of a function : public function login()

    If you need to return data from your login() method, and that data is contained within your SoapWrapper::service() method, then both methods need a return statement