2012-02-17 5 views
2

나는 추상적 인 기본 컨트롤러 클래스를 가지고 있으며 모든 액션 컨트롤러는이 클래스에서 파생됩니다.기본 클래스와 파생 클래스의 종속성 주입

건설중인 기본 컨트롤러 클래스는 View 개체를 초기화합니다. 이 View 객체는 모든 액션 컨트롤러에서 사용됩니다. 각 액션 컨트롤러는 서로 다른 종속성을가집니다 (DI 컨테이너를 사용하여 해결됨).

문제는 기본 컨트롤러 클래스도 일부 종속성 (또는 매개 변수) 경로를 볼 폴더가 필요합니다. 그리고 질문은 - 기본 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(); 
+0

private $ view; $ view가 비공개 인 이유는 무엇입니까? 로드 할보기 경로는 언제 알 수 있습니까? 액션 컨트롤러 내부? 그러면 쉽게 할 수 있습니다. – busypeoples

답변

0

이것은 단지 기본적인 예일뿐입니다. $보기가 비공개 인 이유는 무엇입니까? 좋은 이유가 있니?

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(); 
+0

빠른 ansver 주셔서 감사합니다! 뷰는 private이므로 getView() 메소드를 통해서만 액세스 할 수 있으므로 외부에서 재정의 할 수 없습니다. 죄송 합니다만, 부트 스트랩 파일에서 상수로 정의 된보기 경로 (예 : 'views /')가 하나뿐이라는 사실을 잊었습니다. 액션 컨트롤러의 생성자에서 뷰 패스를 전달하는 것이 정확하다고 느낍니다. 그러나 경로가 변경되지 않으면 다른 해결책 (DI 선호)이 있으므로 각 액션 컨트롤러는 상위 생성자를 호출하고 동일한보기 경로를 다시 전달할 필요가 없습니다. – Hemaulo

+0

가장 좋은 방법은 부모 추상 컨트롤러 내부에 기본 경로를 정의하는 것입니다. 개인 $보기 -> 경로 = "somepath"; – busypeoples

+0

@Hemaulo 당신은 액션 컨트롤러 내부의 생성자를 오버라이드하고 있습니다. 부모 :: __ 컨트롤러를 호출하지 않고 뷰를 어떻게 호출 할 것인가? – busypeoples

관련 문제