I want to set the cookie lifetime in my phtml file.

I am using the following code:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cookieManager = $objectManager->get('Magento\Framework\Stdlib\CookieManagerInterface');
$cookieMetadataFactory = \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory::getInstance();
$cookie_lifetime = (90 * 60);//90 days
$cookie_metadata = $cookieMetadataFactory->createPublicCookieMetadata()->setDuration($cookie_lifetime); 
$cookieManager->setPublicCookie('cookie1', 'value', $cookie_metadata);

I get this error:

Call to undefined method Magento\Framework\Stdlib\Cookie\CookieMetadataFactory::getInstance()

So, is there no getInstance method? What can I use instead?

  • 1
    please accept the answer if my answer worked for you – Vivek Kumar Oct 5 '17 at 8:55

You cannot directly get instance for Magento\Framework\Stdlib\Cookie\CookieMetadataFactory instead use

$cookieMetadataFactory = $objectManager->get("Magento\Framework\Stdlib\Cookie\CookieMetadataFactory");

However, you should probably using dependency injection of your constructor if you are in block or controller, make a function in block in case of phtml as objectmanager is not a recommended practice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.