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

Zend Server Laravel Package

zendframework/zend-server

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require zendframework/zend-server
    

    (Note: Package is archived; use laminas/laminas-server for active maintenance.)

  2. Basic JSON Server Example:

    use Zend\Json\Server;
    
    $server = new Server();
    $server->setClass('My\ServiceClass');
    $server->handle();
    
  3. Basic XML-RPC Server Example:

    use Zend\XmlRpc\Server;
    
    $server = new Server();
    $server->setClass('My\ServiceClass');
    $server->handle();
    

First Use Case: Exposing a Service Class

Define a service class with public methods:

class MyService {
    public function add($a, $b) { return $a + $b; }
    public function greet($name) { return "Hello, $name"; }
}

Configure the server to use this class:

$server = new \Zend\Json\Server();
$server->setClass('MyService');
$server->handle();

Access via HTTP POST to / with JSON payload:

{"method":"add","params":[5,3]}

Implementation Patterns

1. Service Class Design

  • Public Methods Only: Only public methods are exposed.

  • Type Hints: Leverage Zend\Server\Reflection for parameter/return type inspection.

    $reflection = \Zend\Server\Reflection::reflectClass(MyService::class);
    $prototypes = $reflection->getMethod('add')->getPrototypes();
    
  • Namespacing: Explicitly set namespaces for API documentation:

    $reflection->setNamespace('MyAPI');
    

2. Request Handling Workflow

  • Middleware Integration: Use Laravel middleware to pre-process requests before handing to Zend\Server:

    // app/Http/Middleware/JsonServerMiddleware.php
    public function handle($request, Closure $next) {
        if ($request->isJson() && $request->method() === 'POST') {
            $server = new \Zend\Json\Server();
            $server->setClass('MyService');
            return $server->handle();
        }
        return $next($request);
    }
    
  • Routing: Bind to a specific route in routes/web.php:

    Route::post('/api', function () {
        $server = new \Zend\Json\Server();
        $server->setClass('MyService');
        return $server->handle();
    });
    

3. Dynamic Function Loading

Load functions dynamically at runtime:

$server = new \Zend\Json\Server();
$server->loadFunctions([
    'multiply' => [$this, 'multiply'],
    'divide'   => [$this, 'divide']
]);

4. Error Handling

Customize error responses:

$server->setErrorHandler(function ($exception) {
    return response()->json([
        'error' => $exception->getMessage(),
        'code'  => $exception->getCode()
    ], 500);
});

5. Authentication

Integrate Laravel Auth:

$server->setAuthAdapter(function ($request) {
    $token = $request->header('Authorization');
    return Auth::validate($token);
});

Gotchas and Tips

Pitfalls

  1. Archived Package:

    • The package is no longer maintained. Use laminas/laminas-server for new projects.
    • Bug fixes or updates may require forking.
  2. Reflection Limitations:

    • Zend\Server\Reflection may not fully support PHP 7.4+ features (e.g., union types, named arguments).
    • Test reflection output thoroughly for edge cases.
  3. Security:

    • Expose only trusted methods to avoid remote code execution risks.
    • Validate all input parameters in service methods.
  4. Performance:

    • Reflection is expensive. Cache reflection data if methods are static:
      static $reflection = null;
      if (!$reflection) {
          $reflection = \Zend\Server\Reflection::reflectClass(MyService::class);
      }
      
  5. Laravel-Specific Quirks:

    • Request Wrapping: Zend\Server expects raw input. Use Laravel's Request object carefully:
      $rawInput = file_get_contents('php://input');
      $server->setRawData($rawInput);
      

Debugging Tips

  1. Enable Verbose Logging:

    $server->setLogger(new \Zend\Log\Logger());
    $logger->addWriter(new \Zend\Log\Writer\Stream('php://stderr'));
    
  2. Inspect Prototypes: Dump method prototypes to debug API exposure:

    $method = \Zend\Server\Reflection::reflectMethod(MyService::class, 'add');
    dump($method->getPrototypes());
    
  3. Test with curl: Simulate requests for debugging:

    curl -X POST http://localhost/api \
      -H "Content-Type: application/json" \
      -d '{"method":"add","params":[1,2]}'
    

Extension Points

  1. Custom Reflection: Extend Zend\Server\Reflection\Class or Function for custom metadata:

    class CustomReflection extends \Zend\Server\Reflection\Class {
        public function getCustomMetadata() { ... }
    }
    
  2. Protocol-Specific Handlers: Override handle() for custom logic (e.g., CORS headers):

    $server = new \Zend\Json\Server();
    $server->handle(); // Extend this method
    
  3. Laravel Service Providers: Bootstrap the server in a provider:

    public function register() {
        $this->app->singleton('zend.server', function () {
            $server = new \Zend\Json\Server();
            $server->setClass('MyService');
            return $server;
        });
    }
    

Laravel Integration Tips

  1. Service Container Binding: Bind the server to Laravel’s container for dependency injection:

    $this->app->bind('zend.server', function () {
        $server = new \Zend\Json\Server();
        $server->setClass($this->app->make('MyService'));
        return $server;
    });
    
  2. API Resource Classes: Use Laravel’s API resources to format responses:

    $server->setResponseFormatter(function ($result) {
        return new MyServiceResource($result);
    });
    
  3. Rate Limiting: Combine with Laravel’s throttle middleware:

    Route::post('/api', function () {
        return $this->app->make('zend.server')->handle();
    })->middleware('throttle:60,1');
    
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.
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
spatie/mailcoach-vapor