PHP code example of atournayre / link-collection-component

1. Go to this page and download the library: Download atournayre/link-collection-component library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

atournayre / link-collection-component example snippets




namespace App\Generator;

use Exception;
use Atournayre\Component\LinkCollection;
use Symfony\Component\WebLink\Link;

class LinkCollectionGenerator
{
    /**
     * @throws Exception
     */
    public function __invoke(): LinkCollection
    {
        // Create links always available.
        $links = [
            (new Link())
                ->withHref('#')
                ->withAttribute('title', 'Anchor'),
            (new Link())
                ->withHref('https://google.com')
                ->withAttribute('title', 'Google'),
        ];

        $collection = new LinkCollection($links);

        // Add link conditionally to collection using a callback
        $collection->add(
            (new Link())
                ->withHref('https://bing.com')
                ->withAttribute('title', 'Bing'),
            fn () => false
        );

        // Add link conditionally to collection using a callback
        $collection->add(
            (new Link())
                ->withHref('https://yahoo.com')
                ->withAttribute('title', 'Yahoo')
                ->withAttribute('aria-expanded', true),
            fn () => true
        );

        return $collection;
    }
}



namespace App\Controller;

use Atournayre\Component\LinkCollection\Converter\HtmlConverter;
use Atournayre\Component\LinkCollection\Converter\JsonConverter;
use App\Generator\LinkCollectionGenerator;

class ExampleController extends AbstractController
{
    public function __invoke(
         LinkCollectionGenerator $linkCollectionGenerator,
    ): Response
    {
        return $this->render('index.html.twig', [
            // Get raw collection of Symfony\Component\WebLink\Link.
            'links' => $linkCollectionGenerator(),
            // Convert link collection to html.
            'htmlLinks' => HtmlConverter::getLinks($linkCollectionGenerator()),
            // Convert link collection to json.
            'jsonLinks' => JsonConverter::getLinks($linkCollectionGenerator()),
        ]);
    }
}