aqarmap/doctrine-behaviors

Doctrine2 行为特性


README

Build Status

这是一个 PHP >=5.4 库,它包含了一系列特性接口,可以为 Doctrine2 实体和存储库添加行为。

它目前处理以下行为:

本项目正在寻找维护者

我们意识到,我们不再有那么多时间来维护这个项目,正如它应该被维护的那样。因此,我们正在寻找维护者。如果你想要继续工作在这个项目上,请打开一个 issue。

注意

一些行为(translatable、timestampable、softDeletable、blameable、geocodable)需要 Doctrine 订阅者才能工作。请确保通过阅读订阅者部分来激活它们。

安装

composer require knplabs/doctrine-behaviors:~1.1

配置

默认情况下,当与 Symfony 集成时,所有订阅者都已被启用(如果你没有为包指定任何配置)。但你可以通过白名单的方式启用你需要的特性

knp_doctrine_behaviors:
    blameable:      false
    geocodable:     ~     # Here null is converted to false
    loggable:       ~
    sluggable:      true
    soft_deletable: true
    # All others behaviors are disabled

订阅者

如果你使用 symfony2,你可以轻松地将它们注册在

  • 推荐方式

添加到 AppKernel

class AppKernel
{
    function registerBundles()
    {
        $bundles = array(
            //...
            new Knp\DoctrineBehaviors\Bundle\DoctrineBehaviorsBundle(),
            //...
        );

        //...

        return $bundles;
    }
}
  • 已弃用方式: 导入服务定义文件
    # app/config/config.yml
    imports:
        - { resource: ../../vendor/knplabs/doctrine-behaviors/config/orm-services.yml }

你还可以使用 doctrine2 api 注册它们

<?php

$em->getEventManager()->addEventSubscriber(new \Knp\DoctrineBehaviors\ORM\Translatable\TranslatableSubscriber);
// register more if needed

使用方法

你所要做的就是定义一个 Doctrine2 实体并使用特性

<?php

use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Model as ORMBehaviors;

/**
 * @ORM\Entity(repositoryClass="CategoryRepository")
 */
class Category implements ORMBehaviors\Tree\NodeInterface, \ArrayAccess
{
    use ORMBehaviors\Blameable\Blameable,
        ORMBehaviors\Geocodable\Geocodable,
        ORMBehaviors\Loggable\Loggable,
        ORMBehaviors\Sluggable\Sluggable,
        ORMBehaviors\SoftDeletable\SoftDeletable,
        ORMBehaviors\Sortable\Sortable,
        ORMBehaviors\Timestampable\Timestampable,
        ORMBehaviors\Translatable\Translatable,
        ORMBehaviors\Tree\Node
    ;

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="NONE")
     */
    protected $id;
}

对于像 tree 这样的某些行为,你可以使用存储库特性

<?php

use Doctrine\ORM\EntityRepository;
use Knp\DoctrineBehaviors\ORM as ORMBehaviors;

class CategoryRepository extends EntityRepository
{
    use ORMBehaviors\Tree\Tree,
}

就这样!

你现在有一个工作的 Category,其行为如下:

tree

<?php

    $category = new Category;
    $category->setId(1); // tree nodes need an id to construct path.
    $child = new Category;
    $child->setId(2);

    $child->setChildNodeOf($category);

    $em->persist($child);
    $em->persist($category);
    $em->flush();

    $root = $em->getRepository('Category')->getTree();

    $root->getParentNode(); // null
    $root->getChildNodes(); // ArrayCollection
    $root[0][1]; // node or null
    $root->isLeafNode(); // boolean
    $root->isRootNode(); // boolean

你可以使用除了 id 之外的其他标识符,只需重写 getNodeId 并返回你的自定义标识符(与 Sluggable 结合使用效果极佳)

translatable

如果你正在处理 Category 实体,默认情况下,Translatable 行为期望在 Category 实体相同的文件夹中有一个 CategoryTranslation 实体。

默认的命名约定(或通过特性方法的定制)可以避免你手动处理实体关联。它将由 TranslationSubscriber 自动处理。

为了使用 Translatable 特性,你必须创建这个 CategoryTranslation 实体。

<?php

use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Model as ORMBehaviors;

/**
 * @ORM\Entity
 */
class CategoryTranslation
{
    use ORMBehaviors\Translatable\Translation;

    /**
     * @ORM\Column(type="string", length=255)
     */
    protected $name;

    /**
     * @ORM\Column(type="string", length=255)
     */
    protected $description;

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param  string
     * @return null
     */
    public function setName($name)
    {
        $this->name = $name;
    }

    /**
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * @param  string
     * @return null
     */
    public function setDescription($description)
    {
        $this->description = $description;
    }
}

相应的 Category 实体需要 use ORMBehaviors\Translatable\Translatable; 并应只包含你不需要翻译的字段。

<?php

use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Model as ORMBehaviors;

/**
 * @ORM\Entity
 */
class Category
{
    use ORMBehaviors\Translatable\Translatable;

    /**
     * @ORM\Column(type="string", length=255)
     */
    protected $someFieldYouDoNotNeedToTranslate;
}

更新数据库后,即使用 ./console doctrine:schema:update --force,你现在可以使用 translategetTranslations 方法来处理翻译。

<?php

    $category = new Category;
    $category->translate('fr')->setName('Chaussures');
    $category->translate('en')->setName('Shoes');
    $em->persist($category);

    // In order to persist new translations, call mergeNewTranslations method, before flush
    $category->mergeNewTranslations();

    $category->translate('en')->getName();

重写

如果你更喜欢为翻译实体使用不同的类名,或者想要使用单独的命名空间,你有两种方法

如果你想要全局定义一个自定义翻译实体类名
重写翻译实体中的 trait TranslatablegetTranslationEntityClass 方法以及 TranslationgetTranslatableEntityClass 方法。如果你重写了一个,你也需要重写另一个以返回相反的类。

示例:假设你想创建一个子命名空间 AppBundle\Entity\Translation 来存储翻译类,然后在那个文件夹中放置重写的特性。

<?php
namespace AppBundle\Entity\Translation;

use Knp\DoctrineBehaviors\Model\Translatable\Translatable;
use Symfony\Component\PropertyAccess\PropertyAccess;

trait TranslatableTrait
{
    use Translatable;

    /**
     * @inheritdoc
     */
    public static function getTranslationEntityClass()
    {
        $explodedNamespace = explode('\\', __CLASS__);
        $entityClass = array_pop($explodedNamespace);
        return '\\'.implode('\\', $explodedNamespace).'\\Translation\\'.$entityClass.'Translation';
    }
}
<?php
namespace AppBundle\Entity\Translation;

use Knp\DoctrineBehaviors\Model\Translatable\Translation;

trait TranslationTrait
{
    use Translation;

    /**
     * @inheritdoc
     */
    public static function getTranslatableEntityClass()
    {
        $explodedNamespace = explode('\\', __CLASS__);
        $entityClass = array_pop($explodedNamespace);
        // Remove Translation namespace
        array_pop($explodedNamespace);
        return '\\'.implode('\\', $explodedNamespace).'\\'.substr($entityClass, 0, -11);
    }
}

如果你使用这种方式,请确保重写 DoctrineBehaviors 的特性参数

parameters:
    knp.doctrine_behaviors.translatable_subscriber.translatable_trait: AppBundle\Entity\Translation\TranslatableTrait
    knp.doctrine_behaviors.translatable_subscriber.translation_trait: AppBundle\Entity\Translation\TranslationTrait

如果您只想为单个可翻译类定义自定义翻译实体类名
在可翻译实体中重写getTranslationEntityClass方法,在翻译实体中重写getTranslatableEntityClass方法。如果重写了一个,也需要重写另一个以返回相反的类。

猜测当前区域设置

您可以通过将其第一个参数设置为可调用的方式来配置订阅者猜测当前区域设置的方式。此库提供了一个可调用的对象(Knp\DoctrineBehaviors\ORM\Translatable\CurrentLocaleCallable),它使用Symfony2返回当前区域设置。

代理翻译

一个额外功能允许您代理可翻译实体的翻译字段。

您可以在可翻译实体的__call魔法方法中使用它,这样当您尝试调用getName(例如)时,它将返回当前区域设置下名称的翻译值。

<?php

    public function __call($method, $arguments)
    {
        return $this->proxyCurrentLocaleTranslation($method, $arguments);
    }
    
    // or do it with PropertyAccessor that ships with Symfony SE
    // if your methods don't take any required arguments
    public function __call($method, $arguments)
    {
        return \Symfony\Component\PropertyAccess\PropertyAccess::createPropertyAccessor()->getValue($this->translate(), $method);
    }

软删除

<?php

    $category = new Category;
    $em->persist($category);
    $em->flush();

    // get id
    $id = $category->getId();

    // now remove it
    $em->remove($category);
    $em->flush();

    // hey, I'm still here:
    $category = $em->getRepository('Category')->findOneById($id);

    // but I'm "deleted"
    $category->isDeleted(); // === true

    // restore me
    $category->restore();

    //look ma, I am back
    $category->isDeleted(); // === false

    //do not forget to call flush method to apply the change
    $em->flush();
<?php

    $category = new Category;
    $em->persist($category);
    $em->flush();

    // I'll delete you tomorrow
    $category->setDeletedAt((new \DateTime())->modify('+1 day'));

    // OK, I'm here
    $category->isDeleted(); // === false

    /*
     *  24 hours later...
     */

    // OK, I'm deleted
    $category->isDeleted(); // === true

timestampable

<?php

    $category = new Category;
    $em->persist($category);
    $em->flush();

    $id = $category->getId();
    $category = $em->getRepository('Category')->findOneById($id);

    $category->getCreatedAt();
    $category->getUpdatedAt();

如果您希望更改将创建用于时间戳模型的数据库名字段的doctrine类型,您可以设置以下参数,如下所示

parameters:
    knp.doctrine_behaviors.timestampable_subscriber.db_field_type: datetimetz

datetimetz如果您正在使用Postgres数据库,这是一个很有用的选择,否则您可能会遇到一些时区问题。有关更多信息,请参阅:http://doctrine-dbal.readthedocs.org/en/latest/reference/known-vendor-issues.html#datetime-datetimetz-and-time-types

默认类型是datetime

blameable

Blameable能够跟踪特定实体的创建者和更新者。一个blameable可调用的用于从您的应用程序中获取当前用户。

如果您使用Doctrine实体来表示您的用户,您可以配置订阅者自动管理此用户实体与您的实体之间的关联。

使用symfony2,您只需配置名为%knp.doctrine_behaviors.blameable_subscriber.user_entity%的DI参数,例如

# app/config/config.yml
parameters:
    knp.doctrine_behaviors.blameable_subscriber.user_entity: AppBundle\Entity\User

然后,您可以使用它如下

<?php

    $category = new Category;
    $em->persist($category);

    // instances of %knp.doctrine_behaviors.blameable_subscriber.user_entity%
    $creator = $category->getCreatedBy();
    $updater = $category->getUpdatedBy();

loggable

Loggable能够跟踪生命周期修改并将它们记录到任何第三方日志系统中。一个loggable可调用的用于从您想要的位置获取记录器。

<?php

/**
 * @ORM\Entity
 */
class Category
{
    use ORMBehaviors\Loggable\Loggable;

    // you can override the default log messages defined in trait:
    public function getUpdateLogMessage(array $changeSets = [])
    {
        return 'Changed: '.print_r($changeSets, true);
    }

    public function getRemoveLogMessage()
    {
        return 'removed!';
    }
}

然后,将这些消息传递到配置的可调用对象。您可以通过向LoggableSubscriber传递另一个可调用来定义自己的。

<?php

$em->getEventManager()->addEventSubscriber(
    new \Knp\DoctrineBehaviors\ORM\Loggable\LoggableSubscriber(
        new ClassAnalyzer,
        function($message) {
            // do stuff with message
        }
    )
);

如果您使用symfony,您也可以配置要使用哪个可调用对象

// app/config/config.yml
parameters:
    knp.doctrine_behaviors.loggable_subscriber.logger_callable.class: Your\InvokableClass

geocodable

Geocodable为PostgreSQL平台提供扩展,以便与cube和earthdistance扩展一起使用。

它允许您根据地理坐标查询实体。它还提供了一个简单的入口点来使用第三方库,例如出色的geocoder将地址转换为纬度和经度。

<?php

    $geocoder = new \Geocoder\Geocoder;
    // register geocoder providers

    // $subscriber instanceof GeocodableSubscriber (add "knp.doctrine_behaviors.geocodable_subscriber" into your services.yml)
    $subscriber->setGeolocationCallable(function($entity) use($geocoder) {
        $location = $geocoder->geocode($entity->getAddress());
        return new Point(
            $location->getLatitude(),
            $location->getLongitude()
        ));
    });

    $category = new Category;
    $em->persist($category);

    $location = $category->getLocation(); // instanceof Point

    // find cities in a circle of 500 km around point 47 lon., 7 lat.
    $nearCities = $repository->findByDistance(new Point(47, 7), 500);

sluggable

Sluggable为实体生成slugs(唯一性不保证)。将在更新/持久化时自动生成(您可以覆盖getRegenerateSlugOnUpdate以返回false来禁用更新生成。您还可以通过覆盖getSlugDelimiter从默认的连字符重写slug分隔符。可以通过覆盖generateSlugValue更改slug生成算法。用例包括SEO(即如http://example.com/post/3/introduction-to-php的URL)

<?php

use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Model as ORMBehaviors;

/**
 * @ORM\Entity
 */
class BlogPost
{
    use ORMBehaviors\Sluggable\Sluggable;

    /**
     * @ORM\Column(type="string")
     */
    protected $title;

    public function getSluggableFields()
    {
        return [ 'title' ];
    }

    public function generateSlugValue($values)
    {
        return implode('-', $values);
    }
}

filterable

Filterable可以在Repository级别使用

它允许简单地过滤结果

连接过滤示例

<?php

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="ProductRepository")
 */
class ProductEntity
{

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(type="string", nullable=true)
     */
    private $name;

    /**
     * @ORM\Column(type="integer")
     */
    private $code;

    /**
     * @ORM\OneToMany(targetEntity="Order", mappedBy="product")
     */
    protected $orders;
}

和仓库

<?php

use Knp\DoctrineBehaviors\ORM\Filterable;
use Doctrine\ORM\EntityRepository;

class ProductRepository extends EntityRepository
{
    use Filterable\FilterableRepository;

    public function getLikeFilterColumns()
    {
        return ['e:name', 'o:code'];
    }

    public function getEqualFilterColumns()
    {
        return [];
    }

    protected function createFilterQueryBuilder()
    {
        return $this
            ->createQueryBuilder('e')
            ->leftJoin('e.orders', 'o');
    }
}

现在我们可以使用以下方式过滤

    $products = $em->getRepository('Product')->filterBy(['o:code' => '21']);

可调用对象

可调用对象被一些订阅者(如blameable和geocodable)使用,根据第三方系统填充信息。

例如,可追责的可调用对象可以是任何实现了 __invoke 方法的 symfony2 服务或者任何匿名函数,只要它们返回当前登录用户的表示(这意味着一切,一个用户实体、一个字符串、一个用户名等)。关于被调用的依赖注入服务的示例,请查看 Knp\DoctrineBehaviors\ORM\Blameable\UserCallable 类。

对于可地理编码的情况,你可以将其设置为任何实现了 __invoke 的服务或返回 Knp\DoctrineBehaviors\ORM\Geocodable\Type\Point 对象的匿名函数。

测试

阅读测试文档