Yii2 params access within local config file in common directory - yii2

I'm using Yii2 advanced template,
I want to access params.php in main-local.php file,
I called this ways:
main-local.php:
'mailer' => [
'class' => 'myClass',
'apikey' => \Yii::$app->params['mandrill_api_key'],
'viewPath' => '#common/mail',
],
and I have stored this mandrill_api_key in params.php
params.php:
<?php
return [
'adminEmail' => 'admin#example.com',
'supportEmail' => 'support#example.com',
'user.passwordResetTokenExpire' => 3600,
'mandrill_api_key' => 'mykey'
];
I'm getting this error:
Notice: Trying to get property of non-object in C:\xampp\htdocs\myproject\common\config\main-local.php on line 25
What should I do to access these parameters?

The config files are read before the application is instantiated as explained in the request lifecycle:
A user makes a request to the entry script web/index.php.
The entry script loads the application configuration and creates an application instance to handle the request.
The application resolves the requested route with the help of the request application component.
...
As such \Yii::$app does not yet exist hence the error. I would suggest moving your api_key definition to the main-local.php config such that there is no confusion over where it is being set:
'mailer' => [
'class' => 'myClass',
'apikey' => 'actual api key',
'viewPath' => '#common/mail',
],
Alternatively, you can use Yii2's dependancy injection container to set the apikey in your application's entry script:
...
$app = new yii\web\Application($config);
\Yii::$container->set('\fully\qualified\myClass', [
'apikey' => \Yii::$app->params['mandrill_api_key'],
]);
$app->run();

You can just do
$params['mandrill_api_key']
you dont need to use
\Yii::$app->params['mandrill_api_key']

The params is a part of config and you can not call this in your config .
the best way for handel this you can use this in your class :
myClass:
class myClass extends ... {
public $apikey;
public function __construct(){
$this->apikey = \Yii::$app->params['mandrill_api_key'];
}
}

Related

Is it possible to set the path for all frontend AJAX request

My slugs looks like this:
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'<lang>/<p_page>/<p_category>/<p_product>' => 'splitter/manage-request',
'<lang>/<p_page>/<p_category>' => 'splitter/manage-request',
'<lang>/<p_page>' => 'splitter/manage-request',
'<lang>/' => 'splitter/manage-request',
'<lang>' => 'splitter/manage-request',
'' => 'splitter/manage-request',
],
],
I am sending all the requests to that SplitterController where I am parsing them. But I don't want the AJAXs to be send to it. Is it possible to give them some default route? To redirect them backend for example. I couldn't find information about it in the documentation? Appreciating links also is I missed it. Thank you!
According to my experience, there are probably the following options for your reference:
the first: The easiest way is to add a beforeAction() to your SplitterController, determine if it is an ajax request in beforeAction(), and redirect to your target address, for example:
public function beforeAction()
{
if (\Yii::$app->request->isAjax) {
return \Yii::$app->response->redirect($targetUrl);
}
return parent::beforeAction($action);
}
second: You can check if the request is an ajax request in the nginx configuration and then redirect to your target address
third: If you can't set up additional routing rules and configure the ajax request address, then you can consider implementing it by customizing UrlManager::parseRequest(), just check if it is an ajax request before it starts parsing the request, then redirect to your target. address
This answer is translated from Google Translate

How can I check the load and existence of the module (Yii2)?

I generated module siteadmin using GII, it appeared in the frontend/module folder. Next, I added it in the main.php front-end configuration file
'siteadmin' => [
'class' => 'app\modules\siteadmin\Module',
],
But the domain.net/siteadmin address shows a 404 error. Individual routs in the urlManager for this address are not created. How can I check all, and understand what is wrong and where is the error? Debug panel works, but it says: route to run: site/error
Try using explicit frontend application name eg:
'siteadmin' => [
'class' => 'frontend\modules\siteadmin\Module',
],
You need to confirm the namespace of the module class if you generated that module for the frontend the module class file frontend/modules/siteadmin/Siteadmin.php should have the namespace like.
namespace frontend\modules\siteadmin;
and the directory structure should look like below
The Siteadmin.php file that you are seeing in the above picture is the main module file.
If the directory structure is like I stated above in the picture then you should add the module inside the frontend/config/main.php like below
'modules' => [
'siteadmin' => [
'class' => 'frontend\modules\siteadmin\Siteadmin',
],
],
Then you can access it like http://example.com/siteadmin/default or if there is any other controller than default you can provide that name.

How to load class at every page load in advanced app

I want to have class in which I would put all my methods that should run everytime someone loads a page, lets call it InitRoutines.
In yii2 basic app I would do something like this. I would add class to compontents config file, and add it to bootstrap, simple as that.
But I can not figure out how to do it in advanced app, preferable in common/config
config.php
$config = [
// ..
'components' => [
'InitRoutines' => [
'class' => 'app\commands\InitRoutines',
],
],
];
$config['bootstrap'][] = 'InitRoutines';
And in InitRoutines I have init class which run everything I need at page load.
InitRoutines.php
namespace app\commands;
use Yii;
use yii\base\Component;
use app\commands\AppHelper;
use app\commands\Access;
class InitRoutines extends Component
{
public function init()
{
parent::init();
Access::checkForMaintenance();
Yii::$app->language = AppHelper::getUserLanguageCode();
}
}
How can I accomplish same in advanced app ?
I think I found the solution, I dont know if it is correct way but it seem to be working.
config.php
return [
// ...
'components' => [
'InitRoutines' => [
'class' => 'common\commands\InitRoutines',
],
],
'bootstrap' => [
'log',
'common\commands\InitRoutines'
],
];

how to run action of frontend controller from backend in yii2

Is it possible to run action of frontend controller from backend?
this code works if called action is in backend too. can i specify in runAction that controller/action is in frontend?
Yii::$app->runAction('controller/action')
Also i' m tried something like
$c=new controller();
$s->action();
too but it seems it not working too. //new controller() need some parameters and i have no idea what it is.
The yii\base\Application object has a public property controllerNamespace, which defaults to app\\controllers. You need to change it accordingly to changing default controller namespace.
Change namespace in action:
Yii::$app->controllerNamespace = 'frontend\controllers' and use runAction
A way could be this .
In your backend application config you could create an additional 'UrlManager' component
name eg: urlManagerFrontEnd
return [
'components' => [
'urlManager' => [
// here is your backend URL rules
],
'urlManagerFrontEnd' => [
'class' => 'yii\web\urlManager',
'baseUrl' => 'http://your_path/frontend/web/index.php',
'enablePrettyUrl' => true,
'showScriptName' => false,
],
],
];
Then you should invoke following to compose front-end URL:
Yii::$app->urlManagerFrontEnd->createUrl();
and add the controller/action you prefer
remeber that
runAction()
Runs an action within this controller with the specified action ID and
parameters.
http://www.yiiframework.com/doc-2.0/yii-base-controller.html#runAction()-detail
this mean that cannot run an action of another controller or of another application ..
If you need a service then you must configure a RESTFull or you simply need a redirection you can use redirect

Yii2 isGuest giving exception in console application

In console application when I used Yii::$app->user->isGuest it is giving the below exception:
Exception 'yii\base\UnknownPropertyException' with message 'Getting unknown prop
erty: yii\console\Application::user'
I even tried adding the user in components array in config file. But it didn't worked. Any idea what am I doing wrong?
In Console application Yii->$app->user does not exist. So, you need to configure user component in config\console.php.
like as,
config\console.php
'components' => [
.........
......
'user' => [
'class' => 'yii\web\User',
'identityClass' => 'app\models\User',
//'enableAutoLogin' => true,
],
'session' => [ // for use session in console application
'class' => 'yii\web\Session'
],
.......
]
To check it works or not using below code.
public function actionIndex($message = 'hello world')
{
echo $message . "\n";
$session = \Yii::$app->session->set('name', 'ASG');
if(\Yii::$app->session) // to check session works or not
echo \Yii::$app->session->get('name')."\n";
print_R(\Yii::$app->user);
}
More info about your problem : Link
Note : There's no session in console.
The reason is simple. Guide says about application components (user is a component):
user: represents the user authentication information. This component
is only available in Web applications Please refer to the
Authentication section for more details.
So Yii::$app->user it not available in console applications.
As a consequence you have to consider using this component in model classes that are also used by console applications.
Extra note: it is internally used by BlameableBehavior, however, this makes no problems since user will be null if a model gets saved/created and no user is available.