@nera4llife
Сторонник гелиоцентр

Как убрать кучу аргументов у класса?

Прошестил инет на тему внедрение зависимостей, ниче не понял, но сделал контейнер
Код контейнера
class Container
{
    public $request;
    public $router;
    public $view;
    public $validator;
    public $redirect;
    public $session;
    public $config;
    public $database;
    public $auth;
    public $storage;
    public $csrf;
    public $notification;
    public $logger;

    function __construct()
    {
        $this->registerServices();
    }

    private function registerServices()
    {
        $this->request = Request::createFromGlobals();
        $this->validator = new Validator();
        $this->request->setValidator($this->validator);
        $this->logger = new Logger(
            $this->request->server['HTTP_USER_AGENT'],
            $this->request->server['REMOTE_ADDR']
        );
        $this->config = new ConfigFile();
        $this->database = new Database($this->config, $this->logger);
        $this->redirect = new Redirect();
        $this->session = new Session();
        $this->auth = new Auth($this->database, $this->session);
        $this->notification = new Notification($this->database);
        $this->view = new View($this->session, $this->auth, $this->notification);
        $this->storage = new Storage($this->config);
        $this->csrf = new CSRF($this->session);
        

        $this->router = new Router(
            $this->view,
            $this->request,
            $this->redirect,
            $this->session,
            $this->database,
            $this->auth,
            $this->storage,
            $this->config,
            $this->csrf,
            $this->notification,
            $this->logger
        );
    }


в роутер уже куча параметров передается (мне это кажется неверным) и с роутера они прокидываются в контроллер
spoiler
// ...
[$controller, $action] = $route->getAction();

$controller = new $controller();

call_user_func([$controller, 'setView'], $this->view);
call_user_func([$controller, 'setRequest'], $this->request);
call_user_func([$controller, 'setRedirect'], $this->redirect);
call_user_func([$controller, 'setSession'], $this->session);
call_user_func([$controller, 'setDatabase'], $this->database);
call_user_func([$controller, 'setAuth'], $this->auth);
call_user_func([$controller, 'setStorage'], $this->storage);
call_user_func([$controller, 'setConfig'], $this->config);
call_user_func([$controller, 'setCsrf'], $this->csrf);
call_user_func([$controller, 'setNotification'], $this->notification);
call_user_func([$controller, 'setLogger'], $this->logger);

if ($route->hasParams()) {
    call_user_func([$controller, $action], $uri);
} else {
    call_user_func([$controller, $action]);
}
// ...


Причем не всегда все эти классы используются в контроллере. Плюс сейчас надо добавить еще парочку классов, соответственно еще добавления в роутер и прокидывание в контроллер. Зашел в тупик, помогите улучшить пожалуйста
  • Вопрос задан
  • 1028 просмотров
Решения вопроса 1
SilenceOfWinter
@SilenceOfWinter Куратор тега PHP
та еще зажигалка...
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 2
@maxlarcenko
Паттерн Строитель тебе в помощь
Ответ написан
tkovacs
@tkovacs
веб мастер
Думаю тебе нужно узнать какие аргументы требует метод контроллера, скорее всего через reflection api. Затем через контейнер зависимостей создавать необходимые объекты и желательно где то заложить возможность создавать правила по которым будет создан объект по аналогии с app bind в сервис провайдерах laravel
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы