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

Using container object from Included file

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

首先我想在 bootstrap.php 中使用一个简单的 return:

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();

我在某处读到,使用这样的 return 语句是一个坏习惯。所以我想知道如何让 index.php 中的容器以一种简单且正确的方式访问?

不需要 return,如果包含文件,您已经可以访问变量 $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();

另一个例子:

如果你需要在 return 之前在 Container 对象上添加你的服务,你可以使用静态助手 class (仅作为示例)如果你想避免全局变量:

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();