概述 快速入门 教程 手册 最佳实践 组件 参考 贡献

发布于 2015-08-27 16:47:35 | 111 次阅读 | 评论: 0 | 来源: 网络整理

The ExpressionLanguage component already provides a compile() method to be able to cache the expressions in plain PHP. But internally, the component also caches the parsed expressions, so duplicated expressions can be compiled/evaluated quicker.

The Workflow

Both evaluate() and compile() need to do some things before each can provide the return values. For evaluate(), this overhead is even bigger.

Both methods need to tokenize and parse the expression. This is done by the parse() method. It returns a ParsedExpression. Now, the compile() method just returns the string conversion of this object. The evaluate() method needs to loop through the “nodes” (pieces of an expression saved in the ParsedExpression) and evaluate them on the fly.

To save time, the ExpressionLanguage caches the ParsedExpression so it can skip the tokenize and parse steps with duplicate expressions. The caching is done by a ParserCacheInterface instance (by default, it uses an ArrayParserCache). You can customize this by creating a custom ParserCache and injecting this in the object using the constructor:

use SymfonyComponentExpressionLanguageExpressionLanguage;
use AcmeExpressionLanguageParserCacheMyDatabaseParserCache;

$cache = new MyDatabaseParserCache(...);
$language = new ExpressionLanguage($cache);

注解

The DoctrineBridge provides a Parser Cache implementation using the doctrine cache library, which gives you caching for all sorts of cache strategies, like Apc, Filesystem and Memcached.

Using Parsed and Serialized Expressions

Both evaluate() and compile() can handle ParsedExpression and SerializedParsedExpression:

// ...

// the parse() method returns a ParsedExpression
$expression = $language->parse('1 + 4', array());

echo $language->evaluate($expression); // prints 5
use SymfonyComponentExpressionLanguageSerializedParsedExpression;
// ...

$expression = new SerializedParsedExpression(
    '1 + 4',
    serialize($language->parse('1 + 4', array()))
);

echo $language->evaluate($expression); // prints 5
最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务