Created
August 20, 2016 14:20
-
-
Save Driver86/c09067541e0c16250c33f6f6a863ed93 to your computer and use it in GitHub Desktop.
Yii2 Config for CDN-assets with current versions from Composer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$bundles = []; | |
foreach(json_decode(file_get_contents(__DIR__ . '/composer.lock'))->packages as $package) { | |
if (!preg_match('#^bower-asset/(.+)$#', $package->name, $name) or !preg_match('#^v?(.+)$#', $package->version, $version)) { | |
continue; | |
} | |
$name = $name[1]; | |
$version = $version[1]; | |
switch ($name) { | |
case 'jquery': | |
$bundles['yii\web\JqueryAsset'] = [ | |
'sourcePath' => null, | |
'css' => [], | |
'js' => ['//cdnjs.cloudflare.com/ajax/libs/jquery/' . $version . '/jquery.min.js'], | |
]; | |
break; | |
case 'tether': | |
$bundles['yii\bootstrap\TetherAsset'] = [ | |
'sourcePath' => null, | |
'css' => ['//cdnjs.cloudflare.com/ajax/libs/tether/' . $version . '/css/tether.min.css'], | |
'js' => ['//cdnjs.cloudflare.com/ajax/libs/tether/' . $version . '/js/tether.min.js'], | |
]; | |
break; | |
case 'bootstrap': | |
$bundles['yii\bootstrap\BootstrapAsset'] = [ | |
'sourcePath' => null, | |
'css' => ['//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/' . $version . '/css/bootstrap.min.css'], | |
'js' => [], | |
]; | |
$bundles['yii\bootstrap\BootstrapPluginAsset'] = [ | |
'sourcePath' => null, | |
'css' => [], | |
'js' => ['//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/' . $version . '/js/bootstrap.min.js'], | |
]; | |
break; | |
case 'font-awesome': | |
$bundles['common\assets\FontAwesomeAsset'] = [ | |
'sourcePath' => null, | |
'css' => ['//cdnjs.cloudflare.com/ajax/libs/font-awesome/' . $version . '/css/font-awesome.min.css'], | |
'js' => [], | |
]; | |
break; | |
} | |
} | |
$config = [ | |
//... | |
'components' => [ | |
//... | |
'assetManager' => [ | |
'linkAssets' => true, | |
'bundles' => $bundles, | |
], | |
], | |
]; | |
//... | |
return $config; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Integrating CDN in Yii2 is quite easy. Yii2 has some open source packages that configure CDN services for delivering assets such as CSS and JavaScript files, like blacksmoke26/yii2cdn package. If you have this package installed, create a CDN directory in the root and install the asset in it. Open web.php under config folder and add cdn property under component. Define two version of the files, one for the local and another for the live version. Add code, something like this, in the view:
Yii::$app->cdn->get('font-awesome')->register();
source: https://www.cloudways.com/blog/cdn-in-yii2/