requestAction
主要是在CakePHP中用于呈现某些内容,应该在应用程序的所有页面上或最初未找到的页面上都可以找到它。
例如:在网站每个页面的页脚显示注册用户总数。
在requestAction方法中,这可以通过请求UsersController的操作来完成,该操作返回模型User的计数。让我们将其命名为usersCount()。该请求应采用该应用程序视图使用的布局。
在我建议的方法中,可以通过在AppControler中使用User模型然后为用户计数设置变量来实现,例如,在所有布局和视图中均应可用
//in AppController
function beforeRender(){
$this->uses = array('Model', 'User');
$this->set('totalUsers',$this->User->find('count'));
}
因此,在任何布局,视图或元素中,我们都可以轻松使用$ totalUsers值
<div class="footer">Currently, we have <?php echo $totalUsers;?> registered users.</div>
这里的“更好”一词是指性能。这两种方法中哪一种在性能上更好?
每当对几种可能性的相对性能有疑问时,请不要依赖他人的建议(这可能是纯粹的推测):profile。
DebugKit带有Benchmark shell,它是生成基准信息的便捷方法(seige和ab是两个更准确/可靠的替代方法):
$ cd my/app
$ Console/cake DebugKit.benchmark
Allows you to obtain some rough benchmarking statistics about a fully
qualified URL.
Usage:
cake debug_kit.benchmark [-h] [-v] [-q] [--n 10] [--t 100] <url>
Options:
--help, -h Display this help.
--verbose, -v Enable verbose output.
--quiet, -q Enable quiet output.
--n Number of iterations to perform. (default:
10)
--t Maximum total time for all iterations, in seconds.If a
single iteration takes more than the tiemout, only one request will be
made (default: 100)
Arguments:
url The URL to request.
Example Use: `cake benchmark --n 10 --t 100 http://localhost/testsite`.
Note: this benchmark does not include browser render times.
使用这样的工具将解决大多数关于性能的疑问-只需设置几个控制器动作并记下每个动作的相对性能即可。
让我们假设的问题不是使用requestAction是否比总是填充一个可能不使用(提示)的变量更好,而是:在所有/大多数页面上显示<something>的最佳方法是什么?
这里有2条简单的规则可以解决大多数问题:
requestAction
在某些方面,建议的两个选项中的某些选项更合适-但还有其他选项可以实现与给出的示例相同的结果。
而不是总是(一种或另一种方式)获取数据-一次获取,直到数据过时再获取。例如,在布局中使用元素缓存,这样就不会在每个请求上都执行元素中的内容:
echo $this->element(
'footer',
array(),
"cache" => array('config' => 'element_config', 'key' => 'footer')
);
footer
元素的内容应该是自给自足的,例如:
<?php
$User = ClassRegistry::init('User');
// $betterExample = $User->expensiveCall(); // more relevant where the call is slow
$totalUsers = $User->find('count');
?>
<div class="footer">Currently, we have <?php echo $totalUsers;?> registered users.</div>
这样,仅当没有缓存结果时才请求元素的数据。通过调整相关的缓存配置(适当的缓存配置取决于要求-需要多少实时性?使用例如30秒的缓存配置;是否过时没关系?使用1天),即计数器的频率可以修改更新。
或者,可以使用无限的缓存时间,而仅当值更改时才清除缓存:
class User extends AppModel {
public function updateCounterCache($keys = array(), $created = false) {
Cache::delete('footer', 'element_config');
return parent::updateCounterCache($keys, $created);
}
}
可以使用其他类似的技术(包括与结合使用元素requestAction
)-但原理始终相同:不要急于执行可能不需要的逻辑(获取数据),请有效地使用缓存。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句