哪里定义与在Symfony2的实体静态数组? [英] Where to define static array related to an entity in symfony2 ?

查看:139
本文介绍了哪里定义与在Symfony2的实体静态数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组包含与实体的静态数据的产品

I have an array contains static data related to an entity Product:

public static $category = array(
    1 => 'animal.png',
    2 => 'blague.png',
    3 => 'devinette.png',
    4 => 'enfant.png',
    5 => 'h-f.png',
    6 => 'nationalite.png',
    7 => 'politique.png',
    8 => 'sport.png',
    9 => 'name',
    10 => 'travail.png',
    11 => 'vulgaire.png',
    12 => 'autre.png',
);

我应该声明数组?

Where i should declare the array ?

和如何从树枝视图加入数据?

And how i can accede to data from the Twig view ?

感谢

推荐答案

我不知道这是最好的方式,但我使用了类似的东西到code:

I don't know if that's the best way but I used something similar to your code:

class Product
{
    protected static $category = array( 
        1 => 'animal.png',
        2 => 'blague.png',
        3 => 'devinette.png',
        // ...
        )
    );
}

然后你就可以在这个类中,以获得来自阵列数据添加一些功能

Then you can add some functions in this class in order to get data from the array

    public function getCategoryImageFromIndex($a)
    {
        return self::$category[$a];
    }

    // if you have a getter getCategory() which returns the category of the Product
    public function getCategoryImage()
    {
        return self::$category[$this->getCategory()];
    }

然后就可以从枝杈调用这些函数:

Then you can call these functions from Twig:

{{ product.categoryImageFromIndex(1) }}

将显示:

animal.png

animal.png

{{ product.categoryImage }}

将显示在类别相应的图像。

will display the corresponding image from the category.

这篇关于哪里定义与在Symfony2的实体静态数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆