Yii2 make a path alias from information stored in DB - php

Right now I'm trying to implement themming for my Yii2 based project.
How I see the thing now:
User chooses an application theme from the list on the settings
page in backend.
Using yii2-settings I'm saving all the
configuration data in DB (pretty easy).
In the application
bootstrap.php I'm creating new alias called #theme. Basically it
should lead us to a application theme base path (used in search
paths, assets manager, e.t.c.).
According to official
documentation, that's how I configured my view component:
'view' => [
'theme' => [
'basePath' => '#theme',
'baseUrl' => '#theme',
'pathMap' => [
'#app/views' => '#theme',
'#app/widgets' => '#theme/widgets',
'#app/modules' => '#theme/modules',
],
],
],
An issue I have is with p.3. According to yii2-settings documentation that's how I supposed to read the settings:
$theme = Yii::$app->settings->get('name', 'general');
Yii::setAlias('#theme', realpath(dirname(__FILE__)."/../../themes/$theme"));
But obviously, it's not working for me because of yii2-settings component didn't initialized yet when bootstrap.php is called. I've been trying to initialize it later in the init() method of my base controller, then adjust other aliases manually, but I feel that way being somewhat 'unclean', and also it still fails because of #theme alias is also used in asset file which is Yii2 starting to publish before calling the controller's init method.
So does anyone has any thoughts of how to do that 'hacking' the code as less as possible? I know I could just move configuration to some file, then read it manually before the application initialization, but it's still not the way I want to go.
Maybe there's some way to override some system component to set the alias after db component is loaded, but before view component configuration? Or Yii loads this components in a different order? Anyway. Any help would be appreciated!

You could try an Application Event in bootstrap:
\Yii::$app->on(\yii\base\Application::EVENT_BEFORE_REQUEST, function ($event) {
$theme = Yii::$app->settings->get('name', 'general');
Yii::setAlias('#theme', realpath(dirname(__FILE__)."/../../themes/$theme"));
});
OR in configuration file:
[
'on beforeRequest' => function ($event) {
// ...
},
]
From Yii 2 docs:
EVENT_BEFORE_REQUEST This event is triggered before an application
handles a request. The actual event name is beforeRequest.
When this event is triggered, the application instance has been
configured and initialized. So it is a good place to insert your
custom code via the event mechanism to intercept the request handling
process. For example, in the event handler, you may dynamically set
the yii\base\Application::$language property based on some parameters.

Here's the final solution:
config/bootstrap.php:
// Setting a temporary path for components configuration - will be changed later
Yii::setAlias('#theme', realpath(dirname(__FILE__)."/../../themes/"));
config/main.php
'components' => [
'view' => [
'theme' => [
'basePath' => '#theme',
'baseUrl' => '#theme',
'pathMap' => [
'#app/views' => '#theme',
'#app/widgets' => '#theme/widgets',
'#app/modules' => '#theme/modules',
],
],
],
],
'on beforeRequest' => function ($event) {
$theme = Yii::$app->settings->get('theme', 'general');
Yii::setAlias('#theme', realpath(dirname(__FILE__)."/../../themes/$theme"));
},

Related

Yii2 RBAC not working - allowing access to everything

I'm facing a problem where I've configured RBAC in Yii 2.0 but it does not work - meaning it dooes not prevent any of the pages from being loaded - even as guest.
This is in my web.php config (also in my console.php):
'authManager' => [
'class' => 'yii\rbac\DbManager',
],
The migrations have completed successfully.
This is how behaviors() look like at the moment, but I tried many different ways.
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['error'],
'allow' => true,
//'roles' => ["?"],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
If I implement the behaviors() function in my controller, the framework starts doing some access-handling, but the goal of using a DB as I understand should be that the RBAC system takes over this responsibility - meaning I don't have to enable/disable every single action I write for every single role.
I have added a Role "Admin" and assigned a few of the available routes (actions) to it.
Then I assigned this role to my User name. In theory this should enable my login to access those specific routes but nothing else - instead, I can traverse the site however I please, no 403s whatsoever. (This is why I'm saying RBAC acts like it's non-existing.)
Any hints or tips are appreciated.
Thanks.
where is your authManager configuration located?
According to [yii2 guide]
If you are using yii2-basic-app template, there is a config/console.php configuration file where the authManager needs to be declared additionally to config/web.php. In case of yii2-advanced-app the authManager should be declared only once in common/config/main.php.
Update to this question, I just tried do rbac manually
My result
We must do conditional in every action like
...
public function actionAbout()
{
if (Yii::$app->user->can('ViewAbout')) {
echo "you may see view about";
} else {
echo "view about is prohibited";
}
// return $this->render('about');
}
...
If you want assign it in common way, you better use extension/module that handle authmanager (like yii2-admin, yii2-mimin, etc)
Hope this answer help

Yii2 framework: How to change English default language to Spanish

I am using the Yii2 Framework and I am translating all texts of buttons, labels, messages, etc.
Then I read this article http://www.yiiframework.com/doc-2.0/guide-tutorial-i18n.html that shows how to do it automatically but I don't understand it.
I want to translate to Spanish from Argentina: es-AR or at least to any Spanish.
So I think I need to change from en-US to es-AR but I would like to know which files should I change.
Also I am using the great Gii code generator where I can see a checkbox called Enable I18N.
I watched these files but I am not sure if I am looking the right files:
vendor/yiisoft/yii2/base/Application.php
vendor/yiisoft/yii2/i18n/I18N.php
common/config/main-local.php
Add language propery and i18n component in application config. For advanced application template in common/config/main.php
return [
'language' => 'es-AR',
...
'components' => [
...
'i18n' => [
'translations' => [
'app*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#app/messages',
],
],
],
...
],
]
Use Yii::t() for all user messages (model labels, views, error messages etc).
echo \Yii::t('app', 'Friend');
Create directory messages/es-AR. Create file app.php in this directory and add translations
return [
'Friend' => 'Amigo',
'Girl' => 'Сhica',
...
];
Try to look into the official documentation, it is best tutorial for you. http://www.yiiframework.com/doc-2.0/guide-tutorial-i18n.html
Also, look at this answer yii2 basic multiple language
You can change default language by changing 'language' parameter of your main configuration file. Like this:
return
[
// set target language to be English
'language' => 'en-US',
]
Where instead 'en-US' you must to set needed locale code, e.g. 'es-AR'

How i can get log message with yii2

i have a little problem.
I'm developing a php application using Yii2 framework and i want to save a log messagges into db table.
I'm coding my own component witch extends DbTarget, in this component i rewrite export() function to save data into my table. It's works fine, but i can't get the log message.
For example, when i call Yii:log('message log'), all my data are saved in my db except 'message log' because i don't know how to get this value in my component.
Any solutions?
thanks
P.s. I'm newbee with yii2 and i have read the official documentation, but i didn't find any solution.
It seems you should specify level of the message
Yii:log('message log', Logger::LEVEL_TRACE);
or use shortcut methods
Yii::info('message log');
Yii::trace('message log');
Yii::error('message log');
Check your config for another targets. May be your message goes to level or category of another target. Notice that default category is 'application'.
To be shure you can make this configuration
'components' => [
'log' => [
'targets' => [
[
'class' => 'YourDbTarget',
'levels' => ['info'],
'categories' => ['application'],
],
],
],
],
And try to log info message
Yii::info('message log'); // target = info, category = application

CakePHP 3.2 - Specify different datasource for session handler

I am having an issue specifying a different datasource to use in a custom session handler inside config/app.php. Here are the relevant bits:
config/app.php
<?php
return [
... ,
'Datasources' => [
'default' => [...],
'test' => [...],
'session' => [...]
],
'Session' => [
'defaults' => 'database',
'ini' => ['session.cookie_domain' => '.example.com'],
'handler' => [
'engine' => 'CustomSessionHandler', // file and class name of custom handler
'model' => 'sessions' // table name
]
]
];
CustomSessionHandler.php is a copy of the default DatabaseSession.php with a few customisations in the query building to work with our existing sessions table schema.
Right now, it's trying to use the 'default' datasource, and as you might guess, I'm trying to get it to use the 'session' datasource. However I can't find any information on how to do that.
Any assistance is greatly appreciated!
The session handler only knows about the model, respectively the table class, and it shouldn't really know more than that.
So what you could do is configure that table class to use a non-default connection. If you don't have a concrete SessionsTable class yet, create one, and override Table::defaultConnectionName(), like
public static function defaultConnectionName()
{
return 'session';
}
See also Cookbook > Database Access & ORM > Table Objects > Configuring Connections

How to load a language file from a package in fuelphp?

Using the config.php always_load configuration, how does one load a language file from a package?
All of the fuelphp documentation alludes to being able to do this, but only shows the syntax for loading from a module.
Here's what I'm trying to do:
fuel/app/config/config.php
'always_load' => [
'language' => [
// loads fuel/app/lang/en/login.php into login group
'login',
],
],
fuel/app/config/production/config.php
'always_load' => [
'language' => [
// override /config/config.php with contents from
// /fuel/packages/pkg/lang/en/login.php
'lang_file_from_package' => 'login',
],
],
Packages are core extensions, which means it will merge the contents of the files found in app and in the package.
As such, there is no method to define you want to load it from the package only, other then by specifying a fully qualified pathname, which will always load just that file.

Categories