글쓴사람 미바니
글쓴시간2009년 7월 14일 오전 9시 48분 1초
    제목ZendFramework 에서 템플릿언더바 써보기...동작은 되나...
관리자님 짱입니다. 언제나 변치 않는 답글^^

ZendFramework 에서 삽질하다 Zend_View 래퍼런스에 Smarty 클래스를 번외로 제공되어 있길래 글자만 고쳤을 뿐인데 동작이 되는군요...^^
오류가 있을꺼 같은데 충분히 테스트 하지 못하고 올렸습니다.

libraryZend/View/TemplateUnderbar.php 파일을 생성하고 다음소스를 넣는다.

-----------------------------------------------------------------------------------------------------------
<?
require_once("Template_.class.php");
class Zend_View_TemplateUnderbar implements Zend_View_Interface
{
    /**
     * Template_ object
     * @var Template_
     */
    public $Template_;

    /**
     * Constructor
     *
     * @param string $tmplPath
     * @param array $extraParams
     * @return void
     */
    public function __construct($tmplPath = null, $extraParams = array())
    {
         $this->Template_ = new Template_();

         if (null !== $tmplPath) {
              $this->setScriptPath($tmplPath);
         }

         foreach ($extraParams as $key => $value) {
              $this->Template_->$key = $value;
         }
    }

    /**
     * Return the template engine object
     *
     * @return Template_
     */
    public function getEngine()
    {
         return $this->Template_;
    }

    /**
     * Set the path to the templates
     *
     * @param string $path The directory to set as the path.
     * @return void
     */
    public function setScriptPath($path)
    {
         if (is_readable($path)) {
              $this->Template_->template_dir = $path;
              return;
         }

         throw new Exception($this->Template_->template_dir);
    }

    /**
     * Retrieve the current template directory
     *
     * @return string
     */
    public function getScriptPaths()
    {
         return array($this->Template_->template_dir);
    }

    /**
     * Alias for setScriptPath
     *
     * @param string $path
     * @param string $prefix Unused
     * @return void
     */
    public function setBasePath($path, $prefix = ‘Zend_View‘)
    {
         return $this->setScriptPath($path);
    }

    /**
     * Alias for setScriptPath
     *
     * @param string $path
     * @param string $prefix Unused
     * @return void
     */
    public function addBasePath($path, $prefix = ‘Zend_View‘)
    {
         return $this->setScriptPath($path);
    }

    /**
     * Assign a variable to the template
     *
     * @param string $key The variable name.
     * @param mixed $val The variable value.
     * @return void
     */
    public function __set($key, $val)
    {
         $this->Template_->assign($key, $val);
    }

    /**
     * Allows testing with empty() and isset() to work
     *
     * @param string $key
     * @return boolean
     */
    public function __isset($key)
    {
         return (null !== $this->Template_->getTemplate_vars($key));
    }

    /**
     * Allows unset() on object properties to work
     *
     * @param string $key
     * @return void
     */
    public function __unset($key)
    {
         $this->Template_->clear_assign($key);
    }

    /**
     * Assign variables to the template
     *
     * Allows setting a specific key to the specified value, OR passing
     * an array of key => value pairs to set en masse.
     *
     * @see __set()
     * @param string|array $spec The assignment strategy to use (key or
     * array of key => value pairs)
     * @param mixed $value (Optional) If assigning a named variable,
     * use this as the value.
     * @return void
     */
    public function assign($spec, $value = null)
    {
         if (is_array($spec)) {
              $this->Template_->assign($spec);
              return;
         }

         $this->Template_->assign($spec, $value);
    }

    /**
     * Clear all assigned variables
     *
     * Clears all variables assigned to Zend_View either via
     * {@link assign()} or property overloading
     * ({@link __get()}/{@link __set()}).
     *
     * @return void
     */
    public function clearVars()
    {
         $this->Template_->clear_all_assign();
    }

    /**
     * Processes a template and returns the output.
     *
     * @param string $name The template to process.
     * @return string The output.
     */
    public function render($name)
    {
         return $this->Template_->fetch($name);
    }
}

?>
-----------------------------------------------------------------------------------------------------
이 소스는 ZendFramework 레퍼런스에서 제공하는 smarty 쓰는 방법중에 나와있는 소스를
smarty -> template_ 라는 글자로만 고쳤다.
그래도 동작이 된다
버그가 있는지는 차근차근 써보면서 찾아보기록 하고 일단 잘되니 패스

----------------------------------------------------------------------------------------------------
set_include_path로
/library/Template_.2.2.4
경로를 세팅한다.
php.ini에 등록해도 되나 귀차니즘으로 header.php 같은곳에 넣어 쓰세요
----------------------------------------------------------------------------------------------------
Bootstrap.php에 다음 함수를 추가한다.
         function _initTemplate()
         {
              //xtac.net 에서 제공하는 Template_ 클래스 생성
              //경로는 환경 클래스(Zend_Config) 에서 등록하여 로드하는게 편하다
              $view = new Zend_View_TemplateUnderbar("템플릿경로");
              $view->Template_->compile_dir = "컴파일경로";
              $view->Template_->prefilter = "adjustPath";

              $view->Template_->define(Array(
                   "index"=>"index.tpl",
                   "header"=>"header.tpl",
                   "left"=>"left.tpl",
                   "content"=>"content.tpl",
                   "footer"=>"footer.tpl"
              ));
              Zend_Registry::set(‘Template_‘, $view->Template_);
              //$view->Template_->print_("index");

              //Zend_View 에서 Rander를 담당하는 인스턴스를 얻어와서 템플릿 언더바와 연결한다.
              $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper(‘viewRenderer‘);
              $viewRenderer->setView($view)
                        ->setViewBasePathSpec($view->Template_->template_dir)
                        ->setViewScriptPathSpec(‘index‘)
                        ->setViewScriptPathNoControllerSpec(‘:action.:suffix‘)
                        ->setViewSuffix(‘tpl‘);
              //setViewScriptPathSpec(‘index‘) 의 index는 위에 $view->Template_->define 에서 선언된 index 파일을 print_ 해준다.
         }

----------------------------------------------------------------------------------------------------

마지막으로
Action 에서
템플릿 언더바를 가져다 쓰기만 하면 된다.
class IndexController extends Zend_Controller_Action
    public function indexAction()
    {
         $subtitle = "TEST";
         $_tpl = Zend_Registry::get("Template_");
         $_tpl->define(array(‘content‘=>‘bbs/index.tpl‘));
         $_tpl->assign(array(‘subtitle‘=>$subtitle));
    }
}
----------------------------------------------------------------------------------------------------

잘되시나요?
관리자 미바니님 안녕하세요..

올려주신 소스에서 __isset, __unset, clearVars 메소드만 아래와 같이 고쳐주시면 될 것 같습니다.

public function __isset($key)
{
   return isset($this->Template_->var_[''][$key]);
}
public function __unset($key)
{
   unset($this->Template_->var_[''][$key]);
}
public function clearVars()
{
   $this->Template_->var_['']=array();
}    

몇 년 전에 온플래너님께서 올려주셨는데 보다 자세한 설명 감사합니다...
09-07-14 21:44
미바니 뉍^^ 감사합니다. 꾸벅~
09-07-14 22:11
관리자 그런데.. 좀.. 필요한 이야기 같아서요..

$view=Zend_Registry::get("view");
$view->assign(..);
echo $view->render('index.tpl');

이런 식으로 ZendFramework 가 제공하는 인터페이스(Zend_View_Interface)를 사용하려고 Zend_View_TemplateUnderbar 클래스(어댑터)를 만든 것인데.. 본문은 그냥 언더바 인터페이스를 사용하게 되는 것 같습니다..


아래와 같이 fetch 대신 xfetch 를 사용하면 Template_->define()을 생략하고 템플릿파일경로를 바로 $name에 전달할 수 있습니다.

public function render($name)
{
    return $this->Template_->xfetch($name);
}

나머지 변환디렉토리, 필터 등의 설정은 __construct($config)에 배열로 전달해서 해결할 수 있을 것 같네요..
09-07-14 22:38
미바니 어익후~ 제가 실력이 아직 미천한 나머지
머가 맞고 틀린지도 모르고 사용하기에만 급급해 버렸나 봅니다.

저는 언제쯤 관리자님 실력이 되려는지 ^^

Zend를 최근에 써보는 중이라
관리자님의 가르침을 이어받아 좀더 공부하겠습니다.^^

근데 갑자기 성함이 궁금해지네요 ㅎ
09-07-16 02:38
    이름
비밀번호
 
Since 2003-03-03 hosted on vultr.com