I'm very new to Yii framework.
I did only basic compulsory steps in setting up advance Yii. But it gives the following error when I try load the index.php(localhost:8888/new/advanced/frontend/web/index.php) in frontend as well as the index.php (localhost:8888/new/advanced/backend/web/index.php) in the backend.
Things I have done from the beginning:
Downloaded the advanced Yii framework & extracted it to the htdocs
Run the command php init in the terminal.that's all...
I tried this solution yii2-error-the-view-file-does-not-exist.. but it didn't worked
Error
An Error occurred while handling another error:
exception 'yii\base\InvalidParamException' with message 'The view file does not exist: /Applications/MAMP/htdocs/SMS_Messenger/vendor/yiisoft/yii2/views/errorHandler/exception.php' in /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/base/View.php:226
Stack trace:
#0 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/web/ErrorHandler.php(241): yii\base\View->renderFile('#yii/views/erro...', Array, Object(yii\web\ErrorHandler))
#1 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/web/ErrorHandler.php(112): yii\web\ErrorHandler->renderFile('#yii/views/erro...', Array)
#2 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/base/ErrorHandler.php(109): yii\web\ErrorHandler->renderException(Object(yii\base\InvalidParamException))
#3 [internal function]: yii\base\ErrorHandler->handleException(Object(yii\base\InvalidParamException))
#4 {main}
Previous exception:
exception 'yii\base\InvalidParamException' with message 'The file or directory to be published does not exist: /Applications/MAMP/htdocs/SMS_Messenger/vendor/yiisoft/yii2/assets' in /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/web/AssetManager.php:452
Stack trace:
#0 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/web/AssetBundle.php(179): yii\web\AssetManager->publish('/Applications/M...', Array)
#1 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/web/AssetManager.php(266): yii\web\AssetBundle->publish(Object(yii\web\AssetManager))
#2 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/web/AssetManager.php(237): yii\web\AssetManager->loadBundle('yii\\web\\YiiAsse...', Array, true)
#3 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/web/View.php(284): yii\web\AssetManager->getBundle('yii\\web\\YiiAsse...')
#4 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/web/View.php(289): yii\web\View->registerAssetBundle('yii\\web\\YiiAsse...', NULL)
#5 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/web/AssetBundle.php(123): yii\web\View->registerAssetBundle('frontend\\assets...')
#6 /Applications/MAMP/htdocs/new/advanced/frontend/views/layouts/main.php(13): yii\web\AssetBundle::register(Object(yii\web\View))
#7 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/base/View.php(325): require('/Applications/M...')
#8 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/base/View.php(247): yii\base\View->renderPhpFile('/Applications/M...', Array)
#9 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/base/Controller.php(392): yii\base\View->renderFile('/Applications/M...', Array, Object(frontend\controllers\SiteController))
#10 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/base/Controller.php(378): yii\base\Controller->renderContent('<div class="sit...')
#11 /Applications/MAMP/htdocs/new/advanced/frontend/controllers/SiteController.php(75): yii\base\Controller->render('index')
#12 [internal function]: frontend\controllers\SiteController->actionIndex()
#13 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/base/InlineAction.php(55): call_user_func_array(Array, Array)
#14 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/base/Controller.php(154): yii\base\InlineAction->runWithParams(Array)
#15 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/base/Module.php(454): yii\base\Controller->runAction('', Array)
#16 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/web/Application.php(84): yii\base\Module->runAction('', Array)
#17 /Applications/MAMP/htdocs/new/advanced/vendor/yiisoft/yii2/base/Application.php(375): yii\web\Application->handleRequest(Object(yii\web\Request))
#18 /Applications/MAMP/htdocs/new/advanced/frontend/web/index.php(18): yii\base\Application->run()
#19 {main}
frontend sitecontroller.php
<?php
namespace frontend\controllers;
use Yii;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
class SiteController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout', 'signup'],
'rules' => [
[
'actions' => ['signup'],
'allow' => true,
'roles' => ['?'],
],
[
'actions' => ['logout'],
'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()
{
return $this->render('index');
}
//other codes
My environment is Mac OS 10.11 El capitain
since I'm very newbie to Yii & I haven't changed the default code its hard to figure out the problem.
Hope for any suggestion
You don't have vendor directory.
Run composer from command line. Probably you must first install composer. Then in root dir of advanced project run:
composer install
or
php composer install
Related
I am new on Yii2 and I'm trying to build a restful API.
I need create few custom actions for getting data.
When I call https://localhost/api/v1/record/GetAll using GET method, which will return 404.
Here is the log
[yii\web\HttpException:404] yii\base\InvalidRouteException: Unable to resolve the request: v1/record/getall in /home/demo/vendor/yiisoft/yii2/base/Controller.php:149
Stack trace:
#0 /home/demo/vendor/yiisoft/yii2/base/Module.php(552): yii\base\Controller->runAction()
#1 /home/demo/vendor/yiisoft/yii2/web/Application.php(103): yii\base\Module->runAction()
#2 /home/demo/vendor/yiisoft/yii2/base/Application.php(384): yii\web\Application->handleRequest()
#3 /home/demo/api/web/index.php(18): yii\base\Application->run()
#4 {main}
Next yii\web\NotFoundHttpException: Page not found. in /home/demo/vendor/yiisoft/yii2/web/Application.php:115
Stack trace:
#0 /home/demo/vendor/yiisoft/yii2/base/Application.php(384): yii\web\Application->handleRequest()
#1 /home/demo/api/web/index.php(18): yii\base\Application->run()
#2 {main}
Here is the project directory structure
api
-config
--main.php
-modules
--v1
---controllers
----RecordController.php
---Module.php
-runtime
-web
frontend
backend
common
...
Here is my code
api\config\main.php
...
'urlManager' => [
'class'=>'yii\web\UrlManager',
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => ['v1/record'=>'v1/record'],
//'prefix' => 'record/<id:\\w+>',
'pluralize' => false,
'extraPatterns' => [
'GET,HEAD getAll'=>'getall',
'OPTIONS getAll'=>'options',
],
],
],
],
...
api\modules\v1\controllers\RecordController.php
namespace api\modules\v1\controllers;
use yii\rest\ActiveController;
use common\components\JsonSerializer;
use yii\filters\ContentNegotiator;
use yii\web\Response;
use yii\web\ForbiddenHttpException;
use frontend\models\Record;
class RecordController extends ActiveController
{
public $modelClass = 'frontend\models\Record';
public $serializer = [
'class' => 'common\components\JsonSerializer',
'collectionEnvelope' => 'items',
];
protected function verbs(){
return [
'getAll' => [ 'GET' ],
];
//return $verbs;
}
public function actions()
{
$actions = parent::actions();
$actions['options'] = [
'class' => 'yii\rest\OptionsAction',
];
return $actions;
}
//the custom action - getAll
public function actiongetAll(){
$result = Record::find()
->all();
return $result;
}
}
The default actions[index,view,update,create,delete] are OK, but the custom action cannot get the data.
How can I fix it.
Thanks.
First I would change the action function in your controller to
public function actionGetAll()
Then your URL will be https://localhost/api/v1/record/get-all
and please use this get-all in your rules and verbs.
If you override the url-rule I think you have to use this
'GET,HEAD getAll'=>'v1/record/get-all',
I've been facing this weird error... I set up my laravel passport auth, and login works and provides a token. I'm trying to 'guard' my routes so that only logged in users can access them. I am using 'auth:api' middleware, when a token is provided everything goes well as it should but when it's not I keep getting 'The GET method is not supported for this route. Supported methods: POST.' error and I can't seem to figure out why.
here is my Authenticate.php
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* #param \Illuminate\Http\Request $request
* #return string|null
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
}
here are the routes I have set up
Route::group([
'prefix' => 'auth'
], function () {
Route::post('login', 'Auth\AuthController#login')->name('login');
Route::post('register', 'Auth\AuthController#register');
Route::group([
'middleware' => 'auth:api'
], function () {
Route::get('logout', 'Auth\AuthController#logout');
Route::get('user', 'Auth\AuthController#user');
});
});
Route::get('check', function () {
return response()->json([
'message' => 'YOU'RE IN!'
], 200);
})->middleware('auth:api');
and here is my authController
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
class AuthController extends Controller
{
//
public function login(Request $request)
{
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string'
]);
$credentials = request(['email', 'password']);
if (!Auth::attempt($credentials))
return response()->json([
'message' => 'Unauthorized'
], 401);
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
if ($request->remember_me)
$token->expires_at = Carbon::now()->addWeeks(1);
$token->save();
return response()->json([
'user' => Auth::user(),
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at
)->toDateTimeString()
], 200);
}
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'fName' => 'required|string',
'lName' => 'required|string',
'email' => 'required|string|email|unique:users',
'password' => 'required|string'
]);
if ($validator->fails()) {
$error = $validator->errors()->first();
return response()->json([
'message' => $error
], 404);
}
$user = new User;
$user->first_name = $request->fName;
$user->last_name = $request->lName;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->save();
return response()->json([
'message' => 'Successfully created user!'
], 201);
}
public function logout(Request $request)
{
$request->user()->token()->revoke();
return response()->json([
'message' => 'Successfully logged out'
], 200);
// Auth::logout();
}
public function user(Request $request)
{
return response()->json($request->user());
}
}
when I send my request with a header containing the token it works and I get the "YOU'RE IN" message, when I don't I get the error. I did try to send it as both a POST and a GET request which in fact shouldn't be needed since I have it declared as a GET route.
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException: The GET method is not supported for this route. Supported methods: POST. in file D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Routing\AbstractRouteCollection.php on line 117
#0 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Routing\AbstractRouteCollection.php(103): Illuminate\Routing\AbstractRouteCollection->methodNotAllowed(Array, 'GET')
#1 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Routing\AbstractRouteCollection.php(40): Illuminate\Routing\AbstractRouteCollection->getRouteForMethods(Object(Illuminate\Http\Request), Array)
#2 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Routing\RouteCollection.php(162): Illuminate\Routing\AbstractRouteCollection->handleMatchedRoute(Object(Illuminate\Http\Request), NULL)
#3 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Routing\Router.php(639): Illuminate\Routing\RouteCollection->match(Object(Illuminate\Http\Request))
#4 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Routing\Router.php(628): Illuminate\Routing\Router->findRoute(Object(Illuminate\Http\Request))
#5 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Routing\Router.php(617): Illuminate\Routing\Router->dispatchToRoute(Object(Illuminate\Http\Request))
#6 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(165): Illuminate\Routing\Router->dispatch(Object(Illuminate\Http\Request))
#7 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(128): Illuminate\Foundation\Http\Kernel->Illuminate\Foundation\Http\{closure}(Object(Illuminate\Http\Request))
#8 D:\My Workspace\Laravel\awiz\app\Http\Middleware\Cors.php(18): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#9 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): App\Http\Middleware\Cors->handle(Object(Illuminate\Http\Request), Object(Closure))
#10 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TransformsRequest.php(21): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#11 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Illuminate\Foundation\Http\Middleware\TransformsRequest->handle(Object(Illuminate\Http\Request), Object(Closure))
#12 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TransformsRequest.php(21): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#13 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Illuminate\Foundation\Http\Middleware\TransformsRequest->handle(Object(Illuminate\Http\Request), Object(Closure))
#14 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\ValidatePostSize.php(27): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#15 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Illuminate\Foundation\Http\Middleware\ValidatePostSize->handle(Object(Illuminate\Http\Request), Object(Closure))
#16 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode.php(63): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#17 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode->handle(Object(Illuminate\Http\Request), Object(Closure))
#18 D:\My Workspace\Laravel\awiz\vendor\fruitcake\laravel-cors\src\HandleCors.php(37): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#19 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Fruitcake\Cors\HandleCors->handle(Object(Illuminate\Http\Request), Object(Closure))
#20 D:\My Workspace\Laravel\awiz\vendor\fideloper\proxy\src\TrustProxies.php(57): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#21 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Fideloper\Proxy\TrustProxies->handle(Object(Illuminate\Http\Request), Object(Closure))
#22 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(103): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#23 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(140): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#24 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(109): Illuminate\Foundation\Http\Kernel->sendRequestThroughRouter(Object(Illuminate\Http\Request))
#25 D:\My Workspace\Laravel\awiz\public\index.php(55): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request))
#26 D:\My Workspace\Laravel\awiz\server.php(21): require_once('D:\\My Workspace...')
#27 {main}
EDIT
I did, in fact, try to change the route the middleware is supposed to redirect me to which in turn caused me to face another error... It says the route isn't defined but am pretty sure it is...
Route::get('loginfailed', function () {
return response()->json(['error' => 'unauthenticated']);
});
this is my route definition and this is the new redirectTo function
protected function redirectTo($request)
{
if (!$request->expectsJson()) {
return route('loginfailed');
}
}
this is the error I get now
Symfony\Component\Routing\Exception\RouteNotFoundException: Route [loginfailed] not defined. in file D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Routing\UrlGenerator.php on line 420
#0 D:\My Workspace\Laravel\awiz\vendor\laravel\framework\src\Illuminate\Foundation\helpers.php(768): Illuminate\Routing\UrlGenerator->route('loginfailed', Array, true)
#1 D:\My Workspace\Laravel\awiz\app\Http\Middleware\Authenticate.php(18): route('loginfailed')
You're getting that error because your middleware is supposed to redirect to login route i.e return route('login');
The problem is that your login route is POST i.e Route::post('login', 'Auth\AuthController#login')->name('login');
if you are using postman to do request to your api make sure you add in Headers (Accept - appication/json) so it will show the Unauthenticated message otherwise it will try to redirect if it doesn't expect json
Good afternoon.
I have created my own filter in Yii2 basic project:
class LanguageFilter extends Behavior
{
/**
* #var string
*/
public $shortLanguage;
/**
* Declares event handlers for the [[owner]]'s events.
* #return array events (array keys) and the corresponding event handler methods (array values).
*/
public function events()
{
return [Controller::EVENT_BEFORE_ACTION => 'beforeAction'];
}
/**
* #param ActionEvent $event
* #return bool
* #throws BadRequestHttpException
*/
public function beforeAction($event)
{
if (null === $this->shortLanguage){
throw new BadRequestHttpException('Parameter "shortLanguage" is not defined.');
}
$langModel = Language::find()->where([
'shortName' => $this->shortLanguage
])->one();
if (null === $langModel){
throw new BadRequestHttpException('There are not any data for language: '.$this->shortLanguage);
}
Yii::$app->language = $langModel->locale;
return true;
}
}
And use it in controller:
class BaseController extends Controller
{
/**
* #var string
*/
protected $shortLanguage;
/**
* Initialize.
*/
public function init()
{
$this->defaultAction = 'index';
$this->layout = '#app/views/layouts/base';
$this->shortLanguage = Yii::$app->request->get('shortLanguage');
$this->view->params['shortLanguage'] = $this->shortLanguage;
$this->view->params['pages'] = Page::getMenu();
parent::init();
}
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'language' => [
'class' => LanguageFilter::class,
'shortLanguage' => $this->shortLanguage
],
'access' => [
'class' => AccessControl::class,
'rules' => [
[
'allow' => true,
'actions' => ['reg', 'login'],
'roles' => ['?'],
],
[
'allow' => true,
'actions' => ['logout'],
'roles' => ['#'],
],
[
'allow' => true,
'actions' => ['index', 'about', 'contact'],
'roles' => ['?', '#'],
],
[
'allow' => true,
'actions' => ['error'],
'roles' => ['?', '#'],
],
],
],
'verbs' => [
'class' => VerbFilter::class,
'actions' => [
'index' => ['get'],
'logout' => ['post', 'get'],
],
],
];
}
/**
* #inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
];
}
}
In web configuration file error handler:
'components' => [
...
...
'errorHandler' => [
'errorAction' => 'base/error',
],
...
...
]
But when the filter throws an exception, the error handler displays an error message WITHOUT TEMPLATE !!! And with another mistake.
An Error occurred while handling another error:
yii\web\BadRequestHttpException: There are not any data for language: fr in C:\xampp\htdocs\pack-develop\filters\LanguageFilter.php:44
Stack trace:
#0 [internal function]: app\filters\LanguageFilter->beforeAction(Object(yii\base\ActionEvent))
#1 C:\xampp\htdocs\pack-develop\vendor\yiisoft\yii2\base\Component.php(627): call_user_func(Array, Object(yii\base\ActionEvent))
#2 C:\xampp\htdocs\pack-develop\vendor\yiisoft\yii2\base\Controller.php(274): yii\base\Component->trigger('beforeAction', Object(yii\base\ActionEvent))
#3 C:\xampp\htdocs\pack-develop\vendor\yiisoft\yii2\web\Controller.php(164): yii\base\Controller->beforeAction(Object(yii\web\ErrorAction))
#4 C:\xampp\htdocs\pack-develop\vendor\yiisoft\yii2\base\Controller.php(155): yii\web\Controller->beforeAction(Object(yii\web\ErrorAction))
#5 C:\xampp\htdocs\pack-develop\vendor\yiisoft\yii2\base\Module.php(528): yii\base\Controller->runAction('error', Array)
#6 C:\xampp\htdocs\pack-develop\vendor\yiisoft\yii2\web\ErrorHandler.php(108): yii\base\Module->runAction('base/error')
#7 C:\xampp\htdocs\pack-develop\vendor\yiisoft\yii2\base\ErrorHandler.php(111): yii\web\ErrorHandler->renderException(Object(yii\web\BadRequestHttpException))
#8 [internal function]: yii\base\ErrorHandler->handleException(Object(yii\web\BadRequestHttpException))
#9 {main}
Previous exception:
yii\web\BadRequestHttpException: There are not any data for language: fr in C:\xampp\htdocs\pack-develop\filters\LanguageFilter.php:44
Stack trace:
#0 [internal function]: app\filters\LanguageFilter->beforeAction(Object(yii\base\ActionEvent))
#1 C:\xampp\htdocs\pack-develop\vendor\yiisoft\yii2\base\Component.php(627): call_user_func(Array, Object(yii\base\ActionEvent))
#2 C:\xampp\htdocs\pack-develop\vendor\yiisoft\yii2\base\Controller.php(274): yii\base\Component->trigger('beforeAction', Object(yii\base\ActionEvent))
#3 C:\xampp\htdocs\pack-develop\vendor\yiisoft\yii2\web\Controller.php(164): yii\base\Controller->beforeAction(Object(yii\base\InlineAction))
#4 C:\xampp\htdocs\pack-develop\vendor\yiisoft\yii2\base\Controller.php(155): yii\web\Controller->beforeAction(Object(yii\base\InlineAction))
#5 C:\xampp\htdocs\pack-develop\vendor\yiisoft\yii2\base\Module.php(528): yii\base\Controller->runAction('index', Array)
#6 C:\xampp\htdocs\pack-develop\vendor\yiisoft\yii2\web\Application.php(103): yii\base\Module->runAction('home/index', Array)
#7 C:\xampp\htdocs\pack-develop\vendor\yiisoft\yii2\base\Application.php(386): yii\web\Application->handleRequest(Object(yii\web\Request))
#8 C:\xampp\htdocs\pack-develop\web\index.php(33): yii\base\Application->run()
#9 {main}
The strange thing is that when other filters (AccessControl, VerbFilter) issue exceptions, the error handler displays an error message through the view template normally.
Please help me to understand the reason of it!
It's a filter not behavior, I have modified your filter that works.
use Yii;
use yii\web\Controller;
use yii\base\ActionFilter;
use yii\web\BadRequestHttpException;
class LanguageFilter extends ActionFilter
{
/**
* #var string
*/
public $shortLanguage;
/**
* #param ActionEvent $action
* #return bool
* #throws BadRequestHttpException
*/
public function beforeAction($action)
{
if ($this->shortLanguage === null && !$action instanceof yii\web\ErrorAction)) {
throw new BadRequestHttpException('Parameter "shortLanguage" is not defined.');
}
$langModel = Language::find()->where([
'shortName' => $this->shortLanguage,
])->one();
if ($langModel === null && !$action instanceof yii\web\ErrorAction) {
throw new BadRequestHttpException('There are not any data for language: ' . $this->shortLanguage);
}
Yii::$app->language = $langModel->locale;
return true; //return parent::beforeAction($action);
}
}
After a long time away from Zend, I need to get back into it again.
My last work on Zend Framework was in 2016. Now I tried to install Zend Framework 3 with doctrine and get stuck.
What I did:
Build the skeleton app with composer
composer create-project -s dev zendframework/skeleton-application path/to/install
Did not use the minimal installation and said y on all options. Did update of composer and installed Zend Framework:
composer self-update
composer install
I started the machine and entered it: vagrant up && vagrant ssh
I required doctrine require doctrine/doctrine-orm-module and configured it in module.config.php as follow:
'doctrine' => [
'connection' => [
'orm_default' => [
'driverClass' => PDOMySqlDriver::class,
'params' => [
'host' => '127.0.0.1',
'user' => 'root',
'password' => 'r00t',
'dbname' => 'zftest',
]
],
],
],
Then I wrote a controller factory to inject the entity manager:
namespace Application\Controller\Factory;
use Application\Entity\User;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;
use Application\Controller\IndexController;
/**
* This is the factory for IndexController. Its purpose is to instantiate the
* controller.
*/
class IndexControllerFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container,
$requestedName, array $options = null)
{
$entityManager = $container->get('doctrine.entitymanager.orm_default');
// Instantiate the controller and inject dependencies
return new IndexController($entityManager);
}
}
Added an entity to the codebase:
namespace Application\Entity;
/**
* #ORM\Entity
* #ORM\Table(name="user")
*/
class User
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(name="id")
*/
protected $id;
/**
* #ORM\Column(name="nick")
*/
protected $nick;
....
}
I tried to create the mysql tables via doctrine using this entity:
./vendor/bin/doctrine-module orm:schema-tool:create
The table was not created and I got this error:
"No Metadata Classes to process."
I tried to test doctrine:
./vendor/bin/doctrine-module orm:validate-schema
and it seems to be working:
[Mapping] OK - The mapping files are correct.
[Database] OK - The database schema is in sync with the mapping files.
Also tried in the controller to load the tables which I created manually:
class IndexController extends AbstractActionController
{
/**
* Doctrine entity manager.
* #var Doctrine\ORM\EntityManager
*/
private $entityManager;
// Constructor is used to inject dependencies into the service.
/**
* IndexController constructor.
* #param $entityManager
*/
public function __construct($entityManager)
{
$this->entityManager = $entityManager;
}
public function indexAction()
{
$users = $this->entityManager->getRepository('Application\Entity\User')->findAll();
return new ViewModel();
}
}
Which caused following error:
An error occurred
An error occurred during execution; please try again later.
Additional information: Doctrine\Common\Persistence\Mapping\MappingException
File: /var/www/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/MappingException.php:37
Message: The class 'Application\Entity\User' was not found in the chain configured namespaces
Stack trace:
#0 /var/www/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/Driver/MappingDriverChain.php(112): Doctrine\Common\Persistence\Mapping\MappingException::classNotFoundInNamespaces('Application\\Ent...', Array)
#1 /var/www/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php(151): Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain->loadMetadataForClass('Application\\Ent...', Object(Doctrine\ORM\Mapping\ClassMetadata))
#2 /var/www/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php(332): Doctrine\ORM\Mapping\ClassMetadataFactory->doLoadMetadata(Object(Doctrine\ORM\Mapping\ClassMetadata), NULL, false, Array)
#3 /var/www/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php(78): Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory->loadMetadata('Application\\Ent...')
#4 /var/www/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php(216): Doctrine\ORM\Mapping\ClassMetadataFactory->loadMetadata('Application\\Ent...')
#5 /var/www/vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php(281): Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory->getMetadataFor('Application\\Ent...')
#6 /var/www/vendor/doctrine/orm/lib/Doctrine/ORM/Repository/DefaultRepositoryFactory.php(44): Doctrine\ORM\EntityManager->getClassMetadata('Application\\Ent...')
#7 /var/www/vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php(698): Doctrine\ORM\Repository\DefaultRepositoryFactory->getRepository(Object(Doctrine\ORM\EntityManager), 'Application\\Ent...')
#8 /var/www/module/Application/src/Controller/IndexController.php(35): Doctrine\ORM\EntityManager->getRepository('Application\\Ent...')
#9 /var/www/vendor/zendframework/zend-mvc/src/Controller/AbstractActionController.php(78): Application\Controller\IndexController->indexAction()
#10 /var/www/vendor/zendframework/zend-eventmanager/src/EventManager.php(322): Zend\Mvc\Controller\AbstractActionController->onDispatch(Object(Zend\Mvc\MvcEvent))
#11 /var/www/vendor/zendframework/zend-eventmanager/src/EventManager.php(179): Zend\EventManager\EventManager->triggerListeners(Object(Zend\Mvc\MvcEvent), Object(Closure))
#12 /var/www/vendor/zendframework/zend-mvc/src/Controller/AbstractController.php(106): Zend\EventManager\EventManager->triggerEventUntil(Object(Closure), Object(Zend\Mvc\MvcEvent))
#13 /var/www/vendor/zendframework/zend-mvc/src/DispatchListener.php(138): Zend\Mvc\Controller\AbstractController->dispatch(Object(Zend\Http\PhpEnvironment\Request), Object(Zend\Http\PhpEnvironment\Response))
#14 /var/www/vendor/zendframework/zend-eventmanager/src/EventManager.php(322): Zend\Mvc\DispatchListener->onDispatch(Object(Zend\Mvc\MvcEvent))
#15 /var/www/vendor/zendframework/zend-eventmanager/src/EventManager.php(179): Zend\EventManager\EventManager->triggerListeners(Object(Zend\Mvc\MvcEvent), Object(Closure))
#16 /var/www/vendor/zendframework/zend-mvc/src/Application.php(332): Zend\EventManager\EventManager->triggerEventUntil(Object(Closure), Object(Zend\Mvc\MvcEvent))
#17 /var/www/public/index.php(40): Zend\Mvc\Application->run()
#18 {main}
Can someone give me a hint what I am missing?
It looks like you have no definition of where entities should be found.
Here's the link to the missing bit in your code:
DoctrineORMModule Documentation
At first sight your error seems to tell us he can't find 'Application\Entity\User'.
At start, Doctrine doesn't know anything about your namespaces.
Doctrine uses an AnnotationDriver to get informed about the location of your entities.
So at your step 5, where you specify module.config.php, you will need to add the following code into the mix:
<?php
namespace Application;
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
return [
// ...
'doctrine' => [
'driver' => [
__NAMESPACE__ . '_driver' => [
'class' => AnnotationDriver::class,
'cache' => 'array',
'paths' => [__DIR__ . '/../src/Entity']
],
'orm_default' => [
'drivers' => [
__NAMESPACE__ . '\Entity' => __NAMESPACE__ . '_driver'
]
]
]
]
];
And offcourse you'll need to setup to paths to your setup.
I get the following error, when I try to use doctrine 2 in ZF2.
Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for doctrine.entitymanager.orm_default
The needed modules are included and activated.
doctrine.config.local.php
return [
'doctrine' => [
'connection' => [
'orm_default' => [
'driverClass' => 'Doctrine\DBAL\Driver\PDOMySql\Driver',
'params' => [
'host' => 'localhost',
'port' => '3306',
'user' => 'root',
'password' => 'password',
'dbname' => 'database',
'charset' => 'utf8',
'driverOptions' => [
1002 => 'SET NAMES utf8'
],
],
],
],
'configuration' => [
'orm_default' => [
'metadata_cache' => 'array',
'query_cache' => 'array',
'result_cache' => 'array',
'hydration_cache' => 'array',
'generate_proxies' => false,
]
]
]
];
module.config.php of Core module (/module/Core/config/module.config.php)
namespace Core;
return [
'service_manager' => include __DIR__ . '/service-manager.config.php',
'router' => include __DIR__ . '/router.config.php',
'view_manager' => include __DIR__ . '/view-manager.config.php',
'translator' => include __DIR__ . '/translator.config.php',
'hydrators' => include __DIR__ . '/hydrators.config.php'
];
doctrine.config.php of Core module (/module/Core/config/doctrine.config.php)
return [
'driver' => [
__NAMESPACE__ . '_driver' => [
'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
'cache' => 'array',
'paths' => [
__DIR__ . '/../src/' . __NAMESPACE__ . '/Entity',
]
],
'orm_default' => [
'drivers' => [
__NAMESPACE__ => __NAMESPACE__ . '_driver'
]
]
]
];
Factory
namespace Event\Form\Fieldset\Factory;
use Event\Entity\Event;
use Event\Form\Fieldset\EventFieldset;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class EventFieldsetFactory implements FactoryInterface {
public function createService(ServiceLocatorInterface $formElementManager) {
$serviceLocator = $formElementManager->getServiceLocator();
$hydratorManager = $serviceLocator->get('HydratorManager');
// Here I get the error!
$objectManager = $serviceLocator->get('Doctrine\ORM\EntityManager');
$fieldset = new EventFieldset();
$fieldset->setObjectManager($objectManager);
$fieldset->setHydrator($hydratorManager->get('Core\Hydrator\Doctrine'));
$fieldset->setObject(new Event());
return $fieldset;
}
}
modules in application.config.php
'modules' => [
'DoctrineModule',
'DoctrineORMModule',
'Core',
'Event',
'Inquiry'
]
Stack trace
Zend\ServiceManager\Exception\ServiceNotFoundException
File:
/src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php:555
Message:
Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for doctrine.entitymanager.orm_default
Stack trace:
#0 /src/vendor/doctrine/doctrine-orm-module/src/DoctrineORMModule/Service/EntityManagerAliasCompatFactory.php(44): Zend\ServiceManager\ServiceManager->get('doctrine.entity...')
#1 [internal function]: DoctrineORMModule\Service\EntityManagerAliasCompatFactory->createService(Object(Zend\ServiceManager\ServiceManager), 'doctrineormenti...', 'Doctrine\ORM\En...')
#2 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(934): call_user_func(Array, Object(Zend\ServiceManager\ServiceManager), 'doctrineormenti...', 'Doctrine\ORM\En...')
#3 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(1092): Zend\ServiceManager\ServiceManager->createServiceViaCallback(Array, 'doctrineormenti...', 'Doctrine\ORM\En...')
#4 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(634): Zend\ServiceManager\ServiceManager->createFromFactory('doctrineormenti...', 'Doctrine\ORM\En...')
#5 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(597): Zend\ServiceManager\ServiceManager->doCreate('Doctrine\ORM\En...', 'doctrineormenti...')
#6 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(530): Zend\ServiceManager\ServiceManager->create(Array)
#7 /src/module/Event/src/Event/Form/Fieldset/Factory/EventFieldsetFactory.php(22): Zend\ServiceManager\ServiceManager->get('Doctrine\ORM\En...')
#8 [internal function]: Event\Form\Fieldset\Factory\EventFieldsetFactory->createService(Object(Zend\Form\FormElementManager\FormElementManagerV2Polyfill), 'eventfieldsetev...', 'Event\Fieldset\...')
#9 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(934): call_user_func(Array, Object(Zend\Form\FormElementManager\FormElementManagerV2Polyfill), 'eventfieldsetev...', 'Event\Fieldset\...')
#10 /src/vendor/zendframework/zend-servicemanager/src/AbstractPluginManager.php(330): Zend\ServiceManager\ServiceManager->createServiceViaCallback(Array, 'eventfieldsetev...', 'Event\Fieldset\...')
#11 /src/vendor/zendframework/zend-servicemanager/src/AbstractPluginManager.php(287): Zend\ServiceManager\AbstractPluginManager->createServiceViaCallback(Array, 'eventfieldsetev...', 'Event\Fieldset\...')
#12 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(634): Zend\ServiceManager\AbstractPluginManager->createFromFactory('eventfieldsetev...', 'Event\Fieldset\...')
#13 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(597): Zend\ServiceManager\ServiceManager->doCreate('Event\Fieldset\...', 'eventfieldsetev...')
#14 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(530): Zend\ServiceManager\ServiceManager->create(Array)
#15 /src/vendor/zendframework/zend-servicemanager/src/AbstractPluginManager.php(161): Zend\ServiceManager\ServiceManager->get('Event\Fieldset\...', true)
#16 /src/vendor/zendframework/zend-form/src/FormElementManager/FormElementManagerTrait.php(38): Zend\ServiceManager\AbstractPluginManager->get('Event\Fieldset\...', Array, true)
#17 /src/vendor/zendframework/zend-form/src/Factory.php(111): Zend\Form\FormElementManager\FormElementManagerV2Polyfill->get('Event\Fieldset\...')
#18 /src/vendor/zendframework/zend-form/src/Form.php(176): Zend\Form\Factory->create(Array)
#19 /src/module/Inquiry/src/Inquiry/Form/InquiryForm.php(19): Zend\Form\Form->add(Array)
#20 /src/vendor/zendframework/zend-form/src/FormElementManager/FormElementManagerV2Polyfill.php(217): Inquiry\Form\InquiryForm->init()
#21 [internal function]: Zend\Form\FormElementManager\FormElementManagerV2Polyfill->callElementInit(Object(Inquiry\Form\InquiryForm), Object(Zend\Form\FormElementManager\FormElementManagerV2Polyfill))
#22 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(664): call_user_func(Array, Object(Inquiry\Form\InquiryForm), Object(Zend\Form\FormElementManager\FormElementManagerV2Polyfill))
#23 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(597): Zend\ServiceManager\ServiceManager->doCreate('Inquiry\Form\In...', 'inquiryforminqu...')
#24 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(530): Zend\ServiceManager\ServiceManager->create(Array)
#25 /src/vendor/zendframework/zend-servicemanager/src/AbstractPluginManager.php(161): Zend\ServiceManager\ServiceManager->get('Inquiry\Form\In...', true)
#26 /src/vendor/zendframework/zend-form/src/FormElementManager/FormElementManagerTrait.php(38): Zend\ServiceManager\AbstractPluginManager->get('Inquiry\Form\In...', Array, true)
#27 /src/module/Inquiry/src/Inquiry/Controller/Factory/InquiryControllerFactory.php(23): Zend\Form\FormElementManager\FormElementManagerV2Polyfill->get('Inquiry\Form\In...')
#28 [internal function]: Inquiry\Controller\Factory\InquiryControllerFactory->createService(Object(Zend\Mvc\Controller\ControllerManager), 'inquirycontroll...', 'Inquiry\Control...')
#29 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(934): call_user_func(Array, Object(Zend\Mvc\Controller\ControllerManager), 'inquirycontroll...', 'Inquiry\Control...')
#30 /src/vendor/zendframework/zend-servicemanager/src/AbstractPluginManager.php(330): Zend\ServiceManager\ServiceManager->createServiceViaCallback(Array, 'inquirycontroll...', 'Inquiry\Control...')
#31 /src/vendor/zendframework/zend-servicemanager/src/AbstractPluginManager.php(287): Zend\ServiceManager\AbstractPluginManager->createServiceViaCallback(Array, 'inquirycontroll...', 'Inquiry\Control...')
#32 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(634): Zend\ServiceManager\AbstractPluginManager->createFromFactory('inquirycontroll...', 'Inquiry\Control...')
#33 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(597): Zend\ServiceManager\ServiceManager->doCreate('Inquiry\Control...', 'inquirycontroll...')
#34 /src/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(530): Zend\ServiceManager\ServiceManager->create(Array)
#35 /src/vendor/zendframework/zend-servicemanager/src/AbstractPluginManager.php(161): Zend\ServiceManager\ServiceManager->get('Inquiry\Control...', true)
#36 /src/vendor/zendframework/zend-mvc/src/DispatchListener.php(94): Zend\ServiceManager\AbstractPluginManager->get('Inquiry\Control...')
#37 [internal function]: Zend\Mvc\DispatchListener->onDispatch(Object(Zend\Mvc\MvcEvent))
#38 /src/vendor/zendframework/zend-eventmanager/src/EventManager.php(490): call_user_func(Array, Object(Zend\Mvc\MvcEvent))
#39 /src/vendor/zendframework/zend-eventmanager/src/EventManager.php(263): Zend\EventManager\EventManager->triggerListeners('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#40 /src/vendor/zendframework/zend-mvc/src/Application.php(340): Zend\EventManager\EventManager->triggerEventUntil(Object(Closure), Object(Zend\Mvc\MvcEvent))
#41 /src/public/index.php(15): Zend\Mvc\Application->run()
#42 {main}
First trouble is your config loader. You've modified it to contain:
'config_glob_paths' => [
'config/autoload/local/{,*.}local.php',
'config/autoload/global/{,*.}global.php'
],
But your folders are set as:
config/autoload/global/doctrine.php
So the loaders won't match.
This glob path would work for your file structure:
'config_glob_paths' => [
'config/autoload/local/{,*.}php',
'config/autoload/global/{,*.}php'
],
As alternative, I've uploaded a more 'standard' config setup that could help you:
https://github.com/Saeven/doctrine-error/tree/master/src/config
In short though, you were getting bad errors, because no connection could be established, simply because your DB details were absent (because your config loader was hosed).
Second, looks like your composer.json is loading in some incompatible items. I used one from a project I maintain and combined with the loader fix, I see "test" when I put valid DB creds:
composer.json
{
"name": "test",
"minimum-stability": "dev",
"require": {
"php": ">=5.3.3",
"zendframework/zend-servicemanager": "#stable",
"zendframework/zend-eventmanager": "#stable",
"zendframework/zend-modulemanager": "#stable",
"zendframework/zend-developer-tools": "#stable",
"zendframework/zend-config": "#stable",
"zendframework/zend-console": "#stable",
"zendframework/zend-test": "#stable",
"zendframework/zend-crypt": "#stable",
"zendframework/zend-mail": "#stable",
"zendframework/zend-text": "#stable",
"zendframework/zend-serializer": "#stable",
"zendframework/zend-mvc": "2.5.3",
"zendframework/zend-filter": "#stable",
"zendframework/zend-db": "#stable",
"zendframework/zend-stdlib": "#stable",
"zendframework/zend-view": "#stable",
"zendframework/zend-form": "#stable",
"zendframework/zend-validator": "#stable",
"zendframework/zend-i18n": "#stable",
"zendframework/zend-log": "#stable",
"zendframework/zend-cache": "#stable",
"doctrine/doctrine-orm-module": "0.8.0",
"doctrine/orm": "2.5.*#dev"
}
}
I think your problem is in your factory and how you get the EntityManager.
Here is how to get Doctrine\ORM\EntityManager from serviceLocator in a ZF2 factory :
class YourFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
/* #var $em \Doctrine\ORM\EntityManager */
$em = $serviceLocator->getServiceLocator()->get('em');
// $em contains methods to get repo, etc ...
// injections here
$obj = new Obj();
$obj->setEntityManager($em);
return $obj;
}
}
Try that and let me know