Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Fxmlrpc Laravel Package

lstrojny/fxmlrpc

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require lstrojny/fxmlrpc
    

    Add to composer.json if not using autoloading:

    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Lstrojny\\XmlRpc\\": "vendor/lstrojny/fxmlrpc/src/"
        }
    }
    

    Run composer dump-autoload.

  2. First Request

    use Lstrojny\XmlRpc\Client;
    
    $client = new Client('http://example.com/xmlrpc');
    $response = $client->call('methodName', ['arg1', 'arg2']);
    
  3. Key Files to Review

    • src/Client.php (Core client logic)
    • src/Request.php (Request building)
    • src/Response.php (Response handling)
    • tests/ (Usage examples and edge cases)

First Use Case: Consuming a Simple XML-RPC API

$client = new Client('http://api.example.com/RPC2');
$result = $client->call('examples.getStateName', ['41']);
echo $result; // Outputs: "California"

Implementation Patterns

Common Workflows

1. Structured Data Handling

// Passing complex data types
$client->call('system.method', [
    'struct' => [
        'member1' => 'value1',
        'member2' => ['array', 'of', 'values'],
    ],
    'array' => [1, 2, 3],
    'int' => 42,
    'double' => 3.14,
]);

2. Authentication

$client = new Client('http://api.example.com/RPC2');
$client->setAuth('username', 'password'); // Basic Auth
// OR
$client->setHeaders(['X-API-Key' => 'your_key']);

3. Batch Requests

$client->setBatchMode(true);
$client->call('method1', ['arg1']);
$client->call('method2', ['arg2']);
$responses = $client->getBatchResponses();

4. Error Handling

try {
    $result = $client->call('methodName', ['args']);
} catch (\Lstrojny\XmlRpc\Exception\FaultException $e) {
    // Handle XML-RPC fault (e.g., -32601: Invalid method)
    echo "Fault: {$e->getFaultCode()} - {$e->getFaultString()}";
} catch (\Exception $e) {
    // Handle transport/parsing errors
    echo "Error: " . $e->getMessage();
}

5. Integration with Laravel

// Service Provider (app/Providers/AppServiceProvider.php)
public function register()
{
    $this->app->singleton('xmlrpc.client', function () {
        return new \Lstrojny\XmlRpc\Client(config('services.xmlrpc.url'));
    });
}

// Config (config/services.php)
'xmlrpc' => [
    'url' => 'http://api.example.com/RPC2',
    'timeout' => 10,
];

// Usage in Controller
$client = app('xmlrpc.client');
$data = $client->call('methodName', ['args']);

Integration Tips

Middleware for Request/Response Logging

$client = new Client('http://api.example.com/RPC2');
$client->setMiddleware(function ($request, $next) {
    \Log::debug('XML-RPC Request:', [
        'url' => $request->getUri(),
        'method' => $request->getMethod(),
        'data' => $request->getData(),
    ]);

    $response = $next($request);

    \Log::debug('XML-RPC Response:', [
        'status' => $response->getStatusCode(),
        'data' => $response->getData(),
    ]);

    return $response;
});

Retry Logic for Transient Failures

use Lstrojny\XmlRpc\Client;
use Lstrojny\XmlRpc\Exception\FaultException;

function callWithRetry(Client $client, string $method, array $args, int $retries = 3)
{
    $lastException = null;
    for ($i = 0; $i < $retries; $i++) {
        try {
            return $client->call($method, $args);
        } catch (FaultException $e) {
            $lastException = $e;
            if ($i < $retries - 1) {
                sleep(2 ** $i); // Exponential backoff
            }
        }
    }
    throw $lastException;
}

Caching Responses

use Illuminate\Support\Facades\Cache;

function cachedCall(Client $client, string $method, array $args, string $cacheKey, int $ttl = 3600)
{
    return Cache::remember($cacheKey, $ttl, function () use ($client, $method, $args) {
        return $client->call($method, $args);
    });
}

Gotchas and Tips

Pitfalls

  1. Fault Code Handling

    • XML-RPC faults use negative integers (e.g., -32601 for "Invalid method").
    • Always catch FaultException separately from other exceptions.
    • Example fault codes:
      • -32600: Invalid request
      • -32601: Method not found
      • -32602: Invalid arguments
      • -32603: Internal error
  2. Data Type Mismatches

    • The package auto-converts PHP types to XML-RPC types, but edge cases (e.g., null vs. false) can cause issues.
    • Explicitly pass null as null (not false or '') to avoid ambiguity.
  3. Large Payloads

    • XML-RPC has no built-in size limits, but some servers impose them.
    • Test with large arrays/structs and handle FaultException with -32000 (server error).
  4. UTF-8 Encoding

    • Ensure strings are UTF-8 encoded before sending. The package handles this, but custom middleware might break it.
    • Example fix:
      $client->setMiddleware(function ($request, $next) {
          $request->setData(json_encode($request->getData(), JSON_UNESCAPED_UNICODE));
          return $next($request);
      });
      
  5. SSL/TLS Issues

    • Some XML-RPC endpoints use self-signed certificates.
    • Disable SSL verification (not recommended for production):
      $client = new Client('https://insecure.example.com/RPC2');
      $client->setOptions(['ssl' => ['verify_peer' => false]]);
      

Debugging Tips

  1. Enable Verbose Logging

    $client->setDebug(true); // Logs raw request/response
    
  2. Inspect Raw Requests/Responses

    $client->setMiddleware(function ($request, $next) {
        \Log::debug('Raw Request:', $request->getRawData());
        $response = $next($request);
        \Log::debug('Raw Response:', $response->getRawData());
        return $response;
    });
    
  3. Validate XML-RPC Structure

    • Use tools like XML-RPC Validator to check payloads.
    • Example valid structure:
      <methodCall>
          <methodName>methodName</methodName>
          <params>
              <param><value><string>arg1</string></value></param>
              <param><value><int>42</int></value></param>
          </params>
      </methodCall>
      

Extension Points

  1. Custom Type Mappings

    • Extend Lstrojny\XmlRpc\Type to handle custom PHP/XML-RPC type conversions.
    • Example:
      class CustomType extends \Lstrojny\XmlRpc\Type
      {
          public static function fromXml($xml, TypeFactory $factory)
          {
              // Custom logic to parse XML into PHP
          }
      
          public function toXml()
          {
              // Custom logic to serialize PHP to XML
          }
      }
      
    • Register the type in the client:
      $client = new Client('http://api.example.com/RPC2');
      $client->getTypeFactory()->registerType('customType', CustomType::class);
      
  2. Custom Transport Layer

    • Implement Lstrojny\XmlRpc\Transport\TransportInterface for non-HTTP protocols (e.g., WebSockets).
    • Example:
      class WebSocketTransport implements TransportInterface
      {
          public
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky