سؤال

I have an abstract base Controller class and all action controllers are derived from it.

Base Controller class at construction initializes View object. This View object is used by all action controllers. Each action controller have different dependencies (this is solved by using DI container).

The problem is that base Controller class also needs some dependencies (or parameters), for example, path to view folder. And the question is - where and how to pass parameters to base Controller class?

$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();
هل كانت مفيدة؟

المحلول

This is just a basic example. Why is the $view private? Is there a good reason?

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();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top