Php 插件内的Smarty缓存对象实例
我有一个插件/功能,用于检测设备是否为移动设备/平板电脑/台式机 例如:Php 插件内的Smarty缓存对象实例,php,smarty,smarty3,Php,Smarty,Smarty3,我有一个插件/功能,用于检测设备是否为移动设备/平板电脑/台式机 例如: 插件 <?php /* * Smarty plugin * ------------------------------------------------------------- * File: function.detect_device.php * Type: function * Name: detect_device * Purpose: Simple plugin
插件
<?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';
}
}
}
?>
问题1。为什么这从来都不是真的{if detect_device=='desktop'}
但是当我
{detect_device |@var_dump}
它返回字符串'desktop'(长度=7)?
我想我只是混淆了我应该使用的插件类型,因为我现在想给插件传递一个参数,我应该使用修饰符吗?我更喜欢这种语法{if$detect_device | isiOS}
,但它试图检查isiOS是否是一个修饰符而不是参数
问题2。是否有办法缓存Mobile_Detect对象,以便只执行一次用户代理计算
移动检测脚本来自:您需要$来访问分配的变量
<img src="/path/to/images/foo{if $detect_device == 'desktop'}-highres{/if}.jpg"
正如您自己所猜测的,语法{detect\u device}
与{if detect\u device=='desktop'}
不同。前者调用函数“detect device”,而后者将字符串literaldetect\u device
与值进行比较
如果要使用修饰符,正确的方法是这样():
关于缓存结果,您不必存储Mobile_Detect对象,而是存储其结果(浏览器字符串)。为此,您可以使用PHP的常用方法来持久化值:您可以使用$GLOBALS
变量空间,或者,如果您使用的是会话,则将结果存储在会话中(如果用户使用不同的浏览器登录,则会有所不同)。饼干也是如此
会话/cookie方法更好,因为它将在整个用户会话(或更长时间)中缓存结果,而不是每次页面加载一次
{'isiOS'|detect_device}