php - Using container object from Included file

222

I got two index.php and both make use of a bootstrap.php. The bootstrap file is setting up a DI-Container and I need in both index files access to this DI-Container.

First I was thinking about using a simplereturn in 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();

I read somewhere that using return statements like this are a bad habit. So I'm wondering how to make the container in the index.php accessible in an easy and proper way?

977

Answer

Solution:

There is no need for a return, if you include the file you already have the access to the variable$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();

UPDATED (following the comments):

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

ANOTHER EXAMPLE:

If you need to add your services on the Container object before return, you can use a static helper class (just for example) if you want to avoid a global variable:

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

People are also looking for solutions to the problem: php - Storing a list from form to database as an array

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.