Closed koraykupe closed 7 years ago
Can you a make gist what you have done so far so we can guide you accordingly...!
I edited the question a bit.
The problem is actually having lots of dependency injection parameters in constructors of controllers.
I want to create a base controller and inject request, response, validation, repository, config etc.
But If I create a concrete controller by extending it and If I want to add someting to its controller, I'd need create the constructor with lots of parameters (lots of them same with base class) It looks like unnecessary.
abstract class BaseController
{
protected $request;
protected $response;
protected $renderer;
protected $config;
protected $cache;
protected $validator;
public function __construct(
Request $request,
Response $response,
Renderer $renderer,
Config $config,
Cache $cache,
Validator $validator
) {
$this->request = $request;
$this->response = $response;
$this->renderer = $renderer;
$this->config = $config;
$this->cache= $cache;
$this->validator = $validator;
}
class UserController extends BaseController
{
protected $userRepository;
public function __construct(
Request $request,
Response $response,
Renderer $renderer,
Config $config,
Cache $cache,
Validator $validator,
UserRepository $userRepository
) {
parent::__constructor($request, $response, $renderer, $config, $cache, $validator);
$this->userRepository = $userRepository;
}
I think I need some creational design pattern there, but which one and how?
Thanks.
Don't use extension here, that's not what it is meant for.
Your controller is doing too much. Refactor all application logic (like validation, calling a user repo etc) into services.
Hi,
Thanks for the tutorial. It is very helpful.
I've been trying to add more feeature like config, validation, log, repositories etc. and want to inject them to controllers via interfaces.
I created an abstract base controller and concrete controllers by extending it. But constructor parameters are growing. If I extend the base class and want to add more dependencies, I would need get same parameters again and call
parent::__constructor
. Is it reasonable? Is there a better way?Best Regards