<?php /* * User view file * @var User $user * @var CController $this */ ?> <h1><?php echo CHtml::link(CHtml::encode($user->name),array("/user/view", "id" => $user->id))); ?></h1> <p>Some Text</p> <?php if ($user->status == "active") { echo "This user is active"; if ($someOtherCondition) { // do something else } } else { echo "This user is not active"; } ?> <br /> <?php echo CHtml::link("Some Label", "#fish"); echo "Current Controller ID: ".$this->getId(); $this->widget("myCustomWidget", array("foo" => "bar")); ?>
I think it would be useful to introduce a specialized View class so that this kind of logic, which relates only to one or two specific views can be encapsulated outside of the template itself. This makes it easier for designers to work with views, and for views to be localized. The base view class could also provide access to the current CHtml methods, which would make it easy to replace CHtml with your own class, solving a lot of the issues regarding supporting different CSS frameworks. Importantly, it also makes it much easier to test your views without relying on selenium.
<?php /** * User view helper */ class UserView extends CView { public $someOtherCondition = true; public function displayUserStatus($user) { if ($user->status == "active") { return "This user is active".($this->someOtherCondition ? $this->doSomethingElse() : ""); } else { return "This user is inactive"; } } public function doSomethingElse() { return "foo"; } public function userLink($user) { return $this->link($this->encode($user->name),array("/user/view", "id" => $user->id)); } } ?> <?php /** * User view file * @var User $user * @var UserView $this */ ?> <h1><?php echo $this->displayUserLink($user); ?></h1> <p>Some Text</p> <?php echo $this->displayUserStatus($user); ?> <br /> <?php echo $this->link("Some Label", "#fish"); echo "Current Controller ID: ".$this->controller->getId(); // still provide access to the controller if required $this->widget("myCustomWidget", array("foo" => "bar")); // views can render widgets just like controllers do now ?>