Callbacks

46 views
Skip to first unread message

v0idnull

unread,
Feb 22, 2011, 4:23:36 PM2/22/11
to GluePHP
if (is_callable($class))
{
call_user_func($class, $matches);
} elseif (class_exists($class)) {
$obj = new $class;
if (method_exists($obj, $method)) {
$obj->$method($matches);
} else {
throw new BadMethodCallException("Method, $method, not
supported.");
} else {
throw new Exception("$class is not a callback nor a valid
Class.");
}

why not?

Joe

unread,
Feb 24, 2011, 1:32:15 AM2/24/11
to GluePHP
> why not?

I just never ran into the need to do something like this. It's a nice
idea, though.

v0idnull

unread,
Feb 24, 2011, 9:57:35 PM2/24/11
to glu...@googlegroups.com
Doing this is a perfect solution for me.

I have an ini file called urls.ini :
[urls]
map.moduleIndex.path = "/([a-zA-Z]+)"
map.moduleIndex.callback[] = "\\Modules\\%1\\Index"
map.moduleIndex.callback[] = "indexAction"

map.controllerIndex.path = "/([a-zA-Z]+)/([a-zA-Z]+)"
map.controllerIndex.callback[] = "\\Modules\\%1\\%2"
map.controllerIndex.callback[] = "indexAction"

map.controllerAction.path = "/([a-zA-Z]+)/([a-zA-Z]+)/([a-zA-Z]+)"
map.controllerAction.callback[] = "\\Modules\\%1\\%2"
map.controllerAction.callback[] = "%3Action"

I added a method to Glue:

public static function url($url, $callback)
{
self::$urls[$url] = $callback;
}

and changed stick() to run() and iterated over self::$urls instead of an
array passed to the method, then I tweaked the code and did the following:

public static function run()
{
$method = strtoupper($_SERVER['REQUEST_METHOD']);
$path = $_SERVER['REQUEST_URI'];

$found = false;

// krsort($urls);

foreach (self::$urls as $regex => $class) {
$regex = str_replace('/', '\/', $regex);
$regex = '^' . $regex . '\/?$';
if (preg_match("/$regex/i", $path, $matches)) {
$found = true;
if (is_callable($class, true))
{
for ($i = 1; $i < count($matches); $i++)
{
$class[0] = str_replace('%'.$i, $matches[$i],
$class[0]);
$class[1] = str_replace('%'.$i, $matches[$i],
$class[1]);
}
$controller = new $class[0]();
$controller->{$class[1]}($matches);


} elseif (class_exists($class)) {
$obj = new $class;
if (method_exists($obj, $method)) {
$obj->$method($matches);
} else {
throw new BadMethodCallException("Method,
$method, not supported.");
}
} else {

throw new LogicException(str_replace("\n", " ",
print_r($class, true)).' -- not a valid callback or class name');
}
break;
}
}
if (!$found) {
throw new Exception("URL, $path, not found.");
}
}

And thus, with the zend framework's Zend_Config_Ini I can now do this:

$config = new Zend_Config_Ini('urls.ini');
foreach ($config->urls->map as $mapName => $settings)
{
Glue::url($settings->path, $settings->callback->toArray());
}

And poof, routes set up!

Anyways, thanks for Glue. Reminds me a lot of Flask for Python and I
never thought about bringing into PHP.

Reply all
Reply to author
Forward
0 new messages