Using Smarty with OOP: best practices?
| From: | Bharat Mediratta | Date: | Sun, 22 Sep 2002 06:15:36 +0000 |
| Subject: | Using Smarty with OOP: best practices? | ||
| Groups: | php.smarty.dev | ||
| Request: | Send a blank email to php-smarty-dev+get-277@lists.php.net to get a copy of this message | ||
Howdy. I'm writing the second version of Gallery, a PHP
based photo management program. In the rewrite, I'm using
Smarty heavily, and thus far I'm very pleased with its
functionality and performance. (good job, guys!) I'm
also new to this list; I scanned the archives and didn't
see this topic raised. Apologies if I'm flogging a dead
horse here.
G2 is completely object oriented. It's also designed so that
it can be wholly embedded inside another application like
PostNuke or Drupal, which means that it will have to coexist
peacefully with the unpredictable namespace of another
application. I want to provide plenty of features at
the template level, but I want to avoid polluting the global
namespace (function namespace, that is). I also want to be
able to provide much of the common behaviour for my
functions in a class so that when Gallery is ported to a new
environment we can simply extend the base class and override
the specific behaviours that are different.
My problem is that Smarty doesn't allow me to register class
methods as callback functions using $smarty->register_function.
What I'd really like is to be able to register a namespace
delegate. For example, if I could do something like this:
$delegate = new GalleryDelegate();
$smarty->register_delegate('gallery', $delegate);
Then inside the template I'd want to say:
{gallery.generateUrl arg="value"}
And have that get compiled down to the equivalent of:
$delegate->generateUrl(array('arg' => "value"));
In the meantime, to get around this issue, I register all
my callbacks to go to a single function, then tweaked the
compiler so that in the callback parameters it passes in
the name of the actual function that was being called as
part of the $params. This way I can have a single function
that receives all my callbacks, figures out which one was
actually executed and then delegates it to the correct class
method. More specifically, in Smarty_Compiler::_compile_custom_tag
and _compile_block_tag I added this line:
$arg_list[] = "'__function' => '$tag_command'";
then in my callback function I do something like this:
switch($params['__function']) {
case 'galleryUrl':
$adapter->generateUrl($params);
}
This basically lets me do my delegation, but it's a little
gnarly. I'd rather do it using the delegation scheme that
I outlined above.
Is there a better way to do this? If not, would you accept
a patch to implement my delegation scheme?
Thanks,
-Bharat