Skip to content

Action Responder binding

Michał Golon edited this page Jul 27, 2018 · 4 revisions

An Action and a responder are two connected pieces. To bind those two together, simple auto-resolving mechanism was introduced.

Auto-resolving

As mentioned, any action class should return either responder or response (ideally produced by a responder). To simplify responder instantiation, responder helper method as well as static ResponderFactory::create() methods were added.

Both methods use simple auto-resolving mechanism.

The package adds two default responder's class name resolvers:

  • first is based on action's class property $responderClass,
  • second is based on action's class name.

During responder auto-resolving, responder's class name is guessed based on corresponding action's class. First, action class is scanned for $responderClass property. If action class does not have that property or its value is null, then second resolver is called - action's class name is transformed into responder's class name (using configuration). Having responder's class name, its instance is created.

Important

When using responder helper or ResponderFactory factory, make sure that Request instance is the first argument in responder's construct() method.

use Illuminate\Http\Request;

class MyAwesomeActionResponder
{
    public __construct(Request $request, $data // and other arguments, i.e. status code, additional headers, etc.)
    {
        // do stuff here
    }
}

Extensions

If the default responder's class name resolvers don't suit developer's need, there is a possibility to add new resolvers.

It is possible by calling ResponderResolver::extend() method in any of your application service providers:

// extenstion via invokable class
ResponderResolver::extend(new MyCustomResponderResolver());

class MyCustomResponderResolver
{
    public function __invoke(string $actionClassName)
    {
        // my custom resolver content here
    }
}

// or extension via callback

ResponderResolver::extend(function(string $actionClassName) {
    // my custom resolver content here
});

Resolvers are run in the reverse order as they were added.

Clone this wiki locally