Symfony2:几个用于访问存储在数据库中的名称值的捆绑包


Symfony2: several bundles to access name values stored in a database

我是Symfony2

的新手,我正在将旧的Symfony1应用程序移植到v2。

在我的旧应用程序中,我在一个很大的YML文件中定义了我所有的模型。因此,各种"组件"能够引用相同的名称值对(存储在 YML 文件中)。

我现在正在将功能分解到捆绑包中,并且我想完全分离捆绑包。我仍然需要访问名称值对,但我想集中存储它 - 这次在数据库中。

我想保持我的代码干燥,因此想编写代码以仅访问一次名称值对,以及如何在单独的捆绑包中使用它。

我还想提供集中的 CRUD 工具来维护名称值对。

总而言之,我的两个问题如下:

  1. 如何提供功能(实现一次)来访问存储在数据库中的名称值对,并使此功能可供需要它的捆绑包使用?

  2. 提供 CRUD 功能以维护名称值对的最佳方法是什么?(是通过创建另一个捆绑包吗?我不确定

  1. 您可以创建 Doctrine 实体并请求所需的密钥。为了编写 DRY 代码,请使用基实体并将其扩展到每个对类型:

    Pair实体:

    namespace MyBundle'Entity;
    use Doctrine'ORM'Mapping as ORM;
    /**
     * @MappedSuperclass
     */
    class Pair
    {
        /**
         * @Column(type="string", unique=true)
         * @var string
         */
        protected $name;
        /**
         * @Column(type="string")
         * @var string
         */
        protected $value;
        // Getters & setters
        // ...
    }
    

    SportPair实体:

    namespace MyBundle'Entity;
    use Doctrine'ORM'Mapping as ORM;
    /**
     * @Entity(repositoryClass="MyBundle'Entity'PairRepository")
     * @Table(name="sport_pairs")
     */
    class SportPair extends Pair
    {
        /**
         * @Id
         * @GeneratedValue(strategy="AUTO")
         * @Column(name="id", type="integer")
         * @var int
         */
        protected $id;
    }
    

    Pair存储库:

    namespace MyBundle'Entity;
    use Doctrine'ORM'EntityRepository;
    class PairRepository extends EntityRepository
    {
        private $cache = array();
        public function getValue($key)
        {
            if (!isset($this->cache[$key])) {
                $pair = $this->findOneBy(array('name' => $key));
                if (null !== $pair) {
                    $this->cache[$key] = $pair->getValue();
                }
            }
            return $this->cache[$key];
        }
    }
    
  2. 使用SensioGenerationBundle生成 CRUD 以管理Pair实体。


这就是您应该如何进行:

  1. 创建应用程序捆绑包 ( MyAppBundle )。
  2. 可选)创建共享捆绑包 ( MySharedBundle
  3. 将捆绑包引用到应用程序内核中。
  4. 创建PairPairRepository MyAppBundle
  5. (可选)将这些类移动到MySharedBundle
  6. 将派生对类创建到MyAppBundle 中。