saloonphp / saloon

🤠 Build beautiful API integrations and SDKs with Saloon
https://docs.saloon.dev
MIT License
2.09k stars 107 forks source link

Feature | Add HasEndpointPlaceholders trait for Request endpoints syntax sugar #381

Closed onlime closed 5 months ago

onlime commented 8 months ago

This adds a new HasEndpointPlaceholders trait which can be (optionally) used on any Saloon Request as syntax sugar. So instead of overriding resolveEndpoint() like so:

class GetUser extends Request
{
    protected Method $method = Method::GET;

    public function __construct(protected int $id) {}

    public function resolveEndpoint(): string
    {
        return "/user/{$this->id}";
    }

... you could use:

class GetUser extends Request
{
    use HasEndpointPlaceholders;

    protected Method $method = Method::GET;

    protected string $endpoint = '/user/{id}';

    public function __construct(protected int $id) {}

This especially makes sense when you use some custom AbstractRequest that extends from Saloon\Http\Request, so you would only need to use HasEndpointPlaceholders once. It also makes sense if you have a lot of different constructor params – the HasEndpointPlaceholders will pick the ones found in your $endpoint template by reflection, supporting int, string, bool, or enum types.

I use this in like 80% of my integrations/requests and it saved me tons of lines, also greatly increased readability.

Cheers, Pipo

Sammyjo20 commented 8 months ago

Hey @onlime I'm very sorry for not replying to this PR sooner - when I get a chance over the next day or two I will review this properly - from the outset I do quite like this idea!

Sammyjo20 commented 5 months ago

Hey @onlime thank you for the wait, unfortunately I want to try and keep Saloon as minimal as possible and offering multiple ways to set the endpoint isn't something I am looking to have in the core codebase, sorry. I would recommend having a trait like this in your application and using it on your requests or maybe even offering a "Saloon Tools" library of your own that you can provide these extra features, if they become popular features among the community I will definitely reconsider a PR for it.