vthomas
vthomas

Reputation: 41

ZF3 - Get cookie from helper

I'm looking about an issue. I'm starting to work with ZendFramework 3. Now i have to load somes data from cookies in an helper.

Explanation: There is an history stock in the cookie (array of index). I'm building a little menu Helper who take a list and render it (Get from ID etc for render). My menu is on all the pages. And I don't want to go inside all controller for change actions code for doing something like

$this->getRequest()->getCookie();
...
return new ViewModel(["history" => $history]);

There is a easy way to make the helper automaticaly get the value in the history ?

Thank you.

Upvotes: 2

Views: 309

Answers (1)

vthomas
vthomas

Reputation: 41

I found a solution, I create a factory for the helper than send ContainerInterface to the Helper:

public function __invoke(ContainerInterface $container, $requestedName, array $options = null){
        $em = $container->get('doctrine.entitymanager.orm');

        return new MenuWithCookie($container, $em);
    }

There i handle it in the class:

class MenuWithCookie extends AbstractHelper
{
    protected $_em;
    protected $_sm;

    public function __construct($container, $em)
    {
        $this->_sm = $container;
        $this->_em = $em;
    }

    public function __invoke($list, $option = [])
    {
        if (isset($option['from-cookie']) && $option['from-cookie']) {
            $req = $this->_sm->get('Request');
            $c = $req->getCookie();
            $cookieStuff = (isset($c['cookie-stuff'])) ? $c['history'] : NULL;
        }
        //Eat them all and do cool stuff
    }
}

Upvotes: 2

Related Questions