duanliang1999 2014-08-04 17:06
浏览 72
已采纳

像$ smarty.session一样创建自己的Smarty变量

So I am using a custom PHP Session handler (One that kinda works like the one in Laravel if you're familiar with the framework), which don't register to the $_SESSION superglobal, so I can't use {$smarty.session.some_data} to access it.

However, in my Smarty template I still would like to retrieve values stored in the session without needing to assign the value manually to a Smarty variable all the time. What would be the best way to create a way to access my session data?

Thanks in advance!

  • 写回答

1条回答 默认 最新

  • dongqindan4406 2014-08-05 14:27
    关注

    Probably there's no way to use syntax $smarty.yourarray.data but this syntax is used for global array ($_POST, $_GET, $_SESSION, $_COOKIE, $_SERVER).

    However you can access static class in the same method as in PHP.

    Assume you have the following class in PHP file:

    class Session
    {
        public static function get($data) {
            if (is_int($data)) {
                return $data * 3;
            }
            return $data;
        }
    }
    

    Now, you don't need to assign anything to Smarty.

    When in Smarty file you want to access this class method you simply need to use:

    {Session::get('something')}<br />
    {Session::get(2)}
    

    And you will get result:

    something
    6
    

    as expected.

    So you don't have to do anything to access this class (no modifiers/functions, you even don't need to assign this class).

    However let's assume you have your Session class in namespace:

    <?php
    
    //session.php
    
    namespace MySession;
    
    class Session
    {
        public static function get($data) {
            if (is_int($data)) {
                return $data * 3;
            }
            return $data;
        }
    }
    

    If you want to this static class inside Smarty you will need to register your class:

    require ('session.php');
    $smarty->registerClass('Session', 'MySession\Session');
    

    to make it work (you cannot use namespace in TPL file as far as I know).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题