Zend 3 - using logger as service - php

I am quite novice with ZF3 and I can't figure out how should I define a logger module as a service and how could I use (reuse) it in other modules. The official documentation is poor from this point of view. Any short example would be good.

If you want to use zend-log in ZF app, after installation you need to do 2 thing:
To register Zend\Log in the application config under the 'modules' key.
Add config for your logger in global.php or module config
'log' => [
'MyLogger' => [
'writers' => [
'stream' => [
'name' => 'stream',
'priority' => \Zend\Log\Logger::ALERT,
'options' => [
'stream' => '/tmp/php_errors.log',
'formatter' => [
'name' => \Zend\Log\Formatter\Simple::class,
'options' => [
'format' => '%timestamp% %priorityName% (%priority%): %message% %extra%',
'dateTimeFormat' => 'c',
],
],
'filters' => [
'priority' => [
'name' => 'priority',
'options' => [
'operator' => '<=',
'priority' => \Zend\Log\Logger::INFO,
],
],
],
],
],
],
],
],
after that just take it from Service Manager and use it:
$logger = $container->get('MyLogger'); // <-- the key that you register in config above
$logger->info('Logging info message in the file');
You probably want to take logger from SM and than inject it in a class that you want to use it.
There is a god blog post about Logging with zend-log

Related

can't view backend user admin pages using Yii2-usuario

I'm using Yii2-usuario for my user module.
I ran the migrations found in "first step" under the section "Creating the first Administrator during a migration", and only changed from new \Da\User\Model\User() to new \app\models\user\Model\User() like this
$user = new \app\models\user\Model\User([
'scenario' => 'create',
'email' => "admin#admin.com",
'firstname' => 'first',
'lastname' => 'last',
'password' => "verysecret" // >6 characters!
]);
it populated my tables correctly. But when i login to backend and try to view https://localhost/bla/backend/web/user/admin/index, i get a 403 forbidden error
in my backend main.php i have this
'components' => [
....
'authManager' => [
'class' => 'Da\User\Component\AuthDbManagerComponent',
'defaultRoles' => ['guest'],
],
],
'modules' => [
'user' => [
'class' => Da\User\Module::class,
'enableEmailConfirmation' => true,
'enableRegistration' => false,
'maxPasswordAge' => 90,
'enableGdprCompliance' => false,
'classMap' => [
'User' => 'app\models\user\Model\User',
],
'viewPath' => '#app/views/user',
'controllerMap' => [
//disable for backend
'profile' => [
'class' => Da\User\Controller\ProfileController::class,
'as access' => [
'class' => yii\filters\AccessControl::class,
'rules' => [['allow' => false]],
],
],
'recovery' => [
'class' => Da\User\Controller\RecoveryController::class,
'as access' => [
'class' => yii\filters\AccessControl::class,
'rules' => [['allow' => false]],
],
],
'Registration' => [
'class' => Da\User\Controller\RegistrationController::class,
'as access' => [
'class' => yii\filters\AccessControl::class,
'rules' => [['allow' => false]],
],
],
'Settings' => [
'class' => Da\User\Controller\SettingsController::class,
'as access' => [
'class' => yii\filters\AccessControl::class,
'rules' => [['allow' => false]],
],
],
'migrate' => [
'class' => \yii\console\controllers\MigrateController::class,
'migrationNamespaces' => [
'Da\User\Migration',
],
'migrationPath' => [
'#app/migrations',
'#yii/rbac/migrations',
],
],
],
],
my User model in backend\models\user\Model looks like this
use Da\User\Model\User as BaseUser;
class User extends BaseUser
{
public static function tableName()
{
return '{{%admin}}';
}
...
...
..
}
the list of RBAC and admin action don't work. i get a 403.
any idea what I'm missing here or did wrong? Thanks.
In the link which was provided for the first step with migration code, next is written
After installing the extension and having configured everything, you
need setup your application with the all the user related stuff, e.g.
You need to run this migration only after you did all installation steps mentioned here. But still it won't work because default user table will be populated, which was created from initial migration. This package creates its own user table and moreover in installation steps there is a Note
Note: If you are using Yii2's Advanced Application Template, before
starting to work with database, please ensure you have deleted
m130524_201442_init.php migration file which comes from the default
installation. It's located at
%PROJECT_DIR%/console/migrations/m130524_201442_init.php path.
Step 1
In your case i would do yii migrate/down 2, which will revert last 2 migrations(init migration contain user table description). Only in case if you didn't add more migrations :)
Total 2 migrations to be reverted:
m190124_110200_add_verification_token_column_to_user_table
m130524_201442_init
In case migration fail, you can run few SQL queries
drop table user;
delete from migration where version='m130524_201442_init';
and then delete m130524_201442_init.php and m190124_110200_add_verification_token_column_to_user_table.php(second one is optional but its your call) files
Step 2
After that according to docs, you need to run rbac + Yii 2 Usuario migrations all together as stated in this note
Note: You will still have to apply Yii 2 RBAC migrations by executing
./yii migrate --migrationPath=#yii/rbac/migrations. Remember that you
have to configure the AuthManager component first. Also, namespaced
migrations were introduced in Yii 2.0.10, so before using them
consider updating your framework installation version. If you are
using a Yii 2 version prior to 2.0.10, you'll have to copy the
migrations located on vendor/2amigos/yii2-usuario/src/User/Migration,
remove its namespaces and add it to your #app/migrations folder.
But before that, you need to move code below from backend/config/main.php to %PROJECT_DIR%/console/config/main.php
'controllerMap' => [
'migrate' => [
'class' => \yii\console\controllers\MigrateController::class,
'migrationNamespaces' => [
'Da\User\Migration',
],
'migrationPath' => [
'#app/migrations',
'#yii/rbac/migrations',
],
],
]
and add authManager into console config for rbac also
'authManager' => [
'class' => 'Da\User\Component\AuthDbManagerComponent',
],
in final your console/config/main.php should be similar to this
return [
// ....
'controllerMap' => [
// ...
'migrate' => [
'class' => \yii\console\controllers\MigrateController::class,
'migrationPath' => [
'#app/migrations',
'#yii/rbac/migrations', // Just in case you forgot to run it on console (see next note)
],
'migrationNamespaces' => [
'Da\User\Migration',
],
],
],
'components' => [
'authManager' => [
'class' => 'Da\User\Component\AuthDbManagerComponent',
],
// ...
],
// ...
];
Step 3
Run the migration from note
./yii migrate --migrationPath=#yii/rbac/migrations
Total 13 new migrations to be applied:
Da\User\Migration\m000000_000001_create_user_table
Da\User\Migration\m000000_000002_create_profile_table
Da\User\Migration\m000000_000003_create_social_account_table
Da\User\Migration\m000000_000004_create_token_table
Da\User\Migration\m000000_000005_add_last_login_at
Da\User\Migration\m000000_000006_add_two_factor_fields
Da\User\Migration\m000000_000007_enable_password_expiration
Da\User\Migration\m000000_000008_add_last_login_ip
Da\User\Migration\m000000_000009_add_gdpr_consent_fields
m140506_102106_rbac_init
m170907_052038_rbac_add_index_on_auth_assignment_user_id
m180523_151638_rbac_updates_indexes_without_prefix
m200409_110543_rbac_update_mssql_trigger
Step 4
Create and run migration from first steps without changing model in example.
Step 5
Remove user config from both backend/config/main.php and frontend/config/main.php
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-backend', 'httpOnly' => true],
],
Apply authManager and user module with proper administrators option to respective config files. This array should contain same role name as in migration which you did in step 4.
'modules' => [
'user' => [
'class' => Da\User\Module::class,
'administrators' => ['admin']
],
],
'authManager' => [
'class' => 'Da\User\Component\AuthDbManagerComponent',
],
In the final your frontend and backend config files should be similar to this
return [
// ...
'modules' => [
'user' => [
'class' => Da\User\Module::class,
'administrators' => ['admin']
],
],
'components' => [
'authManager' => [
'class' => 'Da\User\Component\AuthDbManagerComponent',
],
// ....
]
// ...
];
Step 6
My favorite step :)
http://yourapp/index.php?r=user/admin visit and enter your creds from migration. Enjoy!

yii\rest\UrlRule with "pluralize" rule is not working in Yii2 REST

I am unable to access default endpoints with pluralize option, view action is also not working
Case 1: Access without configure Module
'controllerNamespace' => 'api\controllers',
...
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'country',
'tokens' => [
'{id}' => '<id:\\w+>'
],
/*'pluralize'=>false,*/
],
]
http://localhost/api/web/countries Not working
http://localhost/api/web/country is working fine
http://localhost/api/web/country/1 is Not working
Case 2: Access via module v1
'modules' => [
'v1' => [
'basePath' => '#app/modules/v1',
'class' => 'api\modules\v1\Module'
]
],
...
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => ['country' => 'v1/country'],
'tokens' => [
'{id}' => '<id:\\w+>'
],
],
]
'pluralize' is not working completely and when access
v1/country & v1/country/12 both giving same result as index action (country list)
Your rule is incorrect you are missing the module name v1 in your rules
[
'class' => 'yii\rest\UrlRule',
'controller' => 'v1/country',
'tokens' => [
'{id}' => '<id:\\w+>'
],
'extraPatterns' => [
'GET index' => 'index',
],
],
Now you can access it with
http://localhost/api/web/v1/countries
Note : in order to enable the POST request along with GET add it to the extra patterns like 'GET,POST index' => 'index',

EAuth Extension Yii2, Class nodge\eauth\EAuth does not exist

I am trying to use EAuth extension in Yii2 advanced application. I installed it through composer and it installed it under vendor directory and configured as mentioned here (did the config in common/config/main). So, following is the directory structure for that:
root
vendor
nodege
lightopenid
provider
*files go here*
yii2-eauth
src
*files go here*
EAuth.php is under src folder. In controller I have done this in use:
use nodge\eauth\EAuth;
and when I do this:
$eauth = Yii::$app->get('eauth')->getIdentity($serviceName);
I get the following error:
Class nodge\eauth\EAuth does not exist
What am I doing wrong? Any help?
Update:
This is my config:
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
'eauth' => [
'class' => 'nodge\eauth\EAuth',
'popup' => true, // Use the popup window instead of redirecting.
'cache' => false, // Cache component name or false to disable cache. Defaults to 'cache' on production environments.
'cacheExpire' => 0, // Cache lifetime. Defaults to 0 - means unlimited.
'httpClient' => [
// uncomment this to use streams in safe_mode
//'useStreamsFallback' => true,
],
'services' => [// You can change the providers and their classes.
'google' => [
// register your app here: https://code.google.com/apis/console/
'class' => 'nodge\eauth\services\GoogleOAuth2Service',
'clientId' => '...',
'clientSecret' => '...',
'title' => 'Google',
],
'facebook' => [
// register your app here: https://developers.facebook.com/apps/
'class' => 'nodge\eauth\services\FacebookOAuth2Service',
'clientId' => '---',
'clientSecret' => '---',
],
'yahoo' => [
'class' => 'nodge\eauth\services\YahooOpenIDService',
//'realm' => '*.example.org', // your domain, can be with wildcard to authenticate on subdomains.
],
],
],
],

Yii2 Moving folder mdm-admin of mdmsoft and xml view appeared

I'm using Yii2 to develop my web app. But when I using yii2-admin of mdmsoft with version 3 for prettyURL, I move folder of yii2-admin to modules folder, and change main.php like this:
'bootstrap' => [
'admin'
],
'authManager' => [
'class' => 'yii\rbac\DbManager', // or use 'yii\rbac\DbManager'
],
'modules' => [
'rbac' => [
'class' => 'app\modules\rbac\Module',
'layout' => '#backend/views/layouts/admin',
'controllerMap' => [
'assignment' => [
'class' => 'app\modules\rbac\controllers\AssignmentController',
]
],
]
],
],
'as access' => [
'class' => 'mdm\admin\classes\AccessControl',
'allowActions' => [
'*',
]
],
But when I access mydomain/rbac/assignment or mydomain.com/rbac/route ,... it's just a xml view, nothing more?
How I can fix it?

How to maintain different log files for different purposes in Yii2

I am using Yii2 for a project. I have a class for consuming a third party service. This class has two methods sendRequest and processResponse. I would like to maintain separate logs for payload in sendRequest before actually sending it and another log for the raw response data received in processResponse before doing any processing. Additionally I would like log rotation on both logs as the files may grow indefinitely and want both files to be separate from the default app.log. Is this possible? How may I implement this using Yii2 APIs?
I eventually reverted back to using Yii2 logger by adding 2 additional file targets in my #app/config/main.php. The file targets had categories = ['orders'] and ['pushNotifications'] respectively so that in my code I use:
Yii::info($message, 'pushNotifications');
or
Yii::info($message, 'orders');
Here is my log config:
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
[
'class' => 'yii\log\FileTarget',
'levels' => ['info'],
'categories' => ['orders'],
'logFile' => '#app/runtime/logs/Orders/requests.log',
'maxFileSize' => 1024 * 2,
'maxLogFiles' => 20,
],
[
'class' => 'yii\log\FileTarget',
'levels' => ['info'],
'categories' => ['pushNotifications'],
'logFile' => '#app/runtime/logs/Orders/notification.log',
'maxFileSize' => 1024 * 2,
'maxLogFiles' => 50,
],
],
],
Since I wasn't quite sure how to configure Yii2 logger to do what I wanted, and googling the subject wasn't much help I decided to go with a third-party logger. The one I chose was Monolog. This functionality was only needed in one class so I create a static getLogger method which returned an instance of Monolog\Logger.
public static function getLogger($name) {
$logger = new \Monolog\Logger($name);
$logger->pushHandler(new \Monolog\Handlers\RotatingFileHandle(Yii::getAlias("#app/runtime/logs/$name.log")), \Monolog\Logger::INFO);
return $logger;
}
Then in sendRequest method I use:
static::getLogger('orders')->info($outgoingXmlPayload.$curlResponseXml);
In the processResponse method I use:
static::getLogger('pushNotifications')->info($notificationXml);
I will be glad to hear(or read) from anyone who has a better solution still. Thanks.
--Ab
Asterisk * may also come handy if we need to collect more subcategories into a cummulative file:
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'flushInterval' => 100, // may prevent from memory exhaustion
'targets' => [
[
'class' => 'yii\log\FileTarget',
'categories' => ['eshop1*'],
'logFile' => '#app/runtime/logs/eshop1.log',
'logVars' => [], // don't log global vars
],
[
'class' => 'yii\log\FileTarget',
'categories' => ['eshop2*'],
'logFile' => '#app/runtime/logs/eshop2.log',
'logVars' => ['GET', 'POST'], // log some globals
'exportInterval' => 100, // may prevent from memory exhaust
],
],
],
This work for me, for dev log
'components' => [
'log' => [
'traceLevel' => YII_DEBUG ? 10 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'logFile' => '#runtime/logs/dev.log',
'categories' => ['dev'],
'levels' => ['trace'],
],
],
],
it's used
Yii::debug('log step 1', 'dev');

Categories