Search code examples
phplaravelsoaptraitsreusability

Reusable code soap client laravel


I have different functions that use the same soap client in laravel: The duplicate code for the soapclient in these functions seems wrong. I tried with a trait file but I don't seem to get it working that way.

 public function getStaff()
    {
        // INITIALISEER DE SOAP CLIENT
        $webservicesPwd = "apipwd";      
        $soap = new SoapClient('https://apiserver.com');

        // HAAL STUDENTEN OP VIA API CALL
        $result = $soap->apiFunction($webservicesPwd,2,1);

        // INDIEN RESULTAAT NIET CORRECT
        if(is_int($result)) {

           throw new \Exception($errorMessage);
        }

And

public function getStudents()
    {
          // INITIALISEER DE SOAP CLIENT
        $webservicesPwd = "apipwd";      
        $soap = new SoapClient('https://apiserver.com');

        // HAAL STUDENTEN OP VIA API CALL     
        $result = $this->soap-someOtherApiFunction($this->webservicesPwd,3,1);

        // INDIEN RESULTAAT NIET CORRECT
      if(is_int($result)) {

           throw new \Exception($errorMessage);
        }


        dd($result);
    }

Solution

  • Create a new class:

    class ApiNameClient {
        protected $soapClient;
    
        protected $webservicesPwd;
    
        public function __construct() {
        // initialize $soapClient and $webservicesPwd here
        }
    
        public function getStudents() {
            $result = $this->soapClient->myFirstAction($this->webservicesPwd,3,1);
    
            return $this->defendInteger($result);
        }
    
        protected function defendInteger($value) {
            if(is_int($value)) {
                throw new \Exception($errorMessage);
            }
            return $value;
        }
    }