petegore / doctrine-behaviors
Doctrine2 行为特性
Requires
- php: >=5.4
- behat/transliterator: ~1.0
- doctrine/common: >=2.2
- ramsey/uuid: ^3.5
Requires (Dev)
- ext-pdo_mysql: *
- ext-pdo_pgsql: *
- ext-pdo_sqlite: *
- doctrine/orm: >=2.2
- hexmedia/yaml-linter: ~0.1
- jakub-onderka/php-parallel-lint: ~0.8
- phpunit/phpunit: ~4.8
Suggests
- symfony/framework-bundle: To be able to use it as a bundle
This package is not auto-updated.
Last update: 2024-09-28 19:09:49 UTC
README
这是一个PHP >=5.4 库,包含一组特性和接口,用于给Doctrine2实体和存储库添加行为。
它与基础Knp/DoctrineBehaviours完全相同,并添加了Uuidable特性。
它目前处理以下内容
- blameable
- filterable
- geocodable
- joinable
- loggable
- sluggable
- softDeletable
- sortable
- timestampable
- translatable
- tree
- [uuidable] (#uuidable)
注意
一些行为(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, ORMBehaviors\Uuidable\Uuidable ; /** * @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,您现在可以使用translate或getTranslations方法进行翻译。
<?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();
覆盖
如果您希望为翻译实体使用不同的类名,或者想要使用单独的命名空间,您有两种方法
如果您想为全局定义自定义翻译实体类名
覆盖翻译实体中的Translatable特性及其方法getTranslationEntityClass,以及Translation特性及其方法getTranslatableEntityClass。如果您覆盖了一个,您还需要覆盖另一个以返回相反的类。
示例:假设您想创建一个子命名空间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();
如果您希望更改为时间戳模型创建的数据库字段的数据类型,您可以将以下参数设置为如下所示:
parameters: knp.doctrine_behaviors.timestampable_subscriber.db_field_type: datetimetz
datetimetz 如果您正在使用 PostgreSQL 数据库,这是一个非常有用的选项,否则您可能会遇到一些时区问题。有关更多信息,请参阅:[http://doctrine-dbal.readthedocs.org/en/latest/reference/known-vendor-issues.html#datetime-datetimetz-and-time-types](http://doctrine-dbal.readthedocs.org/en/latest/reference/known-vendor-issues.html#datetime-datetimetz-and-time-types)
默认类型是 datetime。
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
可记录的功能能够跟踪生命周期更改并将它们记录到任何第三方日志系统中。一个可记录的 调用 用于从任何地方获取记录器。
<?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
可地理编码的功能为 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
可缩写生成实体的缩写(唯一性不可保证)。将在更新/持久化时自动生成(您可以通过覆盖 getRegenerateSlugOnUpdate 并返回 false 来禁用更新生成。您还可以通过覆盖 getSlugDelimiter 从默认的破折号覆盖缩写分隔符。您可以通过覆盖 generateSlugValue 来更改缩写生成算法。用例包括 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
可过滤的功能可以在仓库级别使用
它允许我们简单地过滤结果
连接过滤示例
<?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']);
uuidable
Uuidable 为实体生成 uuid4(唯一性不可保证)。将在持久化时自动生成。
<?php use Doctrine\ORM\Mapping as ORM; use Knp\DoctrineBehaviors\Model as ORMBehaviors; /** * @ORM\Entity */ class BlogPost { use ORMBehaviors\Uuidable\Uuidable; }
调用
调用由一些订阅者(如 blameable 和 geocodable)使用,以根据第三方系统填充信息。
例如,可追究责任的调用者可以是实现__invoke方法的任何symfony2服务或任何匿名函数,只要它们返回当前登录用户的表示(这意味着一切,一个用户实体,一个字符串,一个用户名等)。关于被调用的DI服务的示例,请查看Knp\DoctrineBehaviors\ORM\Blameable\UserCallable类。
对于可地理编码的情况,您可以将其设置为任何实现__invoke的服务或返回Knp\DoctrineBehaviors\ORM\Geocodable\Type\Point对象的匿名函数。