【问题标题】:Smarty cache object instance inside plugin插件内的 Smarty 缓存对象实例
【发布时间】:2013-08-05 02:41:49
【问题描述】:

我有一个插件/功能,用于检测设备是否为移动设备/平板电脑/桌面设备。

例如:

<img src="/path/to/images/foo{if detect_device == 'desktop'}-highres{/if}.jpg"

插件

<?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File:     function.detect_device.php
 * Type:     function
 * Name:     detect_device
 * Purpose:  Simple plugin to access Mobile_Detect methods from within templates
 * Examples:
 * {if detect_device == 'tablet'} - return string either: mobile/tablet/desktop
 * {if detect_device action='isAndroidOS'} - boolean
 * {if detect_device action='isiOS'} - boolean
 * -------------------------------------------------------------
 */
function smarty_function_detect_device($params, &$smarty)
{
    // Include and instantiate the class.
    require_once 'Mobile_Detect/Mobile_Detect.php';
    $detect = new Mobile_Detect;

    // Access specific method
    if(!empty($params)){
        foreach($params as $param){
           if(method_exists($detect, $param)){
               return $detect->$param();
           }
        }
    } else {
        // Simple device type
        switch (true) {
            case $detect->isMobile() : return 'mobile'; 
            case $detect->isTablet() : return 'tablet';
            default                  : return 'desktop';
        }
    }
}
?>

第一季度。为什么这从来都不是真的{if detect_device == 'desktop'} 但是当我 {detect_device|@var_dump} 它返回字符串“桌面”(长度=7)? 我想我只是混淆了我应该使用的插件类型,因为我现在想将参数传递给插件,我应该使用修饰符吗?我更喜欢这种语法{if $detect_device|isiOS},但这会尝试检查 isiOS 是否是修饰符而不是参数。

第二季度。有没有办法缓存 Mobile_Detect 对象,以便只执行一次用户代理计算?

移动检测脚本来自:https://github.com/serbanghita/Mobile-Detect

【问题讨论】:

    标签: php smarty smarty3


    【解决方案1】:

    正如您自己猜到的,{detect_device} 的语法与 {if detect_device == 'desktop'} 不同。前者调用函数“检测设备”,而后者将字符串文字detect_device 与一个值进行比较。

    如果要使用修饰符,正确的方法是这样的(manual):

    {'isiOS'|detect_device} 
    

    关于缓存结果,您不必存储 Mobile_Detect 对象,而是存储它的结果(浏览器字符串)。为此,您可以使用 PHP 的常用方法来持久化值:您可以使用 $GLOBALS 变量空间,或者,如果您使用会话,则将结果存储在会话中(如果用户使用不同的登录方式会有所不同)浏览器)。饼干也是如此。

    会话/cookie 方法更好,因为它将在整个用户会话(或更长时间)中缓存结果,而不仅仅是每次页面加载一次

    【讨论】:

      【解决方案2】:

      您需要一个 $ 来访问分配的变量

      <img src="/path/to/images/foo{if $detect_device == 'desktop'}-highres{/if}.jpg"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多