1

Smarty allows to access object properties using this syntax in templates:

{$object->property}

But (If I understood this correctly) this is possible only if property visibility is public, otherwise it seems that Smarty won't be able to access it.

In Java I'm used to create objects that have private properties, and I usually read/write these properties in business logic using getters and setters. But, even if I create an object with a private property, I'm able to access it in a jsp using expression language:

${object.property}

This won't happen in Smarty templates, since private properties cannot be accessed this way. So I would have to use a syntax like:

{$object->getProperty()}

Why is that? Why doesn't Smarty get round the problem as jsp EL does?

Kurt Bourbaki
  • 11,984
  • 6
  • 35
  • 53
  • 3
    I don't know about Smarty, but in Twig `foo.bar` causes to it to check whether `bar` is an index or property of `foo` and if not check for the methods `foo::bar()` and `foo::getBar()` automatically. If Smarty doesn't do that... it's just not very smarty. – deceze Dec 06 '13 at 10:15

1 Answers1

0

Reading and writing to private members of object from the outside violates OOP encapsulation principle. If you mark a member of class as private, you expect that no one except the code in the class (or friend functions) can access it.

Keeping as few public members as possible reduces dependencies between different code modules, making your application more flexible. If you can access private member of, let's say your model, your template must know internal implementation of the model. Making changes to your model will cost you a lot of time, because you would need to change your templates as well.

If you have getter and setter of your private member, you are free to change it as you like, template will know nothing.

ilnar
  • 1
  • 2
  • That's why I prefer to keep my variables `private`. But, since **Smarty** has got some difficulties to access them, what can I do? Should I use `{$object->getProperty()}` in my templates? – Kurt Bourbaki Dec 06 '13 at 10:46
  • 2
    Yes, I think the best solution is to use getters `{$object->getProperty()}`. – ilnar Dec 06 '13 at 10:54