1. Go to this page and download the library: Download youngmayor/web-service library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
namespace App\Services;
use YoungMayor\WebService\WebService;
class MyExampleService extends WebService
{
/**
* The baseUri for the service.
* This is an important method that must be implemented when extending the WebService Class
*
* @return string
*/
public function baseUri()
{
return "https://example.com";
}
public function demoAction(array $payload = [])
{
return $this->post("/demo/endpoint", [
'json' => $payload
]);
}
// ...
}
namespace App\Http\Controllers;
// ...
class DemoController extends Controller
{
public function demoMethod(Request $request, MyExampleService $myExampleService)
{
// Quickly send the request and render the response/error
return $myExampleService->demoAction()->render();
// Interact with the response
$response = $myExampleService->demoAction();
// Render the response
return $response->render();
// Get the status code
$statusCode = $response->getStatusCode();
// Get the response body
$responseBody = $response->getBody();
// You can also handle the response/error
$response->onComplete(
// ...
);
// Handle response/error
/**
* The onComplete($onSuccessCallback, $onErrorCallback) method takes two parameters
* 1. callback to execute on a successful request
* 2. callback to execute on a failed request
*
* Both callbacks receive an object which has the following methods:
* - render(): Renders the response/error to an array
* - getStatusCode(): Get the status code of the error
* - getBody(): Get the body of the response/error as an array
*
* The object passed to the onErrorCallback however has a method for retrieving the error message
* - getMessage(): Get the error message
*/
return $myExampleService->demoAction()->onComplete(function($response) {
$result = $response->render();
$body = $response->getBody();
$statusCode = $response->getStatusCode();
return [
'status' => $statusCode,
'body' => $body,
'message' => "This is a successful call"
]
// OR
return $result;
}, function ($error) {
$result = $error->render();
$body = $error->getBody();
$statusCode = $error->getStatusCode();
$message = $error->getMessage();
return [
'status' => $statusCode,
'body' => $body,
'message' => "An error occurred: $message"
]
// OR
return $result;
});
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.