Yii2 asset compression using closure compiler and yuicompresser - yii2

http://www.yiiframework.com/doc-2.0/guide-structure-assets.html
i generate assets.php in the root of the application using this command yii asset/template assets.php
assets.php
<?php
/**
* Configuration file for the "yii asset" console command.
*/
// In the console environment, some path aliases may not exist. Please define these:
// Yii::setAlias('#webroot', __DIR__ . '/../web');
// Yii::setAlias('#web', '/');
return [
// Adjust command/callback for JavaScript files compressing:
'jsCompressor' => 'java -jar compiler.jar --js {from} --js_output_file {to}',
// Adjust command/callback for CSS files compressing:
'cssCompressor' => 'java -jar yuicompressor.jar --type css {from} -o {to}',
// The list of asset bundles to compress:
'bundles' => [
// 'app\assets\AppAsset',
// 'yii\web\YiiAsset',
// 'yii\web\JqueryAsset',
],
// Asset bundle for compression output:
'targets' => [
'all' => [
'class' => 'yii\web\AssetBundle',
'basePath' => 'C:/wamp/www/flywings/frontend/web/assets',
'baseUrl' => '/flywings/frontend/web/assets',
'js' => 'js/all-{hash}.js',
'css' => 'css/all-{hash}.css',
],
],
// Asset manager configuration:
'assetManager' => [
//'basePath' => '#webroot/assets',
//'baseUrl' => '#web/assets',
],
];
and i installed closure compiler and yuicompresser in my pc at the following path C:\closure-compiler and C:\YUI\yuicompressor\build
and i dont know how to proceed to next step.in the assets.php whats the {from} {to} and how to add the bundles there(manually ?).I am using the advanced application.

Related

Where do we configure Yii2 Queue extension in project?

I am trying to use the yii2-queue
https://github.com/yiisoft/yii2-queue/blob/master/docs/guide/usage.md
It says:
In order to use the extension you have to configure it like the
following:
return [
'bootstrap' => [
'queue', // The component registers its own console commands
],
'components' => [
'queue' => [
'class' => \yii\queue\<driver>\Queue::class,
'as log' => \yii\queue\LogBehavior::class,
// Other driver options
],
],
];
My question is simple: In which PHP file, in which directory, should I put this code?
Note: I am using the Basic template.
For Yii2 Basic Template config/console.php
For Yii2 Advanced Template console/config/main.php
return [
'bootstrap' => [
'log',
'queue',
],
'components' => [
'queue' => [
'class' => \yii\queue\db\Queue::class,
'db' => 'db', // DB connection component or its config
'tableName' => '{{%queue}}', // Table name
'channel' => 'default', // Queue channel key
'mutex' => \yii\mutex\MysqlMutex::class, // Mutex that used to sync queries
'as log' => \yii\queue\LogBehavior::class,
// 'deleteReleased' => YII_ENV_PROD,
],
]
];
Refer Yii2 Queue extension guide
Add to the main.php file in backend or frond end you are using like this
'bootstrap' => ['log', 'queue'],
Add this to under component array
'queue' => [
'class' => Queue::class,
'db' => 'db', // DB connection component or its config
'tableName' => '{{%db_queue}}', // Table name
'channel' => 'default', // Queue channel key
'mutex' => MysqlMutex::class, // Mutex used to sync queries
]
To make it workfull you need to do same in console /config/main.php
file and run the command listen form documentaiton
It is very simple to configure it on yii2 basic, add the following configuration on config/web.php file, and for yii2 advanced if you are using frontend then add in frontend/config/main.php, if you are using backend then add to to backend/config.main.php.
Just like this
'components' => [
'request' => [
'cookieValidationKey' => 'htXdOInCiP6ut4gNbDO2',
'csrfParam' => '_frontendCSRF',
],
'queue' => [
'class' => \yii\queue\<driver>\Queue::class,
'as log' => \yii\queue\LogBehavior::class,
// Other driver options
],
]

Yii2 migrations - Separated Migrations

I am creating a module with the following structure:
common
L modules
LL blog
LLL backend
LLL frontend
LLL common
LLL migrations
I found in yii2 documentation a section about "Separated Migrations"
In console/config/main.php I have set:
'migrate-blog' => [
'class' => 'yii\console\controllers\MigrateController',
'migrationNamespaces' => ['app\common\modules\blog\migrations'],
'migrationTable' => 'migration_blog',
'migrationPath' => null,
]
Then I go to console and run following command:
php yii migrate/create app\\common\\modules\\blog\\migrations\\create_table_blog_post
It returns an error:
Error: Namespace 'app\common\modules\blog\migrations' not found in `migrationNamespaces`
am I missing any settings?
Did you add the following info to config of console.php
'controllerMap' => [
// Migrations for the specific project's module
'migrate-module' => [
'class' => 'yii\console\controllers\MigrateController',
'migrationNamespaces' => ['app\module\migrations'],
'migrationTable' => 'migration_module',
'migrationPath' => null,
],
],
I have seen that you have the config in console/config/main.php then the check the yii file is having the following line.
$config = require(__DIR__ . '/console/config/main.php');
After this instead of running
php yii migrate/create app\\common\\modules\\blog\\migrations\\create_table_blog_post
Run the following command
php yii/migrate-blog/create create_table_blog_post
I hope this helps.

Yii2 - Gii extension assets folder alias referencing to a wrong path

I am trying to learn Yii 2 from a book (Web application development with Yii2 and PHP). Somewhere along the line it instructs me to install gii and create crud files with it.
When I installed with the following command:
php composer.phar require --prefer-dist "yiisoft/yii2-gii:*"
I have following error:
Invalid Parameter – yii\base\InvalidParamException
The file or directory to be published does not exist: /var/projectsRoot/crmapp/src/vendor/yiisoft/yii2/gii/assets
My bootstrap code:
//Define Yii debug mode
define (YII_DEBUG, true);
//Including composer autoloader
require (__DIR__ . '/../vendor/autoload.php');
//Including Yii framework
require (__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
//debugging for PHP
ini_set('display_errors', true);
//Getting Configuration
$config = require(__DIR__ . '/../config/web.php');
//Include and launch application
(new yii\web\Application($config))->run();
config file:
return [
'id' => 'crmapp',
'basePath' => realpath(__DIR__ . '/../'),
'components' => [
'request' => [
'cookieValidationKey' => 'your secret key here'
],
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false
],
'db' => require(__DIR__ . '/db.php')
],
'modules' => [
'gii' => [
'class' => 'yii\gii\Module',
'allowedIPs' => ['192.168.33.1']
]
],
'extensions' => [
require (__DIR__ . '/../vendor/yiisoft/extensions.php')
]
];
extensions file:
$vendorDir = dirname(__DIR__);
return array (
'yiisoft/yii2-bootstrap' =>
array (
'name' => 'yiisoft/yii2-bootstrap',
'version' => '2.0.5.0',
'alias' =>
array (
'#yii/bootstrap' => $vendorDir . '/yiisoft/yii2-bootstrap',
),
),
'yiisoft/yii2-gii' =>
array (
'name' => 'yiisoft/yii2-gii',
'version' => '2.0.4.0',
'alias' =>
array (
'#yii/gii' => $vendorDir . '/yiisoft/yii2-gii',
),
),
);
I digged it a little bit. It seems problem is about the alias of the assets folder.
In GiiAsset.php file, there is this codeblock:
...
class GiiAsset extends AssetBundle
{
public $sourcePath = '#yii/gii/assets';
...
which returns
/var/projectsRoot/crmapp/src/vendor/yiisoft/yii2/gii/assets
but it normally should return
/var/projectsRoot/crmapp/src/vendor/yiisoft/gii/assets
so it is adding an unnecessary yii2 to the path.
I tried to change the $sourcePath in extensions.php file, but changing the value here does not effect the result in any way.
Any ideas?
--UPDATE--
While I was fiddling with things, I tried to define the alias to force the correct value; as follows:
Yii::setAlias('#yii/gii', $vendorDir . '/yiisoft/yii2-gii');
when I try to run the application with this setting I get following error:
The file or directory to be published does not exist: /var/projectsRoot/crmapp/src/vendor/bower/bootstrap/dist
When I change the alias definition to this:
Yii::setAlias('#yii/gii', $vendorDir . '/yiisoft/yii2-gi');
I get following error:
The file or directory to be published does not exist: /var/projectsRoot/crmapp/src/vendor/yiisoft/yii2-gi
I'm quite confused with this behavior. What would be causing this?
I ended up with deleting my vendor folder and composer.json file, and creating it back with following content:
{
"require": {
"codeception/codeception": "*",
"fzaninotto/faker": "*",
"yiisoft/yii2": "*",
"yiisoft/yii2-gii": "*"
}
}
When I launched the gii, it again threw the following exception:
The file or directory to be published does not exist:
/var/projectsRoot/crmapp/src/vendor/bower/jquery/dist
I renamed the vendor/bower-asset folder to vendor/bower and it works now.
I probably messed up with something before without noticing, but I'm not certain why it is looking for bower, instead of bower-asset. Renaming the bower-asset to bower seems to solve it.
UPDATE
Thanks to jacmoe from the original Yii forum, it has finally solved.
It seems these two lines need do be present in composer.json in order to automatically create bower folder, instead of bower-asset.
"extra": {
"asset-installer-paths": {
"npm-asset-library": "vendor/npm",
"bower-asset-library": "vendor/bower"
}
}
Original conversation can be found at here:
These lines are automatically created when you install the basic application template, but when installing the bare code base, you need to manually write them.
I have similar problem with my app based on yii2-app-advanced, but separated from #common. Solution is just add vendorPath attribute to application config.

Why Yii2 module separate configuration does not work in basic app?

I have a yii2 basic application with 2 parts (web and service for mobile).
I have created a module to handle the restful requests fired from mobile . I want to configure this module to be rest. So I created a config file for this module in side the module directory. as mentioned in the yii2 documentation for modules
/config/config.php:
return [
'components' => [
'urlManager' => [
'class' => 'yii\web\UrlManager',
// Disable index.php
'showScriptName' => false,
// Disable r= routes
'enablePrettyUrl' => true,
'enableStrictParsing' => false,
'rules' => array(
[
'class' => 'yii\rest\UrlRule',
'controller' => 'mobile/mobile-clients',
'extraPatterns' => ['GET search' => 'search']
],
),
],
'request' => [
'class' => '\yii\web\Request',
'enableCookieValidation' => false,
'parsers' => [
'application/json' => 'yii\web\JsonParser',
],
],
]
];
the module class is as follows:
<?php
namespace app\modules\Mobile;
use Yii;
use yii\base\Module;
class MobileService extends Module {
public $controllerNamespace = 'app\modules\Mobile\controllers';
public function init() {
parent::init();
Yii::configure($this, require(__DIR__ .DIRECTORY_SEPARATOR
.'config'.DIRECTORY_SEPARATOR .'config.php'));
}
}
The problem is that the request component is not working as expected while it works fine when configured in the application configuration (config/main.php)
same for the urlManager.
Any Ideas?
The Solution to my problem is to create api application that is a new application inside the yii2 basic app. It shares the models and the vendors directory but has its own configuration and entry script (index.php). This is the solution link for more information .
EDIT:
Do not forget to add the user component in the api.config file
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => false,
],
I think using yii2 advanced application structure is better for a case like mine. But this solution works perfect :) .
Best.

Yii2 advanced accessing frontend from backend using alias

I trying to access frontend/web from backend menu using alias
yii:yii2 advanced
webserver : XAMPP
IDE:net beans
codes I modified:
C:\xampp\htdocs\advanced\common\config\aliases.php
Yii::setAlias('fronthome', dirname(dirname(__DIR__)) . '/frontend/web/');
C:\xampp\htdocs\advanced\backend\views\layouts\main.php
if (Yii::$app->user->isGuest) {
$menuItems[] = ['label' => 'Login', 'url' => ['/site/login']];
$menuItems[] = ['label' => 'fronthome', 'url' => Yii::getAlias('#fronthome')];
but when accessing "fronthome" menu via backend menu; browser was returning the url:
http://localhost/advanced/backend/web/C:/xampp/htdocs/advanced/frontend/web
what i wanted browser to give:
http://localhost/advanced/frontend/web/
can some one please put some light... I searched but there was no elegant solution which I could find via alias.
Thanks
I got it working by making the below change
C:\xampp\htdocs\advanced\common\config\aliases.php
Yii::setAlias('fronthome', dirname(dirname(__DIR__)) . '/frontend/web/');
to
Yii::setAlias('fronthome', '../../frontend/web/');
As the links in the comments are outdated here is a snippet from the Yii2 docs:
Creating links from backend to frontend
Often it's required to create links from the backend application to the frontend application. Since the frontend application may contain its own URL manager rules you need to duplicate that for the backend application by naming it differently:
return [
'components' => [
'urlManager' => [
// here is your normal backend url manager config
],
'urlManagerFrontend' => [
// here is your frontend URL manager config
],
],
];
//After it is done, you can get an URL pointing to frontend like the following:
echo Yii::$app->urlManagerFrontend->createUrl(...);
current link to copy of relevant doc: https://yii2-framework.readthedocs.io/en/stable/guide/tutorial-advanced-app/
The way I have implemented this is to add a switch to my backend/config/bootstrap.php
switch (YII_ENV) {
case 'dev':
$frontend = 'https://my-domain.lan/';
break;
case 'test':
$frontend = 'https://my-domain.test/';
break;
case 'prod':
$frontend = 'https://my-domain.com/';
break;
}
and then in my backend/config/main.php I added the following
'urlManagerFrontend' => [
'class' => UrlManager::className(),
'enablePrettyUrl' => true,
'showScriptName' => false,
'baseUrl' => $frontend,
'rules' => [
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
]
],
and then where I want to use the frontend link:
echo Html::a('link',Yii::$app->urlManagerFrontend->createUrl('controller/view'))
Try using params.php
Add a key on params.php on your common/config folder
'frontendUrl' => 'http://frontendUrl/',
Then you could access it anywhere on your view by:
<?= Yii::$app->params['frontendUrl'] ?>
Hope this helps :)