model view controller - PHP MVC. Am I doing it correctly? -
i've created simple servicefactory class, runs other service classes, stores , gets instances. same servicefactory object shared between both view object , controller object.
the controller changes state of service:
class user extends controller { public function index($user) { $userservice = $this->service->run('user'); $userservice->index($user); } } the view gets data service , decides template use:
class user extends view { public function index() { $userservice = $this->service->get('user'); $this->data = $userservice->data; $this->template = 'user/index'; // render } } am doing correctly?
in this answer tereško said that: "controller responsible changing state of both view , model." controller has nothing view. see examples of how controller , view should work (model2 mvc).
am doing right?
sort of.
let's start extends. when use extends, you're implying is-a relationship, when user extends controller, you're saying user is-a controller. case? no. perhaps rename usercontroller , make more sense contextually.
$userservice = $this->service->get('user'); this called service locator, , it's known anti-pattern. why anti-pattern? because in object oriented programming, each object's public methods api it's usage, , should able see objects requirements entirely it's constructor , method signatures.
with code, developer has read through whole thing see "oh, here's i'm using object" , further down "here's i'm using another".
your code should read this:
public function index(userservice $userservice) { $user = $userservice->getdata(); } with code change, developers can see external objects object requires function - , testable (not test controllers contain no logic - they're 'glue' code tested).
you should injecting components , view controller:
class usercontroller extends controller { public function index(userservice $userservice, view $view) { /** or similar **/ return $view->render($userservice->getdata()); } } some people inject view, people inject templateengine twig, , called render on data. it's you, can delve more specifics given current scenario.
if you're wondering how inject user service index action, that's job of dependency injector auryn uses reflection read object constructor or method signatures determine create before injecting them automatically in controllers.
laravel stole idea , has implemented controllers, symfony follow along soon.
closing note: don't try , strictly adhere 'mvc' - it's not possible in classical sense php request -> response -> dead cycle. instead, focus on separation of concerns associated , make code maintainable, testable , easy read.
Comments
Post a Comment