mardi 22 janvier 2019

Extend Laravel package with the right tool

In my App I installed this package https://github.com/guzzle/guzzle to make http/curl requests.

I then created an ExternalController to extend the functionality of Guzzle Package, like so:

namespace App\Http\Controllers;

use GuzzleHttp\Client as GuzzleHttpClient;
use GuzzleHttp\Exception\ClientException as ClientException;

class ExternalController extends Controller
{
    protected $endpoint = '';
    protected $method   = '';

    public function __construct()
    {
        $this->debug = env("APP_DEBUG", false);
    }

    /**
     * Crypts Server call
     */

    public function encodeCall($method = 'GET', $endpoint = "server_status")
    {
        $EXTERNAL_PROTOCOL         = config('myconfig.EXTERNAL_PROTOCOL');
        $EXTERNAL_IP               = config('myconfig.EXTERNAL_IP');
        $EXTERNAL_PORT             = config('myconfig.EXTERNAL_PORT');
        $EXTERNAL_MANAGEMENT_TOKEN = config('myconfig.EXTERNAL_MANAGEMENT_TOKEN');

        //Skip some parameters for security reasons

        $base64hash                = base64_encode($str2hash);

        $request_url = "${EXTERNAL_PROTOCOL}://${EXTERNAL_IP}:${EXTERNAL_PORT}/manage/${endpoint}?salt=${salt}&hash=${base64hash}";

        $requestContent = [
            'headers' => [
                'Accept'       => 'application/json',
                'Content-Type' => 'application/json',
            ],
        ];

        try {

            $client   = new GuzzleHttpClient();
            $curl     = $client->request($method, $request_url, $requestContent);
            $response = json_decode($curl->getBody());

            return response()->json($response);

        } catch (RequestException $RequestException) {

            return response()->json(['message' => (string) $ClientException]);

        }
    }

    /**
     * Returns Server Status
     * @return \Illuminate\Http\Response
     */
    public function getServerStatus()
    {
        $method   = 'GET';
        $endpoint = "server_status";

        return $this->encodeCall($method, $endpoint);
    }

}

I'm in the situation where I need to call some methods from another controller, like so:

//AnotherController.php

$server = new ExternalController;
return $server->getServerStatus();

I usually do not call a Controller within another Controller but I don't know enough Laravel to understand what is the correct tool.

I'm new to Laravel so perhaps I need to create a ServiceProvider to do this? If so what is the correct way of going about this?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire