2016-10-10 3 views
0

슬림 프레임 워크 3이 새로 도입되었습니다. 이해해야 할 한 가지는 라우터 "012"를 사용하는 방법입니다. ""은 "글로벌"템플릿입니다.슬림 프레임 워크 3 - 글로벌 템플릿에서 라우터 사용하기

내말은 모든 페이지에 나타나는 탐색 메뉴와 같은 템플릿입니다. 내가 함께 설치된 example tutorial에 따라, "PHP-보기"라이브러리를 사용하고 템플릿에 대한

: 내 템플릿 디렉토리에서

composer require slim/php-view

을 나는 출력하고자 nav.php라는 파일이 내 링크.

나는 그렇게

<a href="<?=$router->pathFor('sign-up')?>">Sign Up</a> 

같은 라우터를 호출하지만 ... 예제 튜토리얼은 당신이 1 개인 곳, 예를 들어,에서 해당 링크를 전달하는 방법을 보여줍니다하는 방법을 이해 $app->get('/sign-up' ... })->setName("sign-up");

모든 개별 URL 경로에 매개 변수로 전달하지 않고도 템플릿을 전역 적으로 사용할 수 있습니까?

저는 CakePHP와 같은 프레임 워크에 익숙합니다. CakePHP에서는 모든 요청에서 전역 적으로 설정할 수있는 "AppController"가 있습니다. 이것이 슬림에서 어떻게 이루어 졌는지는 모르겠지만, 이것이 내가 뒤 따르는 효과입니다.

답변

2

글쎄, 당신은 template variable로 전달할 수 있습니다 검색 할 수 있습니다. 당신이 등록하고 가정

// via the constructor 
$templateVariables = [ 
    "router" => "Title" 
]; 
$phpView = new PhpRenderer("./path/to/templates", $templateVariables); 

// or setter 
$phpView->setAttributes($templateVariables); 

// or individually 
$phpView->addAttribute($key, $value); 

: 인스턴스화 또는 용기에 PhpRenderer을 등록 할 때

, 당신은 당신의 모든 템플릿에 액세스 할 수있는 변수 즉, "글로벌"변수를 정의하는 여러 옵션이 있습니다 여드름을 통해 PhpRenderer는 :

<?php 
// Create application instance 
$app = new \Slim\App(); 

// Get container 
$container = $app->getContainer(); 

// Register PhpRenderer in the container 
$container['view'] = function ($container) { 

    // Declaring "global" variables 
    $templateVariables = [ 
     'router' => $container->get('router') 
    ]; 

    // And passing the array as second argument to the contructor 
    return new \Slim\Views\PhpRenderer('path/to/templates/with/trailing/slash/', $templateVariables); 
}; 
+1

이것은 아마 그것을 할 수있는 가장 좋은 방법입니다. 컨테이너 팩토리에서 렌더러를 설정하면 컨테이너의 라우터 인스턴스를 가져 와서 렌더러에 템플릿 변수로 전달할 수 있습니다. – geggleto

+0

@geggleto이 문제는 전체 라우터 객체를 모든 템플릿으로 전달한다는 점에서 문제가 있습니다.내 템플릿에서'var_dump ($ router);'를 수행하면 DB 자격 증명을 포함하여 필요없는 것들이 포함 된 거대한 배열이 있습니다. 명명 된 경로에 액세스 할 수있는 곳에서보다 효율적인 방법이 있는지 확실하지 않은 경우? –

+0

개체는 기본적으로 참조로 전달되므로이 솔루션에는 성능상의 불이익이 없습니다. 비 프리미티브 템플릿이 많은 경우 [Slim Twig-view 구성 요소] (https://github.com/slimphp/Twig-View)를 사용하는 것이 좋습니다. 150 줄보다 훨씬 강력한 Twig 라이브러리가 사용됩니다 단일 클래스 PhpRenderer. –

0

새 클래스를 만들어야합니다. MainMenu를 사용하면 메뉴의 모든 경로가있는 배열을 만들어야합니다. MainMenu의 개체 라벨 및 경로 배열을 반환해야하고 당신이보기에 그 배열을 전달할 수 있습니다

$menu = (new MainMenu())->buildMenu(); 
$response = $this->view->render($response, "index.phtml", [ 
    'menu' => $menu 
]); 

이 그런 다음 *.phtml 파일에 당신이 $menu 변수에 액세스 할 수 있습니다. 그러나 각 경로에서이 코드를 반복하지 않으려면 어떻게해야합니까?

middlewares을 사용하십시오. 당신은

$request = $request->withAttribute('foo', 'bar'); 

를 사용하여 미들웨어에서 변수를 전달하고

$foo = $request->getAttribute('foo'); 
0
<?php namespace App\Helpers; 

/********************/ 
//LinksHelper.php 
/********************/ 

use Interop\Container\ContainerInterface; 

class LinksHelper 
{ 
    protected $ci; 

    public function __construct(ContainerInterface $container){ 
     $this->ci = $container; 
    } 

    public function __get($property){ 
     if ($this->ci->has($property)) { 
      return $this->ci->get($property); 
     } 
    } 

    public function pathFor($name, $data = [], $queryParams = [], $appName = 'default') 
    { 
     return $this->router->pathFor($name, $data, $queryParams); 
    } 

    public function baseUrl() 
    { 
     if (is_string($this->uri)) { 
      return $this->uri; 
     } 
     if (method_exists($this->uri, 'getBaseUrl')) { 
      return $this->uri->getBaseUrl(); 
     } 
    } 

    public function isCurrentPath($name, $data = []) 
    { 
     return $this->router->pathFor($name, $data) === $this->uri->getPath(); 
    } 

    public function setBaseUrl($baseUrl) 
    { 
     $this->uri = $baseUrl; 
    } 
} 

?> 

<?php 
/********************/ 
//dependencies.php 
/********************/ 

$container['link'] = function ($c) { 
    return new \App\Helpers\LinksHelper($c); 
}; 

// view renderer 
$container['view'] = function ($c) { 
    $settings = $c->get('settings'); 
    $view = new App\Views\MyPhpRenderer($settings['renderer']['template_path']); 
    $view->setLayout('default.php'); 
    //$view->addAttribute('title_for_layout', $settings['title_app'] .' :: '); 
    $view->setAttributes([ 
     'title_for_layout'=>$settings['title_app'] .' :: ', 
     'link' => $c->get('link') 
    ]); 
    return $view; 
}; 
?> 


<?php 
/********************/ 
//routes.php 
/********************/ 


use Psr\Http\Message\ServerRequestInterface as Request; 
use Psr\Http\Message\ResponseInterface as Response; 

$app->get('/', function (Request $request, Response $response, array $args) { 
    return $this->view->render($response, 'your_view.php'); 
})->setName('home'); 
?> 

<?php 
/********************/ 
//your_view.php 
/********************/ 
?> 

<a href="<?=$link->pathFor('home')?>">Home</a> 
관련 문제