Skip to content

Instantly share code, notes, and snippets.

@stephencozart
Last active October 18, 2018 20:40
Show Gist options
  • Save stephencozart/43c6a78070c18c5a9eb7d2d5537ef545 to your computer and use it in GitHub Desktop.
Save stephencozart/43c6a78070c18c5a9eb7d2d5537ef545 to your computer and use it in GitHub Desktop.
Yii2 App Engine Standard AssetManager. Must rename web/ -> public/ or specify an entrypoint as entrypoint: web/index.php in your app.yaml file
runtime: php72
handlers:
- url: /css
static_dir: public/css
- url: .*
script: public/index.php
<?php
namespace app\components;
use yii\base\InvalidConfigException;
use yii\helpers\FileHelper;
class AssetManager extends \yii\web\AssetManager
{
/**
* Initializes the component.
* @throws InvalidConfigException if [[basePath]] is invalid
* @throws \yii\base\Exception
*/
public function init()
{
if ($this->basePath) {
FileHelper::createDirectory($this->basePath);
}
parent::init();
}
}
<?php
// comment out the following two lines when deployed to production
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';
$config = require __DIR__ . '/../config/web.php';
$pathInfo = $_SERVER['REQUEST_URI'];
$assetBaseUrl = $config['components']['assetManager']['baseUrl'];
if (\yii\helpers\StringHelper::startsWith($pathInfo, $assetBaseUrl)) {
$path = '/tmp' . $pathInfo;
if (file_exists($path)) {
$mime = \yii\helpers\FileHelper::getMimeTypeByExtension($path);
header('Content-Type: ' . $mime);
echo file_get_contents($path);
} else {
throw new \yii\web\NotFoundHttpException();
}
} else {
$app = new yii\web\Application($config);
$app->run();
}
<?php
$config = [
...
'runtimePath' => '/tmp',
'components' => [
'assetManager' => [
'class' => 'app\components\AssetManager',
'baseUrl' => '/assets',
'basePath' => '/tmp/assets'
]
],
....
// set the baseUrl on the request component to '/' to play nicely with dev_appserver.py
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'JBZIK8HaM3KaOig3KYyzh6GGTBXCNH98',
'baseUrl' => '/'
],
....
// must enablePrettyUrl and set showScriptName to false. Also set baseUrl to '/' to play nicely with dev_appserver.py
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'baseUrl' => '/',
'rules' => [
],
],
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment