October 23, 2014, 10:27am
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!
October 23, 2014, 11:07am
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:
October 23, 2014, 11:27am
Ok, I understand that now, but how can I fix it? I mean… I have the namespace
if I change it to
it will not find the default controller. And I cannot add 2 namespaces… So how can I access the model in the controller?
October 23, 2014, 11:36am
Either import class from another namespace with use:
$post = new Post();
or use fully qualified class name:
$post = new \app\modules\someModule\models\Post();
October 23, 2014, 12:04pm
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?
October 23, 2014, 12:45pm
Wher did you put your Model.php? If you put in frontend/models/Model.php then you have to use "use" like this:
October 23, 2014, 12:46pm
my model is in modules/someModule/models/Model.php and I have
in my code… so? What am I missing?
October 23, 2014, 3:19pm
Inside the model class do you have namespace declared?
October 23, 2014, 3:21pm
October 23, 2014, 4:08pm
Then you should be able to use it like this:
but not like this:
October 23, 2014, 6:57pm
Namespace should match directory structure else class won’t be loaded.
October 24, 2014, 7:54am
@samdark found my error… a freaking typo