i run controller this way
$controller = $this->getContainer()->get($class);
$controller->{$method}(...array_values($vars));
now inside controller i need to use models if i try to autowire model like
class MyClass extends Controller
{
public function doSmth(myModel $myModel)
{
$myModel->getAll());
}
}
i receive error about wrong parameter types. controller methods shouldnt always use some model and because of this models need to be instantiated inside methods .
ok, then im trying to instantiate model directly
class MyClass extends Controller
{
public function doSmth()
{
$myModel = new myModel();
$myModel->getAll());
}
}
but i receive problem that i need instance of the container inside the model (to set up DB connection for example, and these settings registered inside container). i could transfer the container instance from the controller to the model like this:
class MyClass extends Controller
{
public function doSmth()
{
$myModel = new myModel($this->container);
$myModel->getAll());
}
}
but i would have to do this every time i need some model and this is ugly ...
im new to the php-di. i know that when im instantiating inside the method DI doesnt track it ... just dont know how to set this altogether ?
since Controller has an instance of the container required just to call the model through container and wrap it in some method like getModel($modelName)
class MyClass extends Controller
{
public function doSmth()
{
$myModel = $this->getModel('MyModel');
$myModel->getAll());
}
}
and get model will be smth like:
class Controller
{
protected $c;
public function __construct(ContainerInterface $c)
{
$this->c = $c;
}
public function getModel(string $name)
{
return $this->c->get($name);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.