Skip to content

Instantly share code, notes, and snippets.

@Driver86
Created August 20, 2016 14:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Driver86/c09067541e0c16250c33f6f6a863ed93 to your computer and use it in GitHub Desktop.
Save Driver86/c09067541e0c16250c33f6f6a863ed93 to your computer and use it in GitHub Desktop.
Yii2 Config for CDN-assets with current versions from Composer
<?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;
@azazqadir
Copy link

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/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment