php - Silex variable mount point? -
i have series of pages route definitions:
$app->get('/{region}/{instance}/events', 'myapp\eventscontroller::index'); $app->post('/{region}/{instance}/events', 'myapp\eventscontroller::add'); $app->get('/{region}/{instance}/event/{id}', 'myapp\eventscontroller::edit'); $app->post('/{region}/{instance}/event/{id}', 'myapp\eventscontroller::update');
i have eventscontroller
class has have region
, instance
parameters 4 functions (index
, add
, edit
, , update
). i'm wondering if it's possible clean up, , possibly move region
, instance
values global $app
object.
i'd love able do
$app->mount('/{region}/{instance}/', new myapp\eventscontrollerprovider());
and have eventscontrollerprovider
validate region
, instance
variables, , map "event" routes on top of path, seems mount points can't contain variables (the controllerproviderinterface::connect()
method doesn't allow parameters).
is there clean way this? thought of method, seems counter other routing mechanisms:
$app->get('/{region}/{instance}/{action}' function($region, $instance, $action) use ($app) { if ($app['myapp.valid-region']($region) === false) return $app->abort(404); if ($app['myapp.valid-instance']($instance) === false) return $app->abort(404); switch ($action) { case 'events': $c = new myapp\eventscontroller(); return $c->index(); } });
years later, found solution. may not have existed then, now. mentioned in original question, controllerprovider
doesn't have additional parameters can helpful, middleware can solve issue:
$app->mount('/{region}/{instance}/', new myapp\eventscontrollerprovider()) ->before(function(request $r, application $a) { $region = $r->attributes->get('region'); $instance = $r->attributes->get('instance'); $regioninfo = $a['myregionservice']($region, $instance); if ($regioninfo === false) { return $a->abort(404, 'no such region'); } $a['currentregioninfo'] = $regioninfo; });
now, controllers mounted under eventscontrollerprovider
don't need validation on region/instance, since that's done beforehand (and 404 returned if there's problem). if controllers need know current region, can pull out of $a['currentregioninfo']
, since have been set already. because middleware bound specific route collection, it's not called other routes defined in application.
the variables defined in url exposed on request
object under attributes
parameter. technically of controllers still region
, instance
parameters passed methods, there's no need now.
Comments
Post a Comment