0

I'm responsible for a rather large web app I built 8 years ago, then later refactored using ZF1 and now trying to move beyond that into more modern framework components. At the moment am trying to see if I can swap out Zend_View for Phalcon\Mvc\View\Simple without having to touch every .phtml file.

Problem I've run into is that while both assign a variable to the view in the same way (e.g. $this->view->foo = 'bar'), in Zend_View in the template you would <?=$this->foo;?> to print the var but in Phalcon it is <?=$foo;?>.

As I mentioned I don't want to go through each of several hundred .phtml files to remove $this->. Is there a way I can override Phalcon's render() or otherwise enable access to the view params using $this?

pavel
  • 26,538
  • 10
  • 45
  • 61
Chris442
  • 11
  • 2
  • Continuing to research this. So I think the answer is going to be in creating a custom View Engine... If I can solve it I'll post the solution. – Chris442 Jul 23 '14 at 13:22
  • After trial and error found a stupid-simple solution. Since newbies cannot answer their own questions for 8 hrs I'll post the code ASAP after. – Chris442 Jul 23 '14 at 15:33

2 Answers2

1

Here's what I came up with after fiddling with it all day. Simply extend the PHP view engine:

class Engine extends \Phalcon\Mvc\View\Engine\Php
{
    /**
     * Renders a view using the template engine
     *
     * @param   string  $path
     * @param   array   $params
     * @param   boolean $mustClean
     * @return  string
     */
    public function render($path, $params = null, $mustClean = null)
    {        
        /**
         * extract view params into current object scope 
         * so we can access them with <?=$this->foo;?>
         * Maintains backward compat with all the .phtml templates written for Zend_View
         */
        foreach($this->_view->getParamsToView() as $key => $val) {
            $this->$key = $val;
        }

        return parent::render($path, $params, $mustClean);        
    }
Chris442
  • 11
  • 2
0

You can use DI container to access any registered services in the view, so just put your variables into DI (in the action for example):

public function indexAction()
{
    $this->getDi()->set('hello', function() { return 'world'; });
    ...

And then use it in the template via $this variable:

<div>
    <?php echo $this->hello; ?>
</div>

P.S. This is not a good way to assign variables to the view, but should help in your particular case.

Phantom
  • 1,704
  • 4
  • 17
  • 32