Created
May 21, 2015 19:04
-
-
Save markknol/3eccc27b8590938c7f50 to your computer and use it in GitHub Desktop.
Basic Haxe Dispatch example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package; | |
import haxe.web.Dispatch; | |
import haxe.web.Request; | |
import php.Lib; | |
/** | |
Dispatch Example | |
* Make sure `mod_rewrite` is enabled | |
* You can add any `doBla` in Routes and it becomes an url /bla | |
@author Mark Knol | |
**/ | |
class Main | |
{ | |
public static function main() { | |
var url = Request.getURI().split(Routes.BASE_URL)[1]; | |
Dispatch.run(url, Request.getParams(), new Routes()); | |
} | |
} | |
class Routes { | |
// Base path when url is http://localhost/my_website/bin/ | |
static public inline var BASE_URL:String = "/my_website/bin/"; | |
var users = [ | |
{id: 1, name: "Mark", age: 30 }, | |
{id: 2, name: "Johan", age: 42 }, | |
{id: 3, name: "Mary", age: 29 } | |
]; | |
public function new() { | |
Lib.println('<style>* { font-family: helvetica, arial, sans-serif}</style>'); | |
Lib.println('<h4>Navigation:</h4>'); | |
Lib.println('<a href="${BASE_URL}">Home</a> | <a href="${BASE_URL}users/">Users</a> | <a href="${BASE_URL}contact/">Contact</a><br>'); | |
Lib.println("<hr/>"); | |
} | |
/** | |
url: / | |
**/ | |
function doDefault(dispatcher:Dispatch):Void { | |
Lib.println('<h1>Home</h1>'); | |
} | |
/** | |
url: /contact | |
**/ | |
function doContact(dispatcher:Dispatch):Void { | |
Lib.println('<h1>Contact us</h1>'); | |
} | |
/** | |
url: /users/ | |
**/ | |
function doUsers(dispatcher:Dispatch):Void { | |
Lib.println('<h1>Users</h1>'); | |
Lib.println('<ul>'); | |
for (user in users) | |
{ | |
Lib.println('<li><a href="${BASE_URL}user/${user.id}">${user.name}</a>'); | |
} | |
Lib.println('</ul>'); | |
} | |
/** | |
url: /user/{id}/ | |
**/ | |
function doUser(dispatcher:Dispatch, id:Int ):Void { | |
var user = users.filter(function(u) return u.id == id)[0]; | |
Lib.println(' | |
<h1>Profile page</h1> | |
<h3>User</h3> ${user.name} | |
<h3>Age</h3> ${user.age} | |
'); | |
Lib.println('<hr/><a href="${BASE_URL}users">« back</a>'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment