1

I'm trying to use the built-in laravel's Ioc container to inject a PageManager class inside a Page model and I'm a little lost.

What I'm trying to achieve is something like that:

class Pages extends Eloquent {

    public function __construct(PagesManagerInterface $manager, array $attributes = array()) 
    {
        parent::__construct($attributes);
        $this->manager = new $manager;
    }

    public function saveToDisk()
    {
         $this->manager->writeToFile();
    }

But I obtain this error:

ErrorException: Argument 1 passed to Pages::__construct() must be an instance of PagesManagerInterface, none given.

I tried to add this in app/start/global.php:

App::bind('Pages',function(){

    return new Pages(new PagesManager);
});

But is seems ignored by the framework, and also i don't know how to insert the $attribute array into this declaration.

I'm a little lost so any help is appreciated!

Ingro
  • 2,841
  • 5
  • 26
  • 42

3 Answers3

7

It's not a good idea to overload a model's constructor because new instances can be spawned behind the scenes through various methods, like Model::find().

When that happens, the dependencies you're asking for in your custom constructor aren't being passed in because the Model class isn't aware of them. So, you get that error message.

See the find() method here: http://laravel.com/api/source-class-Illuminate.Database.Eloquent.Model.html#380-397

See this post by Jason Lewis: http://forums.laravel.io/viewtopic.php?pid=47124#p47124

Michael
  • 71
  • 2
  • That's a good point, I actually ended up instantiating the manager only when neeeded and passing the page as reference. – Ingro Sep 26 '13 at 17:26
0

I think that what you need is:

App::bind('PagesManagerInterface',function(){

    return new Pages(new PagesManager);

});

This tells Laravel to inject a new Page object everytime it needs an instance of your PagesManagerInterface wich wasn't passed while creating the model.

Antonio Carlos Ribeiro
  • 86,191
  • 22
  • 213
  • 204
  • Thanks for the advice, anyway I ended up instantiating the manager only when neeeded with the page as reference. – Ingro Sep 26 '13 at 17:26
0

In Laravel you can use the IoC Container:

public function saveToDisk(){
    $managerObject = app()->make('path\to\class\PagesManagerInterface');
    $managerObject->writeToFile();
}
tomloprod
  • 7,472
  • 6
  • 48
  • 66