Yii2 restful api object not found error - php

I tried to install RESTful API module from this http://budiirawan.com/setup-restful-api-yii2/ and I am getting error
Object not found!
I tried setting mod_rewrite and also AllowOverride All configuration.
I also have connected it to correct database and that database has country table in it.
I also have .htaccess file and here is my api/config/main.php file
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-api',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'modules' => [
'v1' => [
'basePath' => '#app/modules/v1',
'class' => 'api\modules\v1\Module'
]
],
'components' => [
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => false,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'v1/country',
'tokens' => [
'{id}' => '<id:\\w+>'
]
]
],
]
],
'params' => $params,
];
Here is the model Country
<?php
namespace api\modules\v1\models;
use yii\db\ActiveRecord;
/**
* Country Model
*
* #author Budi Irawan <deerawan#gmail.com>
*/
class Country extends ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'country';
}
/**
* We use the primary function because we don't use integer auto increment as a primary key.
* #inheritdoc
*/
public static function primaryKey()
{
return ['code'];
}
/**
* To let Yii know what fields exist on the table.
* Define rules for validation
*/
public function rules()
{
return [
[['code', 'name', 'population'], 'required']
];
}
}
I still get the same error while accessing it through http://localhost/yii2-api/api/v1/countries.

According to tutorial you have to use url :
http://localhost/yii2-api/api/web/v1/countries
Instead of
http://localhost/yii2-api/api/v1/countries

In my case,
the mysql table had compound primary key (made by mistake),
and only GET /v1/othertable/1 failed with this error, while other routes are working.
When I sorted that indexes through PhpMyAdmin it started to work.

Related

Yii Console Script, Login to User [duplicate]

I am trying to run a console controller from the terminal, but i am getting this errors every time
Error: Getting unknown property: yii\console\Application::user
here is the controller
class TestController extends \yii\console\Controller {
public function actionIndex() {
echo 'this is console action';
} }
and this is the concole config
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'modules' => [],
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
],
'params' => $params];
I tried running it using these commands with no luck
php yii test/index
php yii test
php ./yii test
can anyone help please?
Console application does not have Yii->$app->user. 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'
],
.......
]
More info about your problem see this : Link
OR
Visit following link :
Yii2 isGuest giving exception in console application
Note : There's no session in console application.
Set in \console\config\main.php
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'user' => [
'class' => 'yii\web\User',
'identityClass' => 'app\models\Credential',// class that implements IdentityInterface
//'enableAutoLogin' => true,
],
],
'params' => $params,
];
now in your \console\controller\AbcController.php add init method
public function init() {
parent::init();
Yii::$app->user->setIdentity(Credential::findOne(['id'=><cronloginid>]));
}
create a cron login and pass that login id in variable with this config your Blameable Behavior of yii2 will work
As #GAMITG said, you must config user component in config file, but unfortunately, you couldn't access session in console, that's because session is not available in console. Maybe you could solve the problem like this:
$user_id = isset(Yii::$app->user->id) ? Yii::$app->user->id : 0;

yii2 - frontend to backend and backend to frontend controller config files + .htaccess - COMPLETLY CONFIGURATION

I'm trying to completely manage my page with .htaccess file and two links/button or redirect:
one from frontend to backend
one from backend to frontend
Hope that is clearly enough.
My environment is DEV as I'm working localy if that is so difference.
All I tried:
https://www.yiiframework.com/forum/index.php/topic/60118-creating-links-from-backend-to-frontend-and-frontend-to-backend/
From Backend to Frontend Yii2 Advanced App
https://github.com/yiisoft/yii2/issues/1578
https://www.youtube.com/watch?v=nvMlc1lCOOo
And I'm a bit confused with .htaccess files and urlManager so appreciate any help a lot.
Let's check the files :
DIRECTORY ROOT & COMMON
/.htacces
#prevent directory listing
Options -Indexes
IndexIgnore */*
#follow symbolic links
Options FollowSymlinks
RewriteEngine on
RewriteRule ^admin(/.+)?$ backend/web/$1 [L,PT]
RewriteRule ^(.+)?$ frontend/web
/common/config/main.php
return [
'aliases' => [
'#bower' => '#vendor/bower-asset',
'#npm' => '#vendor/npm-asset',
],
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
],
];
FRONTEND & FRONTEND CONTROLLER
/frontend/.htacces
RewriteEngine on
#if directory or a file exist, use the request directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
#otherwise, forward to index.php
RewriteRule . index.php
/frontend/config/main.php
$params = array_merge(
require __DIR__ . '/../../common/config/params.php',
require __DIR__ . '/../../common/config/params-local.php',
require __DIR__ . '/params.php',
require __DIR__ . '/params-local.php'
);
return [
'id' => 'app-frontend',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'frontend\controllers',
'components' => [
'request' => [
'csrfParam' => '_csrf-frontend',
],
// main - used to generate and parse URLs to frontend from
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'baseUrl' => '/frontend/web',
'rules' => [
'/' => 'site/index',
'home' => 'site/home',
'about' => 'site/about',
'moje-prace' => 'site/moje-prace',
'umow-wizyte' => 'rezerwacje/create',
'contact' => 'site/contact',
'login' => 'site/login',
'signup' => '/site/signup',
],
],
// slave - used to generate URLs to backend from frontend app
'urlManagerBackend' => [
'class' => 'yii\web\urlManager',
'baseUrl' => '/admin',
'enablePrettyUrl' => true,
'showScriptName' => false,
]
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
],
'session' => [
// this is the name of the session cookie used for login on the frontend
'name' => 'advanced-frontend',
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
],
'params' => $params,
];
/frontend/controllers/SiteController.php
namespace frontend\controllers;
use Yii;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
/**
* Site controller
*/
class SiteController extends Controller
{
/**
* {#inheritdoc}
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout', 'index', 'home', 'contact', 'about'],
'rules' => [
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['#'],
],
[
'actions' => ['index'],
'allow' => true,
'roles' => ['#'],
],
[
'actions' => ['home'],
'allow' => true,
'roles' => ['#'],
],
[
'actions' => ['contact'],
'allow' => true,
'roles' => ['#'],
],
[
'actions' => ['about'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
/**
* {#inheritdoc}
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
/**
* Displays homepage.
*
* #return mixed
*/
public function actionIndex()
{
if (!Yii::$app->user->isGuest) {
$this->layout = 'main';
return $this->render('home');
}
return $this->goHome();
}
/**
* Displays about page.
*
* #return mixed
*/
public function actionHome()
{
return $this->render('home');
}
/**
* Logs in a user.
*
* #return mixed
*/
public function actionLogin()
{
$this->layout = 'welcome';
if (!Yii::$app->user->isGuest) {
$this->layout = 'main';
return $this->render('home');
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
$this->layout = 'main';
return $this->render('home');
}
else {
$model->password = '';
return $this->render('login', [
'model' => $model,
]);
}
}
/**
* Logs out the current user.
*
* #return mixed
*/
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
/**
* Displays contact page.
*
* #return mixed
*/
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
}
else {
Yii::$app->session->setFlash('error', 'There was an error sending your message.');
}
return $this->refresh();
}
else {
return $this->render('contact', [
'model' => $model,
]);
}
}
/**
* Displays about page.
*
* #return mixed
*/
public function actionAbout()
{
return $this->render('about');
}
/**
* Signs user up.
*
* #return mixed
*/
public function actionSignup()
{
$this->layout = 'welcome';
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
$this->layout = 'main';
return $this->actionHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
BACKEND & BACKEND CONTROLLER
/backend/.htacces
RewriteEngine on
#if directory or a file exist, use the request directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
#otherwise, forward to index.php
RewriteRule . index.php
/backend/config/main.php
$params = array_merge(
require __DIR__ . '/../../common/config/params.php',
require __DIR__ . '/../../common/config/params-local.php',
require __DIR__ . '/params.php',
require __DIR__ . '/params-local.php'
);
return [
'id' => 'app-backend',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'backend\controllers',
'bootstrap' => ['log'],
'homeUrl' => '/administrator',
'modules' => [],
'components' => [
'request' => [
'csrfParam' => '_csrf-backend',
'baseUrl' => '/administrator',
],
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-backend', 'httpOnly' => true],
],
'session' => [
// this is the name of the session cookie used for login on the backend
'name' => 'advanced-backend',
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
// main - used to generate and parse URLs to backend from backend app
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'baseUrl' => '/backend/web',
],
// slave - used to generate URLs to frontend from backend app
'urlManagerFrontend' => [
'class' => 'yii\web\urlManager',
'enablePrettyUrl' => true,
'showScriptName' => false,
'baseUrl' => '/',
'rules' => [
'/' => 'site/index',
'home' => 'site/home',
'about' => 'site/about',
'moje-prace' => 'site/moje-prace',
'umow-wizyte' => 'rezerwacje/create',
'contact' => 'site/contact',
'login' => 'site/login',
'signup' => 'site/signup',
],
],
'params' => $params,
];
/backend/controllers/SiteController.php
namespace backend\controllers;
use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
/**
* Site controller
*/
class SiteController extends Controller
{
/**
* {#inheritdoc}
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'actions' => ['logout', 'index'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
/**
* {#inheritdoc}
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
];
}
/**
* Displays homepage.
*
* #return string
*/
public function actionIndex()
{
return $this->render('index');
}
/**
* Login action.
*
* #return string
*/
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
$model->password = '';
return $this->render('login', [
'model' => $model,
]);
}
}
/**
* Logout action.
*
* #return string
*/
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
}
VHOST & APACHE.CONF
apache2.conf
<Directory />
Options FollowSymLinks
AllowOverride All
Require all granted
</Directory>
<Directory /usr/share>
AllowOverride All
Require all granted
</Directory>
<Directory /home/user/project>
Options FollowSymLinks
AllowOverride All
Require all granted
</Directory>
vhost
<VirtualHost *:80>
ServerAdmin admin#prst.app
ServerName pp.test
DocumentRoot /home/user/project/pp/
<Directory "/home/user/project/pp/">
Options FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/pp__error.log
CustomLog ${APACHE_LOG_DIR}/pp_access.log combined
</VirtualHost>
I can not create the hyperlink in a view or redirect in controller from frontend to backend, and from backend to frontend.
I'm assuming that your frontend is at http://localhosts and your backend at http://localhosts/admin. If your rewrite rules does not work correctly, you may try use symlinks for this - at least for me it was always simpler and less problematic way of handling frontend/backend URLs on shared hosting.
You always have 2 UrlManager components: main (for current environment) and slave (for second environment, for example for backend in frontend app). So in frontend/config/main.php you will have something like:
// ...
// main - used to generate and parse URLs to frontend from frontend app
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'baseUrl' => '/',
'rules' => [
'/' => 'site/index',
'home' => 'site/home',
'about' => 'site/about',
'moje-prace' => 'site/moje-prace',
'umow-wizyte' => 'rezerwacje/create',
'contact' => 'site/contact',
'login' => 'site/login',
'signup' => 'site/signup',
],
],
// slave - used to generate URLs to backend from frontend app
'urlManagerBackend' => [
'class' => 'yii\web\urlManager',
'baseUrl' => '/admin',
'enablePrettyUrl' => true,
'showScriptName' => false,
],
// ...
And in backend/config/main.php:
// ...
// main - used to generate and parse URLs to backend from backend app
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'baseUrl' => '/admin',
],
// slave - used to generate URLs to frontend from backend app
'urlManagerFrontend' => [
'class' => 'yii\web\urlManager',
'enablePrettyUrl' => true,
'showScriptName' => false,
'baseUrl' => '/',
'rules' => [
'/' => 'site/index',
'home' => 'site/home',
'about' => 'site/about',
'moje-prace' => 'site/moje-prace',
'umow-wizyte' => 'rezerwacje/create',
'contact' => 'site/contact',
'login' => 'site/login',
'signup' => 'site/signup',
],
],
// ...
As you can see, they're swapped - main UrlManager from frontend app is slave in backend app. Depending on current and target environment, you're using different URL manager.
If you want to generate URL to frontend from backend app:
Yii::$app->urlManagerFrontend->createUrl('site/index');
// result: http://localhost
If you want to generate URL to backend from backend app:
Yii::$app->urlManager->createUrl('site/index');
// result: http://localhost/admin/site/index
If you want to generate URL to backend from frontend app:
Yii::$app->urlManagerBackend->createUrl('site/index');
// result: http://localhost/admin/site/index
If you want to generate URL to frontend from frontend app:
Yii::$app->urlManager->createUrl('site/index');
// result: http://localhost
Finally it's done ! On the fresh yii2 advanced i set up connections between frontend and backend, but still have a problem with pretty url in both "sides".
backend/.htaccess
RewriteEngine on
#if directory or a file exist, use the request directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
#otherwise, forward to index.php
RewriteRule . index.php
backend/config/main.php
use \yii\web\Request;
$baseUrl = str_replace('/backend/web', '/backend/web', (new Request)->getBaseUrl());
$frontEndBaseUrl = str_replace('/backend/web', '/frontend/web', (new Request)->getBaseUrl());
$params = array_merge(
require __DIR__ . '/../../common/config/params.php',
require __DIR__ . '/../../common/config/params-local.php',
require __DIR__ . '/params.php',
require __DIR__ . '/params-local.php'
);
return [
'id' => 'app-backend',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'backend\controllers',
'bootstrap' => ['log'],
'modules' => [],
'components' => [
'request' => [
'csrfParam' => '_csrf-backend',
],
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-backend', 'httpOnly' => true],
],
'session' => [
// this is the name of the session cookie used for login on the backend
'name' => 'advanced-backend',
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
// main - used to generate and parse URLs to backend from backend app
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'baseUrl' => '/backend/web',
],
// slave - used to generate URLs to frontend from backend app
'urlManagerFrontend' => [
'class' => 'yii\web\urlManager',
'enablePrettyUrl' => true,
'showScriptName' => false,
'baseUrl' => '/',
'rules' => [
'/' => 'site/index',
'home' => 'site/home',
'about' => 'site/about',
'moje-prace' => 'site/moje-prace',
'umow-wizyte' => 'rezerwacje/create',
'contact' => 'site/contact',
'login' => 'site/login',
'signup' => 'site/signup',
],
],
],
'params' => $params,
];
backend links for frontend
simply created with:
$frontendUrl= Yii::$app->urlManagerFrontend->createUrl('//');
echo yii\helpers\Html::a('link to frontend', $frontendUrl);
frontend/.htaccess
RewriteEngine on
#if directory or a file exist, use the request directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
#otherwise, forward to index.php
RewriteRule . index.php
frontend/config/main.php
use \yii\web\Request;
$baseUrl = str_replace('/frontend/web', '/frontend/web', (new Request)->getBaseUrl());
$backEndBaseUrl = str_replace('/frontend/web', '/backend/web', (new Request)->getBaseUrl());
$params = array_merge(
require __DIR__ . '/../../common/config/params.php',
require __DIR__ . '/../../common/config/params-local.php',
require __DIR__ . '/params.php',
require __DIR__ . '/params-local.php'
);
return [
'id' => 'app-frontend',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'frontend\controllers',
'components' => [
'request' => [
'csrfParam' => '_csrf-frontend',
],
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
],
'session' => [
// this is the name of the session cookie used for login on the frontend
'name' => 'advanced-frontend',
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
// main - used to generate and parse URLs to frontend from frontend app
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'baseUrl' => $baseUrl,
'rules' => [
'/' => 'site/index',
'/home' => 'site/home',
'/about' => 'site/about',
'moje-prace' => 'site/moje-prace',
'umow-wizyte' => 'rezerwacje/create',
'contact' => 'site/contact',
'login' => 'site/login',
'signup' => '/site/signup',
],
],
// slave - used to generate URLs to backend from frontend app
'urlManagerBackend' => [
'class' => 'yii\web\urlManager',
'baseUrl' => $backEndBaseUrl,
'enablePrettyUrl' => false,
'showScriptName' => false,
],
],
'params' => $params,
];
frontend links for backend
simply created with:
$backendUrl= Yii::$app->urlManagerBackend->createUrl('//');
echo yii\helpers\Html::a('link to backend', $backendUrl);
In the root directory what means http://localhost/app-name/ i created index.php file for redirecting to frontend while clicking link on backend (to frontend):
/index.php
header("Location: http://pp.test/frontend/web/", true, 301);
exit();
And by now it works so so, but i'm not able to enable pretty url in the backend as it does not works corectlly. And also i do not think that's a good way using redirecting from other file especially from root directory.
Please note, that in common/config/main.php no changes is needed and do not need .htaccess file in the root directory.

yii2 mongodb migration doesn't work

I am using mongodb in yii2 and I want to use it's migration.
this is my model class .
namespace app\models;
use yii\mongodb\ActiveRecord;
class Company extends ActiveRecord
{
/**
* #return array
*/
public static function collectionName()
{
return ['cafegardesh','companies'];
}
/**
* #return array
*/
public function attributes()
{
return ['_id', 'name', 'address', 'status'];
}
/**
* #return array
*/
public function rules()
{
return [
[['name'], 'required'],
];
}
and this is my migration file :
use yii\mongodb\Migration;
class m160904_053937_create_companies_collection extends Migration
{
public function up()
{
}
public function down()
{
echo "m160904_053937_create_companies_collection cannot be reverted.\n";
return false;
}
/*
// Use safeUp/safeDown to run migration code within a transaction
public function safeUp()
{
}
public function safeDown()
{
}
*/
}
and this is my console config file :
Yii::setAlias('#tests', dirname(__DIR__) . '/tests/codeception');
$params = require(__DIR__ . '/params.php');
$db = require(__DIR__ . '/db.php');
$config = [
'id' => 'basic-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'app\commands',
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => $db,
'mongodb' => [
'class' => \yii\mongodb\Connection::class,
'dsn' => 'mongodb://cafegardesh:12345#localhost:27017/cafegardesh',
]
],
'modules' => [
'taxonomy-term'=>[
'class'=> \mhndev\yii2TaxonomyTerm\Module::class
]
],
'params' => $params,
/*
'controllerMap' => [
'fixture' => [ // Fixture generation command line.
'class' => 'yii\faker\FixtureController',
],
],
*/
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
];
}
return $config;
and this is the command I execute :
php yii migrate/up --db=mongodb
and I get following error:
Exception 'yii\base\InvalidConfigException' with message '"mongodb" refers to a yii\mongodb\Connection component. yii\db\Connection is expected.'
in /home/majid/Projects/Gardesh-Tour-Backend/vendor/yiisoft/yii2/di/Instance.php:135
MongoDB component has got it's own migration controller. Use it instead.
In your console configuration add
'controllerMap' => [
'mongodb-migrate' => 'yii\mongodb\console\controllers\MigrateController'
],
Now you can use php yii mongodb-migrate/up.
It takes mongodb component for db as default.

Yii2 - Getting unknown property: yii\console\Application::user

I am trying to run a console controller from the terminal, but i am getting this errors every time
Error: Getting unknown property: yii\console\Application::user
here is the controller
class TestController extends \yii\console\Controller {
public function actionIndex() {
echo 'this is console action';
} }
and this is the concole config
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'modules' => [],
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
],
'params' => $params];
I tried running it using these commands with no luck
php yii test/index
php yii test
php ./yii test
can anyone help please?
Console application does not have Yii->$app->user. 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'
],
.......
]
More info about your problem see this : Link
OR
Visit following link :
Yii2 isGuest giving exception in console application
Note : There's no session in console application.
Set in \console\config\main.php
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'user' => [
'class' => 'yii\web\User',
'identityClass' => 'app\models\Credential',// class that implements IdentityInterface
//'enableAutoLogin' => true,
],
],
'params' => $params,
];
now in your \console\controller\AbcController.php add init method
public function init() {
parent::init();
Yii::$app->user->setIdentity(Credential::findOne(['id'=><cronloginid>]));
}
create a cron login and pass that login id in variable with this config your Blameable Behavior of yii2 will work
As #GAMITG said, you must config user component in config file, but unfortunately, you couldn't access session in console, that's because session is not available in console. Maybe you could solve the problem like this:
$user_id = isset(Yii::$app->user->id) ? Yii::$app->user->id : 0;

Yii 2.0 restful routing 404 issue

I am trying to follow the Yii2.0 example as found here with my simple product table
instead of User.
http://www.yiiframework.com/doc-2.0/guide-rest-quick-start.html
I'm using the basic package, not advanced.
When I try to access localhost/product
I get a 404 error.
When I use localhost/index.php or localhost/index.php/gii
I get the expected result (the default homepage, and the gii tool).
Here is what I'm working with.
The config file web.php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'xxx',
'parsers' => [
'application/json' => 'yii\web\JsonParser',
],
],
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => 'product'],
],
],
'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.
'useFileTransport' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => require(__DIR__ . '/db.php'),
],
'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;
The Model Product.php
namespace app\models;
use yii\db\ActiveRecord;
/**
* This is the model class for table "product".
*
* #property integer $ProductID
* #property string $Name
* #property double $Price
* #property string $ShortDesc
* #property string $LongDesc
* #property string $PicUrl
*/
class Product extends ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'product';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['Price'], 'number'],
[['ShortDesc', 'LongDesc', 'PicUrl'], 'string'],
[['Name'], 'string', 'max' => 60]
];
}
/**
* #inheritdoc
*/
public static function primaryKey()
{
return ['ProductID'];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'ProductID' => 'Product ID',
'Name' => 'Name',
'Price' => 'Price',
'ShortDesc' => 'Short Desc',
'LongDesc' => 'Long Desc',
'PicUrl' => 'Pic Url',
];
}
}
The controller ProductController.php
use yii\rest\ActiveController;
class ProductController extends ActiveController
{
public $modelClass = 'app\models\Product';
}
I have tried to turn off 'enableStrictParsing' and set $pluralize to false, with no luck.
I have also tried adding this .htaccess file which gave me a 500 rather than a 404.
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php
I'm sure I've done something silly here, but anyone willing to point that out will be a huge help.
Thanks!
Just set enableStrictParsing to false in urlManager array.
Scallopboat - I had the same issue. I raised it on the Yii2 forum and got the answer. The url you should use is http://localhost/basic/web/index.php/products.
I was also advised to change 'showScriptName' to true. The advise was that otherwise the links won't generate ok.
It was also suggested I could write some rewrite rules to use a cleaner url.
#scallopboat - I too have a similar problem. I got 404 response for view action.
Solved by following the instruction from,
How to configure urlManager to use rest api with string id
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'region',
'pluralize'=>false,
'tokens' => [ '{id}' => '<id:\\w+>' ]
],
],
Accessed the view action using the below url:
http://localhost/icdp-service/region/[mongo-id]
Hope this helps.
Scallopboat. You can try this way while you do not solve your problem yet.
If you are using Apache as your web server,you should
edit the Apache config file httpd.conf and find blocks like
<Directory>****</Directory> and <Directory "your web root
dir">****</Directory>,modify the AllowOverride None to
AllowOverride All
uncomment the #LoadModule rewrite_module modules/ApacheModuleRewrite.dll
place the .hataccess file in your the base directory of your index.php

Categories