PHP: gestire le versioni CDN di jQuery

PHP: gestire le versioni CDN di jQuery

Gestire jQuery con PHP è un compito arduo quando si ha a che fare con copie remote su cui non si ha nessun controllo. Lo stesso discorso si applica alle versioni di jQuery che vengono rilasciate ma che non sono ancora disponibili sul sistema CDN di riferimento. Di seguito propongo una semplice classe PHP per gestire le versioni di jQuery sui sistemi CDN di Google.

La classe è la seguente:


class jQueryLibraryLoad
{
    protected $_baseURL;
    protected $_library;
    protected $_version;
    protected $_fallbackVersion;
    protected $_failVersion;
    
    public function __construct($baseURL, $library, $version, $fallbackVersion, $failVersion)
    {
       $this->_baseURL = $baseURL; 
       $this->_library = $library;
       $this->_version = $version;
       $this->_fallbackVersion = $fallbackVersion;
       $this->_failVersion = $failVersion;
    }
    
    protected function _parseVersion($version)
    {
        
        $last_version;
        
        if(preg_match('/(\d\.)+/', $version)) {
            
            
            $last_version = preg_replace('/\.\d$/', '', $version);
            
            
            
        }
        
        return $last_version;
        
        
    }
    
    public function fetchLibrary()
    {
        
        header('Content-Type: text/javascript');
        
        
        $library_ver = $this->_parseVersion($this->_version);
        $output = '';
        
        $full_URL = $this->_baseURL . $library_ver . '/' . $this->_library;
        $alt_URL = $this->_baseURL . $this->_fallbackVersion . '/'. $this->_library;
        $fail_URL = $this->_failVersion;
        
        if(@file_get_contents($full_URL)) {
            
            
            $output = file_get_contents($full_URL);
            
            return $output;
            
            
        } else {
            
            
            $output = @file_get_contents($alt_URL);
            
            if($output) {
            
            	return $output;
            	
            } else {
            
            	return file_get_contents($fail_URL);
            
            
            }
            
        }
        
        
    }
    
    
    
    
}

La classe prende in considerazione le seguenti eventualità:

  1. la versione di jQuery che vogliamo non è ancora presente
  2. si passa quindi ad una versione inferiore
  3. se anche questa versione non è disponibile, si passa alla copia locale

Esempio:


require_once('jQueryLibraryLoad.class.php');

$library = new jQueryLibraryLoad(
    
     'http://ajax.googleapis.com/ajax/libs/jquery/',
     'jquery.min.js',
     '1.8.0',
     '1.7.1',
     'http://sito.local/js/jquery.js'
    
);
echo $library->fetchLibrary();
Torna su