How to structure a PHP service that responds to Ajax requests -
i'm struggling design server-side script responds requests ajax application.
in current state, app divided discrete pages (e.g., orders, items, finances, etc.). when switch between these pages actual webpage reload. each page has it's own "operator", required root operator.php
, ajax requests directed.
contained in each operator pattern:
foreach ($actions $action) { switch ($action) { case 'get-items': [...] break; case 'get-item': [...] break; case 'update-item': [...] break; [...] } }
the $actions
supplied request, e.g. operator.php?page=items&action=get-item&id=123
.
as application became more complicated, helped separate logic of each action from context action requested.
i found use pattern when wanted use action's logic internally in php:
$items = json_decode(file_get_contents('http://[...]/operator.php?action=get-items'));
(needless say, design creates lot of overhead.)
so instead have operator
class extended each page. can create, instance, itemsoperator, , directly call action want, without encoding or decoding or superfluous http requests:
$items = $itemsoperator->getitems();
i modified script responds ajax requests use operator class, so:
foreach ($actions $action) { switch ($action) { case 'get-items': $json['items'] = $operator->getitems(); break; [...] } } if (count($json)) { echo json_encode($json); }
this approach works reasonably well, i've never had formal web development training, , suspect there established, better-abstracted patterns (which maddeningly can't find on google). numerous shortcomings home-brew approach inspired question:
- the concept of "operator" class contains "actions" vague , all-encompassing. how should separate logic?
- where approach gets messy when need to, instance, search items db on finances page. include itemsoperator alongside financesoperator? (i duplicate logic.)
- is there better way interface ajax request script operator objects (assuming shouldn't totally dump concept of operators)? instance, have write script each page maps url "action" variable corresponding method of operator object.
very sorry if question open-ended. don't have developers around me bounce ideas off of (and said, haven't had real training) — it's invaluable hear advice of community. when designing script one, number of possibilities/approaches/strategies can totally overwhelming. , once you've invested couple days time in 1 particular approach, can difficult turn back.
thanks consideration (and reading far).
not full answer, separate operator.php
2 files. 1 called operator.php
, , other operator_ajax.php
. operator.php
have doing now, instead of echoing it, puts variable can included. operator_ajax.php
includes operator.php
, echos value. operator.php
can included other file wish (replacing http request).
Comments
Post a Comment