I wanted to split manager and frontend:
root/manager/controllers/SiteController.php
namespace manager\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;
class SiteController extends Controller
{
public function actionIndex()
{
echo 'hallo';
//return $this->render('index');
}
}
root/manager/config/web.php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'manager\controllers',
'bootstrap' => ['log'],
'modules' => [
'manager' => [
'class' => 'manager\Module',
],
],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'X',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => require(__DIR__ . '/db.php'),
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'' => 'site/index',
'fragebogen/erstellung/<id>' => 'questionary/creation',
'fragebogen/erstellung' => 'questionary/creation',
'auftraege-importieren' => 'upload/jobs',
'auftraege-erfolgreich-importiert' => 'upload/jobssuccess',
],
],
],
'params' => $params,
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = 'yii\debug\Module';
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = 'yii\gii\Module';
}
return $config;
root/manager/web/index.php
<?php
// comment out the following two lines when deployed to production
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
require(__DIR__ . '/../../vendor/autoload.php');
require(__DIR__ . '/../../vendor/yiisoft/yii2/Yii.php');
$config = require(__DIR__ . '/../config/web.php');
(new yii\web\Application($config))->run();
And i get this error:
exception 'yii\base\InvalidRouteException' with message 'Unable to resolve the request "site/error".' in /kunden/xxx/xxx/vendor/yiisoft/yii2/base/Module.php:461 Stack trace:
#0 /kunden/xxx/xxx/vendor/yiisoft/yii2/web/ErrorHandler.php(80): yii\base\Module->runAction('site/error')
#1 /kunden/xxx/xxx/vendor/yiisoft/yii2/base/ErrorHandler.php(95): yii\web\ErrorHandler->renderException(Object(yii\web\NotFoundHttpException))
#2 [internal function]: yii\base\ErrorHandler->handleException(Object(yii\web\NotFoundHttpException))
#3 {main} Previous exception: exception 'yii\base\InvalidRouteException' with message 'Unable to resolve the request "site/index".' in /kunden/xxx/xxx/vendor/yiisoft/yii2/base/Module.php:461 Stack trace:
#0 /kunden/xxx/xxx/vendor/yiisoft/yii2/web/Application.php(83): yii\base\Module->runAction('site/index', Array)
#1 /kunden/xxx/xxx/vendor/yiisoft/yii2/base/Application.php(375): yii\web\Application->handleRequest(Object(yii\web\Request))
#2 /kunden/xxx/xxx/manager/web/index.php(12): yii\base\Application->run()
#3 {main}
Next exception 'yii\web\NotFoundHttpException' with message 'Unable to resolve the request "site/index".' in /kunden/xxx/xxx/vendor/yiisoft/yii2/web/Application.php:95 Stack trace:
#0 /kunden/xxx/xxx/vendor/yiisoft/yii2/base/Application.php(375): yii\web\Application->handleRequest(Object(yii\web\Request))
#1 /kunden/xxx/xxx/manager/web/index.php(12): yii\base\Application->run()
#2 {main}
is this topic resolved?
If not, check your bootstrap file in common/config/bootstrap.php.
If your application is trying to use a path alias and it can't be resolved you will get the following exception!
exception 'yii\base\InvalidRouteException' with message 'Unable to resolve the request "site/error".
Example
wrong path is
Yii::setAlias('backend', dirname(dirname(DIR)) . 'backend');
correct path is
Yii::setAlias('backend', dirname(dirname(DIR)) . '/backend');
I think controllerNamespace may be deprectated in Yii2?
Can you replace that in your config, and use a controllerMap?
'controllerMap' => [
'site' => 'manager\controllers\SiteController',
],
Try removing the url rules, you might have to define the default rule to include the module name of at least. See this Custom URL rules with modules in Yii2
EDIT
Take a look at my installations instructions for my module https://github.com/Mihai-P/yii2-core
In short, not sure what controllerNamespace does there, you should remove it. I do something similar here: https://github.com/Mihai-P/yii2-core/blob/master/Module.php
Afterwards this
'class' => 'manager\Module'
I do not think that will work, where is the manager namespace? How would Yii know to look for it? I use composer to add the namespace in the autoloader, you should probably do something like that manually. Tell Yii that manager means your manager folder, afterwards it will find the controllers.
Also this might help, creating an alias to that folder https://github.com/Mihai-P/yii2-core#note-2
There are some config settings which look questionable to me, first
'modules' => [
'manager' => [
'class' => 'manager\Module',
],
],
Since you've created a separate app, you should remove this setting. From your screenshot there
are also no modules in the manager application.
For debugging, just set enablePrettyUrl URL to false and reeable it after it is working without
nice URLs.
You may also need set an alias in bootstrap.php for manager, not sure about that, but worth a try.
From your error message I'd say that the application is not able to load the SiteController at all,
because site/error fails also.
Addon: Personally, I'd recommend just one app per project, but I know that this a controversial topic.
It just looked to me, like you had that and were switching to two apps for some reason. If you just want to
apply a custom theme to your manager, you could easily do that by module configuration
...
I guess you dont have an alias to your application folder. Maybe autoloading component cannot find your controller file. You can add an alias in your config file doing:
\Yii::setAlias(’#manager’, dirname(__FILE__).'/..');
But I think the best way is to create another module for manager instead of dividing into different namespaces.
I have observed that this error generally occurs due to mis-configuration or due to case sensitive names of classes and namespaces. In my case the error was due to the configuration of ii8n component. I was using the following configuration
'i18n' => [
'translations' => [
'*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#backend/messages',
'sourceLanguage' => 'en-US',
'forceTranslation'=> true,
],
],
],
The issue was resolved after I removed the configuration
I guess you dont have an alias to manager folder.
add an alias in your common\config\bootstrap.php.
Yii::setAlias('#manager', dirname(dirname(__DIR__)) . '/manager');
so your common\config\bootstrap.php file should look like:
Yii::setAlias('#common', dirname(__DIR__));
Yii::setAlias('#frontend', dirname(dirname(__DIR__)) . '/frontend');
Yii::setAlias('#backend', dirname(dirname(__DIR__)) . '/backend');
Yii::setAlias('#console', dirname(dirname(__DIR__)) . '/console');
Yii::setAlias('#manager', dirname(dirname(__DIR__)) . '/manager');
Related
I tried to create a mongodb logging channel
'mongo' => [
'driver' => 'monolog',
'handler' => \Monolog\Handler\MongoDBHandler::class,
'formatter' => \Monolog\Formatter\MongoDBFormatter::class,
'handler_with' => [
'mongo' => new \MongoDB\Client("mongodb://localhost:27017"),
'database' => 'testdb',
'collection' => 'testcoll'
]
],
However, im getting error:
Illuminate\Contracts\Container\BindingResolutionException(code: 0): Unresolvable dependency resolving [Parameter #0 [ <required> $mongodb ]] in class Monolog\Handler\MongoDBHandler
The error is only resolved when I tried to add type hint to the class constructor but obviously I can't do that since it's a package:
public function __construct(Client<<if I add this it works>> $mongodb, string $database, string $collection, $level = Logger::DEBUG, bool $bubble = true)
Any solution for this?
So, I wanted to add here a complete answer because this post is the first one that shows up when looking for adding a mongo logger, and since the answer is buried in the comments, I wanted to add a proper answer.
The solution was to change the key mongo to mongodb in the handler_with array.
Leaving the working code like this:
'mongo' => [
'driver' => 'monolog',
'handler' => \Monolog\Handler\MongoDBHandler::class,
'formatter' => \Monolog\Formatter\MongoDBFormatter::class,
'handler_with' => [
'mongodb' => new \MongoDB\Client("mongodb://localhost:27017"),
'database' => 'testdb',
'collection' => 'testcoll'
]
],
Also, you could add the following element at the same level as formatter to set a custom max level of nesting. This is because, by default, the document stored cannot have a depth greater than 3, and it's automatically converted to "[...]" in the log.
'formatter_with' => [
'maxNestingLevel' => 10
],
Warning, in the probable event of a recursion, or an incredibly deep array, it can cause problems in mongo, because it doesn't support more than 100 levels of nesting, source.
According to the Laravel 8.x doc:
'mongo' => [
'driver' => 'monolog',
'handler' => \Monolog\Handler\MongoDBHandler::class,
'formatter' => \Monolog\Formatter\MongoDBFormatter::class,
'with' => [ // <-- This is `with` instead of `handler_with`
// 'mongodb' => new \MongoDB\Client("mongodb://localhost:27017"), <-- This line will cause an error in `php artisan config:cache`
'database' => 'testdb',
'collection' => 'testcoll'
],
],
So you need to configure the service for MongoDBHandler. as you mentioned with a look at the handler source code the first argument is $mongodb.
public function __construct($mongodb, string $database, string $collection, $level = Logger::DEBUG, bool $bubble = true)
and to be able to resolve this dependency we can configure service container:
// AppServiceProvider.php
// ...
public function register() {
$this->app->when(\Monolog\Handler\MongoDBHandler::class)
->needs('$mongodb')
->give(app(
\MongoDB\Client::class,
[
'uri' => 'mongodb://localhost:27017'
]
));
}
// ...
I am trying to see the traceLine on Yii2 debug bar like explains in (https://github.com/yiisoft/yii2-debug#open-files-in-ide), but I can't see it.
I have Yii2 2.0.28 and debug-bar 2.1.9 with php 7.2.19
For example: is there any way, inspecting any debug bar’s panel, to know which line of my code thrown a trace/profile action in the debug bar?
Or how can I see where is located any query I am seeing in the database panel?
My config:
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
'traceLine' => '{file}:{line}',
'allowedIPs' => ['*'],
'panels' => [
'db' => [
'class' => 'yii\debug\panels\DbPanel',
'defaultOrder' => [
'seq' => SORT_ASC
],
'defaultFilter' => [
'type' => 'SELECT'
]
],
],
];
There are two properties in configuration that affect how the files are displayed in logs in debug bar.
1) traceLine property of debug module. This property contains a template for displaying single line of trace.
In configuration it may look like this
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
'traceLine' => '{file}:{line}',
// ... other debug module configurations
]
2) traceLevel property of log component. This affect how many calls will be displayed in trace. The calls of framework's classes are not displayed in debug toolbar, only your files are displayed.
The configuration might look like this
'components' => [
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
// ... other log component configurations
],
// ... other components
],
In the example the traceLevel depends on YII_DEBUG constant. This is used to avoid performance issues in production environments. This is also how traceLevel is set in default yii2 application templates.
The YII_DEBUG constant is usually set in index.php file like this
defined('YII_DEBUG') or define('YII_DEBUG', true);
I set up an i18n page, where I translate messages using yii\i18n\PhpMessageSource with the following config part:
(config/web.php)
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['debug'],
'language' => 'de-DE',
'components' => [
'i18n' => [
'translations' => [
'app*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#app/messages',
'fileMap' => [
'app' => 'app.php',
],
'forceTranslation' => true,
],
],
]]
...byt the way: this works fine.
For a kind of static content -like an imprint-, I like to use an complete translated view.
So I added some sub-directories in the views - folder, with the view insight:
#app/views/myController/de-DE/myview.php
#app/views/myController/en-US/myview.php
So my action does the following:
public function actionImpressum() {
\Yii::$app->language = 'en-US';
return $this->render('myview');
}
...which results in an invalid parameter
yii\base\InvalidParamException: The view file does not
exist: /path/to/my/app/views/myCtrl/myview.php
This error is valid, because there is no view at this path. But shouldn't the render() method use the path for the translation views, like:
/path/to/my/app/views/myCtrl/en-US/myview.php ??
Is there something I forgot?
Thank you.
Since there is no sourceLanguage set in your configuration I assume you have not changed it and the source language of your app is en-US (default one).
When the source language is the same as target language view is not translated.
See documentation about this:
Note: If the target language is the same as source language original view will be rendered regardless of presence of translated view.
So for en-US it looks for /path/to/my/app/views/myCtrl/myview.php file.
Maybe exist solution to skip 404 exceptions ? I'mean not store this messages in log file ?
2015/04/09 12:28:52 [error] [exception.CHttpException.404] exception 'CHttpException' with message 'Невозможно обработать запрос "offer/downloadOffer".' in /var/www/yii/framework/web/CWebApplication.php:286
Stack trace:
#0 /var/www/yii/framework/web/CWebApplication.php(141): CWebApplication->runController('offer/downloadO...')
#1 /var/www/yii/framework/base/CApplication.php(184): CWebApplication->processRequest()
#2 /var/www/LAP/www/index.php(16): CApplication->run()
#3 {main}
REQUEST_URI=/offer/downloadOffer
For Yii 2.0, you can make your config/main.php like this:
return [
'components' => [
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
'except' => ['yii\web\HttpException:404'],
],
],
],
],
];
For Yii 1.1, the correct way to exclude a category is to use the except key. Prepending a ! in the categories key as per the accepted answer will actually result in only matching categories that start with a !. So whilst it might appear to work, you're actually going to be suppressing all categories. See the filterAllCategories() function of the source code - there's no processing of the ! character, only for the * wildcard: GitHub Source.
I tried the !exception.CHttpException.404 approach in the accepted answer and thought I'd solved the issue of hiding the 404 errors, but then I realised after much hair pulling that this was resulted in no logs being logged!
The correct syntax to ignore a category is:
array(
'class' => 'CFileLogRoute',
'except' => 'exception.CHttpException.404'
)
Solution is exclude categories.
array(
'class' => 'CFileLogRoute',
'categories' => '!exception.CHttpException.404'
),
array(
'class' => 'CEmailLogRoute',
'categories' => '!exception.CHttpException.*'
),
EDIT: Yup, is bug.
I suspect this is a bug, so I've submitted it as an issue at https://github.com/zendframework/zf2/issues/6051, but just in case it's just me being stupid it doesn't hurt to ask here as well. :)
After upgrading ZF2 from 2.2.6 to 2.3.0 I'm receiving the following series of uncaught exceptions inside Zend\Di\Di:
Zend\Di\Exception\RuntimeException: Invalid instantiator of type "NULL" for "Zend\I18n\Translator\TranslatorInterface". in /path/to/vendor/zendframework/zendframework/library/Zend/Di/Di.php on line 305
Zend\ServiceManager\Exception\ServiceNotCreatedException: An exception was raised while creating "Zend\I18n\Translator\TranslatorInterface"; no instance returned in /path/to/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php on line 909
Zend\ServiceManager\Exception\ServiceNotCreatedException: An abstract factory could not create an instance of zendi18ntranslatortranslatorinterface(alias: Zend\I18n\Translator\TranslatorInterface). in /path/to/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php on line 1070
Zend\ServiceManager\Exception\ServiceNotCreatedException: An exception was raised while creating "MvcTranslator"; no instance returned in /path/to/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php on line 909
Unfortunately, I can't work out why exactly this is happening, but the I18n module worked fine prior to the upgrade. I have the i18n extension installed and loaded correctly.
I have this in module/Application/config/module.config.php
'service_manager' => [
'aliases' => [
'translator' => 'MvcTranslator',
],
],
and this in each module's module.config.php
'translator' => [
'translation_file_patterns' => [
[
'type' => 'gettext',
'base_dir' => __DIR__ . '/../language',
'pattern' => '%s.mo',
],
],
],
The only DI configuration I have so far is this:
'di' => [
'instance' => [
'Zend\View\HelperLoader' => [
'parameters' => [
'map' => [
'zfcUserIdentity' => 'ZfcUser\View\Helper\ZfcUserIdentity',
'zfcUserLoginWidget' => 'ZfcUser\View\Helper\ZfcUserLoginWidget',
],
],
],
],
],
Does 2.3.0 add a requirement to add additional configuration to the DI block in order for I18n to work properly? This isn't reflected in the documentation and I haven't been able to work it out from reading the code so far, but from the exceptions that are being thrown it looks like it's actually trying to create an instance of Zend\I18n\Translator\TranslatorInterface itself rather than Zend\I18n\Translator\Translator as it did previously?
Anyone got any ideas?
Answer found on https://github.com/zendframework/zf2/pull/5959:
In DiAbstractServiceFactory, the following function needs to be changed from:
public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
{
return $this->instanceManager->hasSharedInstance($requestedName)
|| $this->instanceManager->hasAlias($requestedName)
|| $this->instanceManager->hasConfig($requestedName)
|| $this->instanceManager->hasTypePreferences($requestedName)
|| $this->definitions->hasClass($requestedName);
}
to:
public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
{
if ($this->instanceManager->hasSharedInstance($requestedName)
|| $this->instanceManager->hasAlias($requestedName)
|| $this->instanceManager->hasConfig($requestedName)
|| $this->instanceManager->hasTypePreferences($requestedName)
) {
return true;
}
if (! $this->definitions->hasClass($requestedName) || interface_exists($requestedName)) {
return false;
}
return true;
}
I believe this has been / is being pull-requested, so it should be included in the next update to ZF2.3.