Last active
January 4, 2016 02:19
-
-
Save lancerushing/8554159 to your computer and use it in GitHub Desktop.
controller with service locator,
This file contains hidden or 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 | |
// ================================================================================= | |
// == Inject Service Locator into controller | |
// ================================================================================= | |
class ServiceLocator extends StrictClass | |
{ | |
/** | |
* @return UserService | |
*/ | |
public function userService() | |
{ | |
return new UserService($this->daoFacotory()->userDao()); | |
} | |
} | |
abstract class HttpController extends StrictClass | |
{ | |
/** | |
* @var ServiceLocator | |
*/ | |
protected $serviceLocator; | |
/** | |
* @var HttpResponse | |
*/ | |
protected $response; | |
/** | |
* @var HttpRequest | |
*/ | |
protected $request; | |
public function __construct(ServiceLocator $serviceLocator, HttpResponse $response, HttpRequest $request) // <-- Should I enject the serviceLocator | |
{ | |
$this->serviceLocator = $serviceLocator; | |
$this->response = $response; | |
$this->request = $request; | |
} | |
} | |
class UserController extends HttpController | |
{ | |
public function get() | |
{ | |
$data = $this->services->userService()->selectAll(); | |
// do stuff | |
} | |
public function post() | |
{ | |
$userDto = $this->services->userService()->create($this->request->params['firstName'], $this->request->params['lastName']); | |
// do stuff | |
} | |
} | |
// ================================================================================= | |
// == Inject explicit dependency into controller's method | |
// ================================================================================= | |
abstract class HttpControllerWithDI extends StrictClass | |
{ | |
/** | |
* @var HttpResponse | |
*/ | |
protected $response; | |
/** | |
* @var HttpRequest | |
*/ | |
protected $request; | |
public function __construct(HttpResponse $response, HttpRequest $request) | |
{ | |
$this->response = $response; | |
$this->request = $request; | |
} | |
} | |
class UserControllerWithDI extends HttpControllerWithDI | |
{ | |
public function get(UserService $userService) | |
{ | |
$data = $userService->selectAll(); | |
// do stuff | |
} | |
public function post(UserService $userService) | |
{ | |
$userDto = $userService->create($this->request->params['firstName'], $this->request->params['lastName']); | |
// do stuff | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment