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).

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

报告相同问题?