Pedro
Pedro

Reputation: 163

ZF2: how to create a new instance of a model inside a controller

I'm starting to learn the benefits of ZF2 dependency injection and am a bit confused on how to create a new instance of a model inside a controller.

I know I can use: $this->getServiceLocator()->get('Crumb'), but I've read it's considered an anti-pattern to use the serviceLocator in a controller.

To bring this problem to life: I have a class Breadcrumbs and a class Crumb. It looks similar to this:

class Breadcrumbs
{
    private $crumbs = array();

    public function getCrumbs(){
        return $this->crumbs;
    }

    public function addCrumb(Crumb $crumb){
        $this->crumbs[] = $crumb;
    }
}


class Crumb
{
    private $title;
    private $url;

    public function setTitle($title){
        $this->title = $name;
    }
}


class DetailController extends AbstractActionController
{
    private $breadcrumbs;

    public function __construct(Breadcrumbs $breadcrumbs){
        $this->breadcrumbs = $breadcrumbs;
    }

    public function indexAction(){
        $crumb = new Crumb();  //Option 1
        $crumb = $this->getServiceLocator()->get('Crumb');  //Option 2
        $crumb = ??  //Option 3 ??

        $this->breadcrumbs->addCrumb($crumb);
    }
}

I'm confused how to create the instance of Crumb. If I follow option 1, I can't use a factory to inject any dependencies into Crumb. If I follow option 2, I use the serviceLocator which is an anti-pattern.

Am I missing anything obvious?

Upvotes: 0

Views: 178

Answers (1)

thewildandy
thewildandy

Reputation: 328

Since your Crumb class is a Model, it's perfectly acceptable to instantiate it in the Controller.

Depending on your use case it may be more appropriate to create the new Crumbs via a Service, e.g. CrumbService->create($data);. You would then inject the Service into the Controller via a Factory, and update your module config accordingly (i.e. ensure your controller is set up to instantiate via a factory rather than as an invokable class.

Upvotes: 2

Related Questions