如何在视图中访问模型 - Symfony 2

时间:2013-10-09 15:56:02

标签: php symfony domain-object

我有以下型号:

class Person
{
    public $name;
    function __Construct( $name )
    {
        $this->name = $name;
    }
}

我有以下控制器:

class NavigationController extends Controller
{
    public function indexAction()
    {
        $people = array(
            new Person("James"),
            new Person("Bob")
        );
        return $this->render('FrameworkBundle:Navigation:index.html.php', $people);
    }
}

如何在视图中访问模型数组。有没有办法直接访问模型,或者我必须分配如下属性:?

class NavigationController extends Controller
{
    public function indexAction()
    {
        $people = array(
            new Person("James"),
            new Person("Bob")
        );
        return $this->render('FrameworkBundle:Navigation:index.html.php', array( "model" => $people ) );
    }
}

查看:

<?php 
    foreach( $model as $person )
    {
       echo $person->title;
    }
?>

上述问题是用户可以将其更改为

return $this->render( 'FrameworkBundle:Navigation:index.html.php', array( "marybloomingpoppin" => $people ) );

1 个答案:

答案 0 :(得分:0)

使用您使用的示例视图,您已经拥有了正确的实现:

class NavigationController extends Controller
{
    public function indexAction()
    {
        $people = array(
            new Person("James"),
            new Person("Bob")
        );
        return $this->render('FrameworkBundle:Navigation:index.html.php', array( "model" => $people ) );
    }
}

你提到了有人可能会改变控制器中的赋值的问题,但是如果有人只在一个地方而不是在所有地方更改变量的名称,那么这就是你总是有的。所以我不认为这是一个问题。