umanit/doctrine-singleton-bundle

与 Doctrine 和 Sonata 一起工作的单例实体

2.0.3 2023-01-12 16:10 UTC

This package is auto-updated.

Last update: 2024-09-12 19:52:45 UTC


README

本插件旨在轻松创建复杂的单例实体(完全独特或基于某些属性)。与 Sonata Admin 兼容,并具有自动集成功能。

安装

将插件注册到您的 'app/AppKernel.php'

    new Umanit\DoctrineSingletonBundle\UmanitDoctrineSingletonBundle(),

这就完成了!

使用方法

告知实体是单例的

只需实现 Umanit\DoctrineSingletonBundle\Model\SingletonInterface

<?php

namespace App\Entity\Content;

use Doctrine\ORM\Mapping as ORM;
use Umanit\DoctrineSingletonBundle\Model\SingletonInterface;

#[ORM\Table(name="page")]
class Page implements SingletonInterface 
{
}

现在,如果您尝试创建两个类型为 "Page" 的实体,您将得到一个 NonUniqueException

更复杂的唯一性

如果您想实现更复杂的唯一性,例如,希望实体按本地唯一,您可以通过订阅 FilterSingletonEvent::SINGLETON_FILTER_EVENT 事件来修改 filters(在 findBy() 子句中使用 filters)

例如(来自 TranslationBundle

 <?php

namespace Umanit\TranslationBundle\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Umanit\DoctrineSingletonBundle\Event\FilterSingletonEvent;
use Umanit\TranslationBundle\Doctrine\Model\TranslatableInterface;

class SingletonSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return [FilterSingletonEvent::SINGLETON_FILTER_EVENT => ['onFilterEvent']];
    }

    public function onFilterEvent(FilterSingletonEvent $event)
    {
        $entity  = $event->getEntity();
        $filters = $event->getFilters();

        if ($entity instanceof TranslatableInterface) {
            $filters['locale'] = $entity->getLocale();
        }

        $event->setFilters($filters);
    }
}

services.yml

 services:
    umanit_translation.event_subscriber.doctrine_singleton_filter:
        class: Umanit\TranslationBundle\EventSubscriber\SingletonSubscriber
        tags:
            - { name: kernel.event_subscriber } 

获取单例

要获取您的单例实例,您可以使用提供的辅助器在您的 PHP 代码或 twig 中使用

<?php

$this->get('umanit_doctrine_singleton.helper')->getSingleton('App\Entity\Page::class');
{% set singleton = get_singleton('App\\Entity\\Page') %}

方法 getSingleton($className, array $filters = [], $instantiateIfNotFound = false) 可以接受 1 到 3 个参数

  • $className : 要获取的类的完全限定名
  • $filters : 要应用于获取单例的过滤器(例如:getSingleton("MyClass", ["locale" => "en"])
  • $instantiateIfNotFound : 如果实体未找到,则返回空实体而不是 null

集成到 SonataAdmin

该插件将自动从列表和编辑视图中移除 addlist 按钮。

如果您将 UmanitDoctrineSingletonBundle:Sonata\SingletonCRUD 作为您的管理类控制器使用,如果没有找到实体,将重定向到 create,如果只有一个实体,将重定向到 edit,如果您有多个实体,将重定向到 list

例如

     app.admin.page:
         class: App\Admin\PageAdmin
         arguments: [~, App\Entity\Content\Page, UmanitDoctrineSingletonBundle:Sonata\SingletonCRUD ]
         tags:
             - { name: sonata.admin, manager_type: orm, group: 'Content', label: 'Page' }