Bind section lambdas? #125

Closed
wants to merge 1 commit into from

2 participants

@bobthecow
Owner

In PHP 5.4, we can re-bind Closures, essentially giving them a new $this internally. This change does that for higher order sections (section lambdas). Which means we can use this:

<?php
$data = array(
  'foo' => 'win',
  'embiggen' => function($text) {
    return strtoupper($this->render($text));
  },
);

instead of this:

<?php
$data = array(
  'foo' => 'win',
  'embiggen' => function($text, $mustache) {
    return strtoupper($mustache->render($text));
  },
);

My question is: is this a good thing? Should it be optional? Should it even be offered?

Pros:

  • It saves a bit of typing.
  • $this->render seems like a natural fit if you think of the Closure as the context of the section.
  • $this could potentially expose other things to the section lambda in the future, such as the current indent level of the template.

Cons:

  • (if always-enabled) it prevents more advanced Closure usage, for example, having a ViewModel object bind the closures it returns to itself, giving them access to private or protected members.
  • (if configurable) it presents an interesting — and possibly hard to track down — situation when the engine instantiation changes. Trying to figure out why $this isn't what you expect it to be is sometimes really confusing, c.f. JavaScript :)
  • (if configurable) it is yet another configuration option, but one that's only available for some versions of PHP.
  • Other future things (indent level, etc) could also be exposed via the $mustache argument passed to the Closure.

Neutral:

  • Because it's compiled-in, it doesn't have a measurable effect on performance either way.
  • This shortcut is not available for non-Closure callables, e.g. the array($this, 'doFoo') style callables.

See #101

Please discuss.

@bobthecow Bind section lambdas to the helper for PHP >= 5.4
This means you can call `$this->render()` from inside a section lambda closure.

See #101
6cbaf8a
@bobthecow
Owner

In retrospect, this is not a good idea. :)

@bobthecow bobthecow closed this Dec 11, 2012
@arrowplum

Would you consider making the LambdaHelper->context accessible from the callback? There are certain cases where it would be helpful to add to the context from the helper.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment