PHP code example of tenqz / shortify

1. Go to this page and download the library: Download tenqz/shortify 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/ */

    

tenqz / shortify example snippets




use Tenqz\Shortify\Shortify;
use Tenqz\Shortify\Infrastructure\Repository\UrlRepositoryInterface;

// 1. Create your implementation of UrlRepositoryInterface
class YourRepository implements UrlRepositoryInterface
{
    // Implement save, findByCode, exists methods
}

// 2. Create a Shortify instance with your repository
$repository = new YourRepository();
$shortify = new Shortify($repository);

// 3. Shorten a URL
try {
    $url = $shortify->shorten('https://example.com/very-long-url');
    echo "Short code: " . $url->getShortCode(); // For example "xB4p2q"
} catch (\Tenqz\Shortify\Exceptions\InvalidUrlException $e) {
    echo "Error: " . $e->getMessage();
}

// 4. Get the original URL from the code
try {
    $originalUrl = $shortify->expand('xB4p2q');
    echo "Original URL: " . $originalUrl;
} catch (\Tenqz\Shortify\Exceptions\UrlNotFoundException $e) {
    echo "Error: " . $e->getMessage();
}



use Tenqz\Shortify\Infrastructure\Repository\UrlRepositoryInterface;
use Tenqz\Shortify\Core\Url;

class InMemoryUrlRepository implements UrlRepositoryInterface
{
    private array $urls = [];

    public function save(Url $url): void
    {
        $code = $url->getShortCode();
        if ($code !== null) {
            $this->urls[$code] = $url;
        }
    }

    public function findByCode(string $code): ?Url
    {
        return $this->urls[$code] ?? null;
    }

    public function exists(string $code): bool
    {
        return isset($this->urls[$code]);
    }
}