为了让一些了解超文本标记语言的UI开发者和了解.NET的后端开发者能够更好地协作,我们正在考虑一种架构,在该架构中,我们使用MVC应用程序,并使用phalanger作为视图引擎。
除了一点以外,将phalanager集成为视图模型看起来相当容易。我不确定如何将模型传递给页面脚本。有什么想法可以实现这一点吗?
一种想法是从php脚本调用一个静态的.NET方法,但感觉有点麻烦。我希望能够只将参数传递给脚本,并让脚本能够在变量中提取它。
发布于 2011-05-27 03:15:17
在后端使用.NET,在前端使用PHP (使用Phalanger)看起来是一个很好的方案。我认为最好的选择是用.NET实现模型,并使用PHP实现控制器和视图(直接或使用某个PHP框架)。
因为PHP代码可以访问.NET对象,所以从使用Phalanger编译的PHP调用.NET模型非常简单。假设您有一个包含以下类型的命名空间DemoDataLayer的C# DLL:
public class Data {
public List<Category> GetCategories() {
var ret = new List<Category>();
// Some code to load the data
return ret;
}
}然后,您可以从Phalanger网站引用PHP库(使用web.config),并使用Phalanger提供的C#扩展来使用Data类,就好像它是一个标准的PHP对象:
<?
import namespace DemoDataLayer;
$dl = new Data;
$categories = $dl->GetCategories();
?>
<ul>
<? foreach($categories as $c) { ?>
<li><a href="products.php?id=<? echo $c->ID ?>"><? echo $c->Name ?></a></li>
<? } ?>
</ul>要配置引用,您需要将C# DLL添加到bin目录,并将其包含在classLibrary元素中。上面使用的import namespace语法是一个特定于Phalanger的语言扩展(用于使用.NET名称空间),需要使用PhpClr功能打开它:
<?xml version="1.0"?>
<configuration>
<phpNet>
<compiler>
<set name="LanguageFeatures">
<add value="PhpClr" />
</set>
</compiler>
<classLibrary>
<add assembly="DemoDataLayer" />
</classLibrary>
</phpNet>
</configuration>发布于 2011-07-22 14:19:19
查看http://phpviewengine.codeplex.com/
该项目包含以下方法,用于将CLR类型转换为PHP脚本可以使用的形式:
object PhpSafeType(object o)
{
// PHP can handle bool, int, double, and long
if ((o is int) || (o is double) || (o is long) || (o is bool))
{
return o;
}
// but PHP cannot handle float - convert them to double
else if (o is float)
{
return (double) (float) o;
}
// Strings and byte arrays require special handling
else if (o is string)
{
return new PhpString((string) o);
}
else if (o is byte[])
{
return new PhpBytes((byte[]) o);
}
// Convert .NET collections into PHP arrays
else if (o is ICollection)
{
var ca = new PhpArray();
if (o is IDictionary)
{
var dict = o as IDictionary;
foreach(var key in dict.Keys)
{
var val = PhpSafeType(dict[key]);
ca.SetArrayItem(PhpSafeType(key), val);
}
}
else
{
foreach(var item in (ICollection) o)
{
ca.Add(PhpSafeType(item));
}
}
return ca;
}
// PHP types are obviously ok and can just move along
if (o is DObject)
{
return o;
}
// Wrap all remaining CLR types so that PHP can handle tham
return PHP.Core.Reflection.ClrObject.WrapRealObject(o);
}它可以像这样使用...
// Get setup
var sc = new ScriptContext.CurrentContext;
var clrObject = /* Some CLR object */
string code = /* PHP code that you want to execute */
// Pass your CLR object(s) into the PHP context
Operators.SetVariable(sc,null,"desiredPhpVariableName",PhpSafeType(clrObject));
// Execute your PHP (the PHP code will be able to see the CLR object)
var result = return DynamicCode.Eval(
code,
false,
sc,
null,
null,
null,
"default",
1,1,
-1,
null
);这甚至可以处理匿名类型。例如,在上面插入以下内容。
var clrObject = new { Name = "Fred Smith" };
Operators.SetVariable(sc,null,"person",PhpSafeType(clrObject));然后,您可以在PHP中访问它:
echo $person->Name;哪一项输出的是Fred Smith
https://stackoverflow.com/questions/6136208
复制相似问题