douchenchepan6465 2019-06-06 02:57
浏览 83

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

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 ?

  • 写回答

1条回答 默认 最新

  • donkey111111 2019-06-06 20:41
    关注

    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);
        }
    }
    
    
    评论

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入