使用包含文件中的容器对象


Using container object from Included file

我得到了两个index.php并且都使用了一个bootstrap.php。引导文件正在设置一个DI-Container,我需要在两个索引文件访问这个DI-Container。

首先,我正在考虑使用一个简单的return在bootstrap.php:

bootstrap.php

<?php
require __DIR__ . '/vendor/autoload.php';
$container = new League'Container'Container;
// add some services
return $container;

index . php

<?php
$container = require __DIR__ . '/bootstrap.php';
$container->get('application')->run();

我在某处读到像这样使用返回语句是一个坏习惯。所以我想知道如何使容器在index.php访问在一个简单和适当的方式?

不需要返回,如果包含了该文件,则已经可以访问变量$container

bootstrap.php

<?php
require __DIR__ . '/vendor/autoload.php';
$container = new League'Container'Container;
// add some services

index . php

<?php
require __DIR__ . '/bootstrap.php';
$container->get('application')->run();

更新(跟随注释):

bootstrap.php

<?php
require __DIR__ . '/vendor/autoload.php';
// add some services
return new League'Container'Container;

index . php

<?php
$container = require __DIR__ . '/bootstrap.php';
$container->get('application')->run();

另一个例子:

如果您需要在返回之前在容器对象上添加服务,如果您希望避免使用全局变量,则可以使用静态helper类(仅举个例子):

class Context {
    private static $container = null;
    public static function getContainer() {
        return self::$container;
    }
    /* maybe you want to use some type hinting for the variable $containerObject */
    public static function setContainer( $containerObject ) {
        self::$container = $containerObject;
    }
}

bootstrap.php

<?php
require __DIR__ . '/vendor/autoload.php';
// require the Context class, or better get it with your autoloader
Context::setContainer( new League'Container'Container );
// add some services
Context::getContainer()->addMyService();
Context::getContainer()->addAnotherService();
//if you want to, you can return just the container, but you have it in your Context class, so you don't need to
//return Context::getContainer();

index . php

<?php
require __DIR__ . '/bootstrap.php';
Context::getContainer()->get('application')->run();