1

I'm running into some trouble while using the IoC container in Laravel 4.2

I have 2 classes: BlockFactory and Block. They are meant to display blocks of content (much like joomla modules) where a single Block represents a block of content and the BlockFactory represents the "container" of those blocks. This BlockFactory has a render method I want to call to render out all the blocks.

What I did was create a BlockServiceProvider like so:

public function register()
{
    $this->app->singleton('BlockFactory', function () {
        return new BlockFactory();
    });
    $this->app->bind('block', 'Animekyun\Block\Block'); // Facade
}

I'm injecting the BlockFactory class into the Block constructor so I can add blocks to the factory:

public function __construct(BlockFactory $blockFactory)
{
    $this->blockFactory = $blockFactory;
}

public function create($title, $content, $parameters)
{
    $this->title = $title;
    $this->content = $content;
    $this->parameters = $parameters;

    return $this;

}

public function push()
{
    $this->blockFactory->add($this);
}

From what I understand is that when I use the singleton method with the IoC container I can access the BlockFactory from within the container and it will be the same instance over and over again. Something like a global variable.

However I have not been able to access BlockFactory in anyway without instantiating it again. I tried App::make('BlockFactory') but according to the documentation it just calls the callback defined in the service provider.

Is this possible? What are some other ways of doing this?

Nick
  • 2,862
  • 5
  • 34
  • 68
  • This should indeed work. Can you post a bit more code, especially the parts where you are injecting and using the singleton? – Marcel Gwerder Dec 26 '14 at 23:09
  • @MarcelGwerder I'm not using `App::singleton()` since it returns void. I used `App::make('BlockFactory')`. I updated my code. – Nick Dec 26 '14 at 23:18
  • Yes `make` should be fine and should always return the same instance if used on a singleton. Do you get the same instance of `BlockFactory` in each `Block` or does that fail too? And did you try to pass a different string as name than `BlockFactory` when calling `$this->app->singleton`? – Marcel Gwerder Dec 26 '14 at 23:26
  • @MarcelGwerder I'm trying it a different way now. Instead of having Block depend on the factory, I'm decoupling them. Reason being that if I keep adding blocks to the factory, which is a dependancy of block itself, it will become a huge object containing itself over and over again. I'm now letting the factory create the blocks and having it store these blocks in itself. – Nick Dec 26 '14 at 23:33

0 Answers0