简体   繁体   English

如何在php-di中注册calss以在实例化时自动调用某些方法

[英]how to register calss in php-di to automatically call some method when instantiated

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. 我是php-di的新手。 i know that when im instantiating inside the method DI doesnt track it ... just dont know how to set this altogether ? 我知道当我在方法DI中实例化时不会跟踪它...只是不知道如何完全设置它?

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) 因为Controller有一个容器实例只需要通过容器调用模型并将其包装在某些方法中,如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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM