mercredi 12 septembre 2018

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?

Aucun commentaire:

Enregistrer un commentaire