[英]Pass container object in XSLTProcessor
有什么方法可以傳遞或綁定Container對象並在XSLTProcessor中調用Service對象的方法。 就像是。
XSLTProcessor::registerFunction(); //in php file.
在xsltStylesheet中
<xslt:value-of select="php:function('serviceobject::serviceObjectMethod',string($xsltProcessingVariable))"/>
在“普通” php代碼中,您可以執行以下操作
<?php
class Foo {
public function __construct($prefix) {
$this->prefix = $prefix;
}
public function myMethod($id) {
return sprintf('%s#%s', $this->prefix, $id);
}
}
$fooA = new Foo('A');
$fooB = new Foo('B');
echo call_user_func_array( array($fooA, 'myMethod'), array('id1') ), "\r\n";
echo call_user_func_array( array($fooB, 'myMethod'), array('id1') ), "\r\n";
即,您不給函數call_user_func_array
僅函數名,而是傳遞一個array($obj, 'methodName')
來調用實例方法。
Unfortunatley似乎不適用於php:function(...)
而且我還沒有找到另一種簡單/干凈的方法來做到這一點。
但是您可以在查找表string_id-> object中注冊您的對象,然后使用類似
select="php:function('invoke', 'obj1', 'myMethod', string(@param1), string(@param2))"
在您的樣式表中。 function invoke($objectId, $methodName)
現在必須找到已在$objectId
下注冊的$objectId
,然后像前面的示例一樣調用該方法。
func_get_args()使您可以檢索傳遞給函數的所有參數,甚至包括那些未在函數簽名中聲明的參數。 切斷前兩個元素(即$ objectId和$ methodName),並將其余的數組作為參數傳遞給call_user_func_array。
獨立的示例:
<?php
class Foo {
public function __construct($prefix) {
$this->prefix = $prefix;
}
public function myMethod($id) {
return sprintf('%s#%s', $this->prefix, $id);
}
}
function invoke($objectId, $methodname)
{
static $lookup = array();
$args = func_get_args();
if ( is_null($methodname) ) {
$lookup[$objectId] = $args[2];
}
else {
$args = array_slice($args, 2);
return call_user_func_array( array($lookup[$objectId], $methodname), $args);
}
}
// second parameter null -> register object
// sorry, it's just a quick hack
// don't do this in production code, no one will remember after two weeks
invoke('obj1', null, new Foo('A'));
invoke('obj2', null, new Foo('B'));
$proc = new XSLTProcessor();
$proc->registerPHPFunctions();
$proc->importStyleSheet(new SimpleXMLElement( style() ));
echo $proc->transformToXML(new SimpleXMLElement( document() ));
function document() {
return <<<EOB
<doc>
<element id="id1" />
<element id="id2" />
</doc>
EOB;
}
function style() {
return <<<EOB
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl">
<xsl:output method="text"/>
<xsl:template match="element">
Obj1-<xsl:value-of select="php:function('invoke', 'obj1', 'myMethod', string(@id))"/>
|||
Obj2-<xsl:value-of select="php:function('invoke', 'obj2', 'myMethod', string(@id))"/>
</xsl:template>
</xsl:stylesheet>
EOB;
}
版畫
Obj1-A#id1
|||
Obj2-B#id1
Obj1-A#id2
|||
Obj2-B#id2
順便說一句:不要像在本示例中那樣實現您的invoke()函數。 對於這個簡單的示例,我只是沒有想出一種更好的方法來實現register()/ invoke()功能;-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.