Created
April 26, 2011 05:31
-
-
Save adaburrows/941836 to your computer and use it in GitHub Desktop.
Sketch of how to make a functional style controller in PHP
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
<?php | |
/** | |
* This is by no means complete, but it's a sketch of an idea I had to create a | |
* classless functional style framework for PHP. | |
* | |
* It might turn out to be something cool! | |
*/ | |
// This function allows creating a new function from two functions passed into it | |
function compose(&$f, &$g) { | |
// Return the composed function | |
return function() use($f,$g) { | |
// Get the arguments passed into the new function | |
$x = func_get_args(); | |
// Call the function to be composed with the arguments | |
// and pass the result into the first function. | |
return $f(call_user_func_array($g, $x)); | |
}; | |
} | |
// Convenience wrapper for mapping | |
function map(&$data, &$f) { | |
return array_map($f, $data); | |
} | |
// Convenience wrapper for filtering arrays | |
function filter(&$data, &$f) { | |
return array_filter($data, $f); | |
} | |
// Convenience wrapper for reducing arrays | |
function fold(&$data, &$f) { | |
return array_reduce($data, $f); | |
} | |
// Page controller | |
$page = function($method, $params) { | |
// Setup null fallback method | |
$$method = function() { | |
return null; | |
}; | |
// Page Index | |
$index = function() use($params) { | |
return "page->index\n"; | |
}; | |
// Method to view a page | |
$view = function() use($params) { | |
return "page->view->{$params['id']}\n"; | |
}; | |
// Method to add a page | |
$set = function() use($params) { | |
return "page->set->{$params['id']}\n"; | |
}; | |
// Method to delete a page | |
$delete = function() use($params) { | |
return "page->delete->{$params['id']}\n"; | |
}; | |
return $$method(); | |
}; | |
// Get the controller | |
$controller = 'page'; | |
$controller = $$controller; | |
// Methods to run | |
$methods = array('index', 'view', 'set', 'delete'); | |
// Fake params passed into the web app | |
$params = array('id' => 'index'); | |
// Curry the controller method, while composing it with print_r | |
/* Highly functional, I know... */ | |
$curry = function($method) use($controller,$params) { | |
// Execute the controller method | |
print_r ($controller($method, $params)); | |
return null; | |
}; | |
// Run all the methods | |
map($methods, $curry); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, if you're still doing some PHP, and still looking into doing FP web apps, here's my attempt at it.
https://gist.github.com/noodlehaus/6539739