PHP code example of diezz / url-shortener

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

    

diezz / url-shortener example snippets


'UrlShortener' => [
    // Requeried. Data Provider Implementation.
    // Full class name should be provided.
    'dataProveder' => YourImplementation::class,
    // Optional. Short url hash length. By default 6
    'urlLength' => 6,
    // Optional. Whether retry if catch DuplicateKeyException
    // By default false
    'retryOnDuplicate' => false,
    //Optioanal. Base url of short url.  
    // If this param not set App.appBaseUrl will be used as baseUrl
    'baseUrl' => 'http://domain.com',
    // Optional. Short url path. By default null,
    // This value will be inserted between base url and short url hash
    // and short url will be looking like this http://domain.com/l/MnNQLC
    'shortUrlPath' => 'l',
]

    Plugin::load('UrlShortener', ['bootstrap' => false, 'routes' => true]);

    $urlShortener = new UrlShortener();
    $shortUrl = $urlShortener->shorten('https://domain.com/some_mega_supper_pupper_long_url');
    // $shortUlr = 'http://domain.com/l/MnNQLC'

    $shortUrl = $urlShortener->shorten('https://domain.com/some_mega_supper_pupper_long_url', 'one');
    // $shortUlr = 'http://domain.com/l/one'
    
    //expand full url in controller
    $fullUrl = $urlShortener->expandByRequest($this->request);
    
    //expand url anywhere
    $fullUrl = $urlShortener->expandByHash($shortUrlHash);

    use UrlShortener/Facade as UrlShortener;
    
    //create short url
    $shortUrl = UrlShortener::shorten('https://domain.com/some_mega_supper_pupper_long_url');
    
    //expand full url
    $fullUrl = UrlShortener::expandByRequest($this->request);

$urlShortener = new UrlShortener();
$urlShortener->setHashGenerator(function($fullUrl) {
    return uniqid($fullUrl);
});

//Define some class in your sorce
class Generator {
    public static generate(string $fullUrl): string
    {
        return uniqid($fullUrl);
    }
}

//app config
'UrlShortener' => [
    ...
    'hashGenerator' => [Generator::class, 'generate']
]

EventManager::instance()->on(UrlShortener::EVENT_EXPAND_FAIL, function(Event $event) {
    $shortUrl = $event->data['shortUrl'];
    Log::write('error', 'Unable to expand url: ' . $shortUrl);
});