【问题标题】:How do I save value in my own session variable in Magento?如何在 Magento 中自己的会话变量中保存值?
【发布时间】:2011-03-21 10:30:16
【问题描述】:

我正在使用 Magento 并尝试在其 index.php 文件中保存会话中的值,如下所示,但该值没有被保留。

$_SESSION['myvar'] = '1';

我该怎么做?

谢谢

【问题讨论】:

  • 我在直接使用setcookie() 时遇到了同样的问题,因为core/cookie 模型处理了这些设置,发现它覆盖了我的值。

标签: php magento session


【解决方案1】:

假设您要将值“Hello world”保存到会话中的“欢迎消息”变量中。代码是:

$inputMessage = 'Hello World';
Mage::getSingleton('core/session')->setWelcomeMessage($inputMessage);

现在您想在代码/站点的其他地方回显“欢迎信息”。

$outputMessage = Mage::getSingleton('core/session')->getWelcomeMessage();
echo $this->__($outputMessage);

【讨论】:

  • 值得一提的是如何清除(取消设置)会话变量:Mage::getSingleton('core/session')->unsWelcomeMessage(); “uns”代表未设置。
  • 我知道那是 5 年前的事了,但是谢谢!
【解决方案2】:

按照 Ali Nasrullah 给出的示例,我会这样做:

$session = Mage::getSingleton("core/session",  array("name"=>"frontend"));
// set data
$session->setData("device_id", 4);
// get data
$myDeviceId = $session->getData("device_id");

确保在调用上面的代码之前包含 [Mage-root]/app/Mage.php!

@Ali Nasrullah:将 device:id 的值作为 setData 函数的第二个参数传递。

【讨论】:

  • 我尝试了上述方法,但无法正常工作。如何调用 /app/Mage.php。默认情况下,index.php 包括: require_once $mageFilename;够了吗?
【解决方案3】:
  Mage::getSingleton('core/session')->setMySessionVariable('MyValue'); 

  $myValue  =  Mage::getSingleton('core/session')->getMySessionVariable();

  echo $myValue;

 Take Look For More: 

Here are code to Get, Set, and Unset Session in Magento

Here are code to Get, Set, and Unset Session in Magento

【讨论】:

    【解决方案4】:
    frontend: Mage::getSingleton('core/session')->setYourNameSession($session_value);
    
    backend: Mage::getSingleton('admin/session')->setYourNameSession($session_value);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-07
      • 2013-03-31
      • 2014-08-09
      • 2021-10-16
      相关资源
      最近更新 更多