Générateur de liens hypermédia PSR-13

VérifiéSûr

Génère des implémentations de liens hypermédia PSR-13 pour PHP 8.4, avec Link, EvolvableLink et LinkProvider, incluant des tests unitaires pour les API HATEOAS.

Spar Skills Guide Bot
DeveloppementIntermédiaire
25/08/2026
Claude CodeCursorWindsurfCopilotCodex
#php#psr-13#hateoas#code-generation#phpunit

Recommandé pour

Synthèse automatique

Génère une implémentation PHP 8.4 conforme à PSR-13 (Link, EvolvableLink, LinkProvider) avec tests PHPUnit pour des API REST HATEOAS.

Points forts

  • Fournit des classes `final readonly` immuables avec les méthodes `with*`/`without*` de PSR-13 déjà câblées
  • Détecte automatiquement les URI templates via la présence d'accolades dans le href
  • Le LinkProvider expose `getLinksByRel()` sous forme de générateur, pratique pour filtrer par relation
  • Place les fichiers et les tests dans une arborescence explicite (src/Infrastructure/Http/Link, tests/Unit/...)

Limites

  • Les templates supposent un namespace et une arborescence de type App/src, à adapter pour Symfony, Laravel ou une autre structure
  • Le template de ressource avec liens est tronqué et l'installation de la dépendance psr/link n'est pas abordée
  • Les tests unitaires sont annoncés mais aucun code de test n'est fourni
  • N'aborde pas l'intégration réelle dans les réponses HTTP (sérialisation, en-têtes Link)
Quand l'utiliser

À utiliser lorsqu'on démarre une API REST PHP devant exposer des liens hypermedia PSR-13 et que l'on veut un squelette conforme sans l'écrire à la main.

Quand l'éviter

À éviter si le projet n'utilise pas PSR-13 ou si l'on attend un générateur qui couvre aussi la sérialisation HTTP et les tests complets.

Analyse de sécurité

Sûr
Score qualité88/100

The skill only provides PHP code templates and instructions for generating PSR-13 hypermedia link implementations. It does not declare or use any tools, execute commands, or handle secrets. No destructive or exfiltrating actions are present.

Aucun point d'attention détecté

Comment cette analyse est faite

Exemples

Scaffold PSR-13 link classes
Create a PSR-13 hypermedia link implementation for my PHP 8.4 REST API: the Link, LinkProvider classes and their unit tests.
Add HATEOAS to a resource
Generate a PSR-13 LinkProvider with rels like self, next and edit, then show how to attach it to my User API resource.
Templated links
Using PSR-13, build an evolvable Link for a URI template like /users/{id} and add a unit test checking isTemplated() returns true.

name: create-psr13-link description: Generates PSR-13 Hypermedia Links implementation for PHP 8.4. Creates LinkInterface, EvolvableLinkInterface, and LinkProviderInterface for HATEOAS support. Includes unit tests. metadata: author: dykyi-roman

PSR-13 Hypermedia Links Generator

Overview

Generates PSR-13 compliant hypermedia link implementations for HATEOAS REST APIs.

When to Use

  • Building REST APIs with HATEOAS
  • Creating hypermedia-driven resources
  • Link relation management
  • URI templates

Generated Components

| Component | Description | Location | |-----------|-------------|----------| | Link | LinkInterface impl | src/Infrastructure/Http/Link/ | | LinkProvider | Provider impl | src/Infrastructure/Http/Link/ | | Unit Tests | PHPUnit tests | tests/Unit/Infrastructure/Http/Link/ |

Template: Link

<?php

declare(strict_types=1);

namespace App\Infrastructure\Http\Link;

use Psr\Link\EvolvableLinkInterface;
use Stringable;

final readonly class Link implements EvolvableLinkInterface
{
    /** @param string[] $rels */
    public function __construct(
        private string $href,
        private array $rels = [],
        private array $attributes = [],
        private bool $templated = false,
    ) {
    }

    public function getHref(): string
    {
        return $this->href;
    }

    public function isTemplated(): bool
    {
        return $this->templated || str_contains($this->href, '{');
    }

    public function getRels(): array
    {
        return $this->rels;
    }

    public function getAttributes(): array
    {
        return $this->attributes;
    }

    public function withHref(string|Stringable $href): static
    {
        return new self((string) $href, $this->rels, $this->attributes, $this->templated);
    }

    public function withRel(string $rel): static
    {
        $rels = [...$this->rels, $rel];

        return new self($this->href, array_unique($rels), $this->attributes, $this->templated);
    }

    public function withoutRel(string $rel): static
    {
        $rels = array_filter($this->rels, fn($r) => $r !== $rel);

        return new self($this->href, array_values($rels), $this->attributes, $this->templated);
    }

    public function withAttribute(string $attribute, string|Stringable $value): static
    {
        $attributes = $this->attributes;
        $attributes[$attribute] = (string) $value;

        return new self($this->href, $this->rels, $attributes, $this->templated);
    }

    public function withoutAttribute(string $attribute): static
    {
        $attributes = $this->attributes;
        unset($attributes[$attribute]);

        return new self($this->href, $this->rels, $attributes, $this->templated);
    }
}

Template: Link Provider

<?php

declare(strict_types=1);

namespace App\Infrastructure\Http\Link;

use Psr\Link\EvolvableLinkProviderInterface;
use Psr\Link\LinkInterface;

final readonly class LinkProvider implements EvolvableLinkProviderInterface
{
    /** @param LinkInterface[] $links */
    public function __construct(
        private array $links = [],
    ) {
    }

    public function getLinks(): iterable
    {
        return $this->links;
    }

    public function getLinksByRel(string $rel): iterable
    {
        foreach ($this->links as $link) {
            if (in_array($rel, $link->getRels(), true)) {
                yield $link;
            }
        }
    }

    public function withLink(LinkInterface $link): static
    {
        return new self([...$this->links, $link]);
    }

    public function withoutLink(LinkInterface $link): static
    {
        $links = array_filter(
            $this->links,
            fn($l) => $l !== $link,
        );

        return new self(array_values($links));
    }
}

Template: Resource with Links

<?php

declare(strict_types=1);

namespace App\Presentation\Api\Resource;

use App\Domain\User\Entity\User;
use App\Infrastructure\Http\Link\Link;
use App\Infrastructure\Http\Link\LinkProvider;
use Psr\Link\LinkProviderInterface;

final readonly class UserResource implements LinkProviderInterface
{
    private LinkProvider $linkProvider;

    public function __construct(
        public string $id,
        public string $email,
        public string $name,
    ) {
        $this->linkProvider = new LinkProvider([
            (new Link("/api/users/{$this->id}"))->withRel('self'),
            (new Link("/api/users/{$this->id}/posts"))->withRel('posts'),
            (new Link('/api/users'))->withRel('collection'),
        ]);
    }

    public static function fromEntity(User $user): self
    {
        return new self(
            $user->getId()->toString(),
            $user->getEmail()->toString(),
            $user->getName(),
        );
    }

    public function getLinks(): iterable
    {
        return $this->linkProvider->getLinks();
    }

    public function getLinksByRel(string $rel): iterable
    {
        return $this->linkProvider->getLinksByRel($rel);
    }

    public function toArray(): array
    {
        $data = [
            'id' => $this->id,
            'email' => $this->email,
            'name' => $this->name,
            '_links' => [],
        ];

        foreach ($this->getLinks() as $link) {
            foreach ($link->getRels() as $rel) {
                $data['_links'][$rel] = [
                    'href' => $link->getHref(),
                    'templated' => $link->isTemplated(),
                ];
            }
        }

        return $data;
    }
}

Usage Example

<?php

use App\Infrastructure\Http\Link\Link;
use App\Infrastructure\Http\Link\LinkProvider;

// Create links
$selfLink = (new Link('/api/users/123'))
    ->withRel('self')
    ->withAttribute('title', 'User Profile');

$collectionLink = (new Link('/api/users'))
    ->withRel('collection');

$templateLink = (new Link('/api/users/{id}'))
    ->withRel('user');

// Create provider
$provider = (new LinkProvider())
    ->withLink($selfLink)
    ->withLink($collectionLink)
    ->withLink($templateLink);

// Get links by relation
foreach ($provider->getLinksByRel('self') as $link) {
    echo $link->getHref(); // /api/users/123
}

Requirements

{
    "require": {
        "psr/link": "^2.0"
    }
}

Converted and distributed by TomeVault — claim your Tome and manage your conversions.

<!-- tomevault:4.0:skill_md:2026-04-11 -->

Du fichier au premier essai

Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.

Consulter la source et ses fichiers annexes

Ce téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.

1. Télécharger le fichier

Télécharger SKILL.md

Depuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/psr-13-hypermedia-links-generator-mt87688k/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.

Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.

mkdir -p '.skill-downloads/psr-13-hypermedia-links-generator-mt87688k' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/psr-13-hypermedia-links-generator-mt87688k/download' --output '.skill-downloads/psr-13-hypermedia-links-generator-mt87688k/SKILL.md.part' && mv '.skill-downloads/psr-13-hypermedia-links-generator-mt87688k/SKILL.md.part' '.skill-downloads/psr-13-hypermedia-links-generator-mt87688k/SKILL.md'

2. Vérifier les prérequis

Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.

Extrait original : Requirements
{
    "require": {
        "psr/link": "^2.0"
    }
}

Converted and distributed by TomeVault — claim your Tome and manage your conversions.

<!-- tomevault:4.0:skill_md:2026-04-11 -->

Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.

3. Charger la skill

Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.

Claude Code
test -f '.skill-downloads/psr-13-hypermedia-links-generator-mt87688k/SKILL.md' && test -s '.skill-downloads/psr-13-hypermedia-links-generator-mt87688k/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/create-psr13-link' && cp -R '.skill-downloads/psr-13-hypermedia-links-generator-mt87688k' '.claude/skills/create-psr13-link'

Cursor
test -f '.skill-downloads/psr-13-hypermedia-links-generator-mt87688k/SKILL.md' && test -s '.skill-downloads/psr-13-hypermedia-links-generator-mt87688k/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/create-psr13-link' && cp -R '.skill-downloads/psr-13-hypermedia-links-generator-mt87688k' '.cursor/skills/create-psr13-link'

Codex
test -f '.skill-downloads/psr-13-hypermedia-links-generator-mt87688k/SKILL.md' && test -s '.skill-downloads/psr-13-hypermedia-links-generator-mt87688k/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/create-psr13-link' && cp -R '.skill-downloads/psr-13-hypermedia-links-generator-mt87688k' '.agents/skills/create-psr13-link'

OpenSkills

OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.

Installation officielle d’OpenSkills
openskills install './.skill-downloads/psr-13-hypermedia-links-generator-mt87688k'

openskills read 'psr-13-hypermedia-links-generator-mt87688k'

La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.

Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.

openskills sync

Mode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.

4. Faire un premier essai

Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :

Lis .skill-downloads/psr-13-hypermedia-links-generator-mt87688k/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.

Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.

Skills similaires