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 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?