plack / Plack

PSGI toolkit and server adapters
http://plackperl.org/
Other
486 stars 214 forks source link

[question] Why does the call() method in a component not return a PSGI application by itself? #687

Closed XSven closed 1 year ago

XSven commented 1 year ago

The description to_app states

... You should not ever need to override this method; ...

I have the feeling I should always override this method with

sub to_app {
    my $self = shift;
    $self->prepare_app;
    $self->call;
}

because I am able to use a different style of call() method

sub call {
    my ($self) = @_;

    sub {
      # Use $self
      my ($env) = @_;
      # Do something with $env

      my $res = ...; # create a response ...

      # return the response
      return $res;
  };
}

that closes over $self! What is disadvantage of this approach?

miyagawa commented 1 year ago

that closes over $self!

sub call {
    my ($self) = @_;

    sub {
      # Use $self
      my ($env) = @_;
      # Do something with $env

You don't need to override to_app to do this. The entire thing can be written as:

sub call {
    my($self, $env) = @_;
    # Use $self, and do something with $env
    my $res = ...;
}

You don't need to close over $self because it's an object method.

Of course whatever you're doing is valid as long as to_app returns a PSGI code ref, but you don't have to use the name call - in fact that'd be just as confusing since it's not following the signature of the call method in Plack::Component.