PatrickLouys / no-framework-tutorial

A small tutorial to show how to create a PHP application without a framework.
MIT License
1.53k stars 186 forks source link

Creating a Base Controller and extend it - but how to deal with lots of constructor parameters? #60

Closed koraykupe closed 7 years ago

koraykupe commented 7 years ago

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

basherr commented 7 years ago

Can you a make gist what you have done so far so we can guide you accordingly...!

koraykupe commented 7 years ago

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.

PatrickLouys commented 7 years ago

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.