aryehraber / statamic-fetch

Statamic v2 Addon — Access content directly as JSON using URL endpoints or via a simple tag.
MIT License
55 stars 8 forks source link

Make Fetch and FetchAuth available as services #50

Closed wanze closed 5 years ago

wanze commented 5 years ago

First of all, thank you for creating this Addon, it rocks! 👍

We had the need to customize the authentication by only allowing registered users to consume the Fetch API.

Note that the constructor of the Fetch class changed its signature, as we need a dependency injection for the FetchAuth class. Parameters are now injected via Fetch::setParameters(). I am not sure if you consider this a BC break. Other than that, the changes should be fully backwards compatible.

Here is an example for a custom decorated FetchAuth service:

// The decorated service
class FetchAuthDecorator extends FetchAuth
{
    private $fetchAuth;

    public function __construct(FetchAuth $fetchAuth)
    {
        $this->fetchAuth = $fetchAuth;
    }

    public function isAuth()
    {
        if (!$this->fetchAuth->isAuth()) {
            return false;
        }

        return User::loggedIn();
    }
}

// The registration in the service provider
$this->app->extend(FetchAuth::class, function ($fetchAuth) {
    return new FetchAuthDecorator($fetchAuth);
});

Cheers

aryehraber commented 5 years ago

Hi @wanze, this looks and sounds great! I'll try and properly review and test in the next week or so when I find some time. Thanks for the contribution!

aryehraber commented 5 years ago

Hey @wanze, sorry about the delay on this! Finally had a chance to have a closer look at the changes and test it locally.

I found 1 small bug but can fix that easily on my end before creating the next release. In case you're interested in what was wrong, you correctly added the new setParameters call on the Tag but not the Controller, so none of the params worked there anymore.

Thanks again for the PR, I think this was a really clean way to go about it and I learned some new things from your changes 😄