Search code examples
dependency-injectionlaravelinversion-of-controlioc-container

Laravel 4: how to inject another class in a eloquent model


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!


Solution

  • 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.