Model instatiation in Yii2

I only have one question: HOW DO YOU INSTANTIATE MODELS? (anywhere in the project)

Old fashion way was $model = new Model(); where model could be in a totally different module and it would still work. How do we do this now? when I try to do it, it says: Class ‘app\modules\somemodule\controllers\Model’ not found which is funny because I want a model and it searches in controllers…

Please help me!

Nothing changed about it. If you need new fresh instance it’s just “new Post()”. If you need to get AR model with data it’s “Post::find->where(…)->one()”.

The thing you’re facing is PHP namespaces: http://php.net/manual/en/language.namespaces.php

Ok, I understand that now, but how can I fix it? I mean… I have the namespace


namespace app\modules\sommodule\controllers;

if I change it to


namespace app\modules\sommodule\models;

it will not find the default controller. And I cannot add 2 namespaces… So how can I access the model in the controller?

Either import class from another namespace with use:




use app\modules\someModule\models\Post;


// ...


$post = new Post();



or use fully qualified class name:




$post = new \app\modules\someModule\models\Post();



Tried it both ways and now it produces this: “Unable to find ‘app\modules\someModule\models\Model’ in file: C:\xampp\htdocs\site/modules/someModule/models/Model.php. Namespace missing?” either way that I’m going…

Am I missing something? :(

Wher did you put your Model.php? If you put in frontend/models/Model.php then you have to use "use" like this:


use frontend\models\Model;

my model is in modules/someModule/models/Model.php and I have


use app\modules\someModule\models\Model;

in my code… so? What am I missing?

Inside the model class do you have namespace declared?

Yup


<?php


namespace app\modules\oder\models;


use Yii;


/**

....

Then you should be able to use it like this:


use app\modules\oder\models\Model;

but not like this:


use app\modules\someModule\models\Model;

Namespace should match directory structure else class won’t be loaded.

tx @samdark :D found my error… a freaking typo :(