Hacker News new | ask | show | jobs
by jermaustin1 328 days ago
I actually started my own PHP based on C# called CHP for fun.

It runs atop whatever the current dotnet hosting service is (Kestrel?). It takes everything inside the "<? ?>" code blocks and inlines it into one big Main method, exposing a handful of shared public convenience methods (mostly around database access and easy cookie-based authentication), as well as the request and response objects.

Each request is JITed, then the assembly is cached in memory for future requests to the same path, and it will recompile sources that are newer than the cached assembly.

There is no routing other than dropping the .chp extension if you pass "-ne" into the arguments launching the server.

It's not very far along, and is completely pointless other than for the sake of building my own web language thingy for the first time since 2003.

1 comments

Have you looked into the string interpolation & verbatim operators as a templating alternative? These can be combined to create complex, nested strings:

  var reportPartial = @$"
    <h1>{report.Name}</h1>
    <table>
      {string.Join('\n', report.Items.Select(reportItem => @$"
        <tr>
          <td>{reportItem.Col1}</td>
          <td>{reportItem.Col2}</td>
        </tr>
      "))}
    </table>
  ";
In more complex views or reuse scenarios, I'd push the inner interpolation loop to a method.

This is how I've been building my .NET web apps for the last ~3 years. @+$ = PHP in C# as far as I'm concerned.

Some dangers with injection attacks if you don't santitize inputs correctly, but this is probably faster than most templating languages like razor.
There are a lot of ways to manage this problem. My preferred path is to wrap interpolated fields with HttpUtility.UrlEncode() when I know a user can touch it and there are plausible reasons for allowing 'illegal' characters at form submit time.

In terms of performance, it is definitely faster. The amount of time it takes to render these partials is negligible. You'd have to switch up your tooling to measure things in microseconds instead of milliseconds if you wanted any meaningful signal.

The only thing that would be comparable might be something like RazorSlices.
It's super easy to add sanitization middleware in .NET.