2014-04-01 1 views
0

저는 PHP로 내 자신의 작은 MVC 프레임 워크를 구축하고 있습니다. 더 나은 이해를 얻고 배우기 위해서입니다.의존성 주입 컨테이너에 전역으로 액세스하는 방법

저는 라우터로 작은 프레임 워크를 만들었습니다.

내 index.php에 내 응용 프로그램 용 컨테이너를 만들었습니다.

index.php를

use \Oak\Route\Route as Route; 
use \Oak\Route\Routes as Routes; 
use \Oak\App\App as App; 

$routes = new Routes(); 

$routes->addRoute(new Route('home', 'index', 'index')); 
$routes->addRoute(new Route('user/{username}/{id}', 'index', 'about')); 
$routes->addRoute(new Route('help', 'help', 'index')); 

$container = new Container(); 
$container->set('app', function() use ($routes) { 
    return new App($routes, new \Oak\Header\Request()); 
}); 

$app = $container->get('app'); 
$app->run(); 

Container.php & ContainerInterface.php

interface ContainerInterface { 

public function set($name, $service); 
public function get($name, array $params = array()); 
public function has($name); 
public function remove($name); 
public function clear(); 
} 

class Container implements ContainerInterface { 

    protected $services = array(); 

    public function set($name, $service) { 
     if(!is_object($service)) { 
      throw new InvalidArgumentException("Only objects can be registred"); 
     } 

     if(!in_array($service, $this->services, true)) { 
      $this->services[$name] = $service; 
     } 
     return $this; 
    } 

    public function get($name, array $params = array()) { 
     if(!isset($this->services[$name])) { 
      throw new RuntimeException($name ." has not been registred in the container"); 
     } 
     $service = $this->services[$name]; 

     return !$service instanceof Closure ? $service : call_user_func_array($service, $params); 
    } 

    public function has($name):bool { 
     return isset($this->services[$name]); 
    } 

    public function remove($name) { 
     if(isset($this->services[$name])) { 
      unset($this->services[$name]); 
     } 
     return $this; 
    } 

    public function clear() { 
     $this->services = array(); 
    } 

    public function getServices():array { 
     return $this->services; 
    } 
} 

내 질문에 내가 내 컨트롤러 내 APP-에서 컨테이너에 액세스 할 수 있도록 어떻게 지금 파일 등 하나의 솔루션은 컨테이너에서 Singleton 또는 정적 메서드를 사용하는 것일까?

blogposts 및 주제에 대한 기사를 많이 읽었지만 모든 예제가 색인 파일의 컨테이너와 만 통신하는 것 같습니다.

나는 또한 상속을 실험하기 시작했다. 그 응용 프로그램은 컨테이너를 확장 한 다음 컨트롤러에 전달했다.

제 질문은, 앱에있는 모든 곳에서 컨테이너에 액세스 할 수있게하려면 어떻게해야할까요? 코드 도처에 그런

class Container { 
    private static $instance; 
    //prevent from creating a container class by itself 
    private function __construct() {};  
    /* .... */ 
    public static function getInstance() { 
     if (self::$instance === null) { 
      self::$instance = new Container(); 
     } 
    } 
} 

대신 사용 어쨌든 $container = new Container(); 사용 $container = Container::getInstance();

내가보기 엔 당신이 여드름을 체크 아웃 (http://pimple.sensiolabs.org/를) 추천 :

답변

0

체크 아웃 단일 디자인 패턴은 .. 당신은 그런 뭔가가 필요 게으른 로딩과 함께 아주 좋은 코드입니다. 여드름처럼 좋은 것을 많이 쓰고 많은 것을 쓸 수있는 많은 시간이 필요합니다.