dongyin2643
2018-08-31 15:09 阅读 59
已采纳

如何从某个地方访问我的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 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.

    点赞 评论 复制链接分享

相关推荐