【问题标题】:Using container object from Included file使用包含文件中的容器对象
【发布时间】:2015-10-06 07:24:02
【问题描述】:

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

首先我想在 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 中的容器以一种简单而正确的方式访问?

【问题讨论】:

  • 如果你真的需要 >>samestackoverflow.com/a/203359/5297359
  • 一个 index.php 是前端的起点,另一个是我的应用程序后端的起点。这两个索引文件不在同一个请求中执行 - 所以不,我不需要相同的容器对象。我只是想知道如何访问容器实例。我不想创建单例或注册表,因为我只会将它们用于这个单一目的。
  • OK 不只是将返回值放在bootstrap.php 中,只需使用简单的require 而不将其分配给$container,然后您可以使用引导程序中的$container 变量而无需执行任何其他操作

标签: php include return


【解决方案1】:

没有必要返回,如果你包含文件你已经可以访问变量$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();

已更新(在 cmets 之后):

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

另一个例子:

如果您需要在返回之前在 Container 对象上添加服务,如果您想避免全局变量,可以使用静态帮助器类(仅作为示例):

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

【讨论】:

  • 我认为这更糟,因为您在这里定义了一个硬编码的全局变量名。 return 更可取,因为它将变量名的选择留给调用者。
  • 是的,return 是对的,我可以拥有自己的新变量名,但即使有 return 语句,全局变量 $container 仍然存在。所以你还需要在 bootstrap.php 中删除 $containerreturn new League.......
  • 确实,这将是更好的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-15
  • 1970-01-01
  • 2020-09-22
  • 2012-09-18
  • 2015-10-06
  • 2018-09-30
  • 1970-01-01
相关资源
最近更新 更多