Внедрение зависимостей в базовые и производные классы - PullRequest
2 голосов
/ 17 февраля 2012

У меня есть абстрактный базовый класс Controller, и все контроллеры действий получены из него.

Базовый класс Controller при построении инициализирует объект View. Этот объект View используется всеми контроллерами действий. Каждый контроллер действий имеет разные зависимости (это решается с помощью контейнера DI).

Проблема в том, что базовому классу Controller также нужны некоторые зависимости (или параметры), например, путь для просмотра папки. И вопрос - где и как передать параметры в базовый класс Controller?

$dic = new Dic();

// Register core objects: request, response, config, db, ...

class View
{
    // Getters and setters
    // Render method
}

abstract class Controller
{
    private $view;

    public function __construct()
    {
        $this->view = new View;

        // FIXME: How / from where to get view path?
        // $this->view->setPath();
    }

    public function getView()
    {
        return $this->view;
    }
}

class Foo_Controller extends Controller
{
    private $db;

    public function __construct(Db $db)
    {
        $this->db = $db;
    }

    public function barAction()
    {
        $this->getView()->some_var = 'test';
    }
}

require_once 'controllers/Foo_Controller.php';

// Creates object with dependencies which are required in __construct()
$ctrl = $dic->create('Foo_Controller');

$ctrl->barAction();

1 Ответ

0 голосов
/ 17 февраля 2012

Это просто базовый пример. Почему $ view является приватным? Есть ли веская причина?

class View {
  protected $path;
  protected $data = array();

  function setPath($path = 'standard path') {
    $this->path = $path;
  }

  function __set($key, $value) {
    $this->data[$key] = $value;
  }

  function __get($key) {
    if(array_key_exists($key, $this->data)) {
      return $this->data[$key];
    }
  }
}

abstract class Controller {
    private $view;

    public function __construct($path)
    {
       $this->view = new View;

       $this->view->setPath($path);
    }

    public function getView()
    {
        return $this->view;
    }
}

class Foo_Controller extends Controller {
    private $db;


    public function __construct(Db $db, $path)
    {
        // call the parent constructor.
        parent::__construct($path);
        $this->db = $db;
    }

    public function barAction()
    {
        $this->getView()->some_var = 'test';
    }

    public function getAction() {
      return $this->getView()->some_var;
    }
}

class DB {

}

$con = new DB;
$ctrl = new Foo_Controller($con, 'main');

$ctrl->barAction();
print $ctrl->getAction();
...