dongyin2643 2018-08-31 15:09
浏览 72
已采纳

如何从某个地方访问我的DI Container配置文件?

This is just for educational purpose. I am trying to reach my container settings file.

have a container class that gets requested class' constructor parameters(for the moment).

$container->register($className) function pushes data into an array.

Here is my container settings(conf.php) file:

require_once("./app/central/layer/items.php");

$container = new App\Central\Layer\Items;

$container->register("BlaBla_1");
$container->register("BlaBla_2");

Purpose: I want to integrate this configuration file to somewhere i can reach easily from every class.

I don't want to call again and again everytime i try to reach container. I tried something like this.

$containerLoader->loadConfig();

BUT the result is an **empty** array.(when i'm trying to call from somewhere on another class)

It only works with:

class SomeClass
{
    public function __construct()
    {
        require_once("./conf.php");

        // I GET BLABLA_1'S CONSTRUCTOR PARAMATERS WITHOUT ANY PROBLEM
        $container->get("BlaBla_1");


    }

    //other methods...
}

I want to know how can i reach my settings file without doing this. I think that i am doing this in a very wrong way i guess. Any implementation ideas?

Any help would be very appreciated. Thanks anyway.

  • 写回答

1条回答 默认 最新

  • douling8772 2018-08-31 15:21
    关注

    Well, DI stands for dependency injection, so one way would be to inject your container into your classes that depend on it.

    class SomeClass
    {
        public function __construct($container)
        {
            ...
        }
    }
    

    Another common method is to make your container global or using a helper function:

    function container()
    {
        global $container;
        return $container;
    }
    

    Then you can access your container with the helper function container() anywhere in your application. Since container will only have one instance and should be accessible app-wide, this is one of the few times I find globals acceptable.

    In either case, your config file should be included, and your container should be defined, prior to instantiating any service class in the application.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码