Is there a way to avoid wording like $model = new ModelName() all the time? Can i call my models from Dependency Injector without actually creating a new instance like mentioned above?
|
Apr '16 |
7 |
581 |
0 |
First of all - for what you need new instance ? If you are doing new ModelName()
then it means you need to save it then, then yes - you have to call it every time, but if you need to select some model of this class there are modelsManager/ModelName::find/ModelName::findFirst/ModelName::query
But why you want to do that ? $this->view is just one object, you never creating new instance of it. Why you need only one instance of your class in di ? I don't get it.
But why you need it ? If you need object of some class you do new Class()
like in any normal language. Just tell me why you need this behaviour and we maybe can figure something out. To create new object use new Class()
, i don't see any logical behaviour for creating new instance of model calling di, no sense in it.
But why you want get rid of it ? What is your use case ? When you are using it ? For what ? Etc etc.
If you need to create for example new user and create it in database - then you should aways use new SomeClass(). If you mean something else - then tell me what.
It's really bad behaviour and you should NEVER do it. new Class() give you stubs from IDE, you can jump to declaration etc etc. What you want won't be user friendly, and also you would make sure you always have this service setted in di. Also just for instance of course you can do it:
$di->setShared('somename',function(){
$user = new User();
return $user;
});
and then in code:
$di->getShared('somename')
But it's really, really, really bad and you shouldn't use it. Di is for storing services etc, not for creating object instances, especially not for creating model instances.
Well, when you access something rom di it's calling function which can create object instance and return it. But it's it shouldn't be used for creating model objects, or just any object.