2010年10月29日星期五

Re: [fw-mvc] Auto HTML escaper module for Zend_View.

On 2010-10-29 5:51 pm, Matthew Weier O'Phinney wrote:
> -- chikaram<chikara.miyake@gmail.com> wrote
> (on Friday, 29 October 2010, 06:23 AM -0700):
>> I love ZendFramework and I wanted my team use it.
>> But that you couldn't escape vars in view automatically was its biggest
>> drawbacks.
>>
>> So I write this - auto HTML escaper module for Zend_View:
>> http://github.com/chikaram/gnix-view
> You may be interested in work I've been doing on Zend\View in ZF2. In
> that component, I'm separating variable storage into a separate object
> -- which makes auto-escaping trivial:
>
> echo $this->vars('foo'); // escaped
> echo $this->vars()->getRawValue('foo'); // unescaped
>
> It's also configurable, allowing you to disable auto-escaping if a
> particular context does not require it:
>
> $this->vars()->setIsStrict(false);
> echo $this->vars('foo'); // unescaped
>
> In ZF1, the only way to do auto-escaping requires extending Zend_View
> and doing some hackery in __get and getVars (and optionally __set).
> While it's do-able, it's non-trivial.

I don't know about the *only* way... What I did for a bit of an
experiment was to extend the Zend_View_Stream class and override the
stream_open method. It was essentially exactly the same, except that I
added this before the conversion of short tags to long:

$this->_data = preg_replace(
'/\<\?\=~ (.*?);? \?>/',
'<?php echo $this->escape($1); ?>',
$this->_data
);

Then all that had to be done was to register the zend.view stream
wrapper before I knew ZF did:

stream_register_wrapper('zend.view', 'MyStream');

and in any views I just had to do:

<?=~ $this->foo; ?>

Of course, it introduced a non-standard php tag in to the views, but it
was OK in this instance because 1) it was just an experiment, and 2) the
code was for wholly in-house applications and none of it distributed, so
I didn't really have to worry about compatibility, short tags,
non-standard php tags, etc. But it did work like a charm!

Andy

没有评论: